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::*;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::{BTreeMap, HashSet};
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::codemap::FileName;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
68 use html::escape::Escape;
69 use html::format::{ConstnessSpace};
70 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
71 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
72 use html::format::fmt_impl_for_trait_page;
73 use html::item_type::ItemType;
74 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
75 use html::{highlight, layout};
77 /// A pair of name and its optional document.
78 pub type NameDoc = (String, Option<String>);
80 /// Major driving force in all rustdoc rendering. This contains information
81 /// about where in the tree-like hierarchy rendering is occurring and controls
82 /// how the current page is being rendered.
84 /// It is intended that this context is a lightweight object which can be fairly
85 /// easily cloned because it is cloned per work-job (about once per item in the
89 /// Current hierarchy of components leading down to what's currently being
91 pub current: Vec<String>,
92 /// The current destination folder of where HTML artifacts should be placed.
93 /// This changes as the context descends into the module hierarchy.
95 /// A flag, which when `true`, will render pages which redirect to the
96 /// real location of an item. This is used to allow external links to
97 /// publicly reused items to redirect to the right location.
98 pub render_redirect_pages: bool,
99 pub shared: Arc<SharedContext>,
102 pub struct SharedContext {
103 /// The path to the crate root source minus the file name.
104 /// Used for simplifying paths to the highlighted source code files.
105 pub src_root: PathBuf,
106 /// This describes the layout of each page, and is not modified after
107 /// creation of the context (contains info like the favicon and added html).
108 pub layout: layout::Layout,
109 /// This flag indicates whether [src] links should be generated or not. If
110 /// the source files are present in the html rendering, then this will be
112 pub include_sources: bool,
113 /// The local file sources we've emitted and their respective url-paths.
114 pub local_sources: FxHashMap<PathBuf, String>,
115 /// All the passes that were run on this crate.
116 pub passes: FxHashSet<String>,
117 /// The base-URL of the issue tracker for when an item has been tagged with
119 pub issue_tracker_base_url: Option<String>,
120 /// The given user css file which allow to customize the generated
121 /// documentation theme.
122 pub css_file_extension: Option<PathBuf>,
123 /// The directories that have already been created in this doc run. Used to reduce the number
124 /// of spurious `create_dir_all` calls.
125 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
126 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
127 /// should be ordered alphabetically or in order of appearance (in the source code).
128 pub sort_modules_alphabetically: bool,
129 /// Additional themes to be added to the generated docs.
130 pub themes: Vec<PathBuf>,
134 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
135 let mut dirs = self.created_dirs.borrow_mut();
136 if !dirs.contains(dst) {
137 fs::create_dir_all(dst)?;
138 dirs.insert(dst.to_path_buf());
146 /// Returns whether the `collapse-docs` pass was run on this crate.
147 pub fn was_collapsed(&self) -> bool {
148 self.passes.contains("collapse-docs")
151 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
152 /// `collapsed_doc_value` of the given item.
153 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
154 if self.was_collapsed() {
155 item.collapsed_doc_value().map(|s| s.into())
157 item.doc_value().map(|s| s.into())
162 /// Indicates where an external crate can be found.
163 pub enum ExternalLocation {
164 /// Remote URL root of the external crate
166 /// This external crate can be found in the local doc/ folder
168 /// The external crate could not be found.
172 /// Metadata about implementations for a type or trait.
175 pub impl_item: clean::Item,
179 fn inner_impl(&self) -> &clean::Impl {
180 match self.impl_item.inner {
181 clean::ImplItem(ref impl_) => impl_,
182 _ => panic!("non-impl item found in impl")
186 fn trait_did(&self) -> Option<DefId> {
187 self.inner_impl().trait_.def_id()
197 impl error::Error for Error {
198 fn description(&self) -> &str {
199 self.error.description()
203 impl Display for Error {
204 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
205 write!(f, "\"{}\": {}", self.file.display(), self.error)
210 pub fn new(e: io::Error, file: &Path) -> Error {
212 file: file.to_path_buf(),
218 macro_rules! try_none {
219 ($e:expr, $file:expr) => ({
223 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
229 macro_rules! try_err {
230 ($e:expr, $file:expr) => ({
233 Err(e) => return Err(Error::new(e, $file)),
238 /// This cache is used to store information about the `clean::Crate` being
239 /// rendered in order to provide more useful documentation. This contains
240 /// information like all implementors of a trait, all traits a type implements,
241 /// documentation for all known traits, etc.
243 /// This structure purposefully does not implement `Clone` because it's intended
244 /// to be a fairly large and expensive structure to clone. Instead this adheres
245 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
246 /// rendering threads.
249 /// Mapping of typaram ids to the name of the type parameter. This is used
250 /// when pretty-printing a type (so pretty printing doesn't have to
251 /// painfully maintain a context like this)
252 pub typarams: FxHashMap<DefId, String>,
254 /// Maps a type id to all known implementations for that type. This is only
255 /// recognized for intra-crate `ResolvedPath` types, and is used to print
256 /// out extra documentation on the page of an enum/struct.
258 /// The values of the map are a list of implementations and documentation
259 /// found on that implementation.
260 pub impls: FxHashMap<DefId, Vec<Impl>>,
262 /// Maintains a mapping of local crate node ids to the fully qualified name
263 /// and "short type description" of that node. This is used when generating
264 /// URLs when a type is being linked to. External paths are not located in
265 /// this map because the `External` type itself has all the information
267 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
269 /// Similar to `paths`, but only holds external paths. This is only used for
270 /// generating explicit hyperlinks to other crates.
271 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
273 /// This map contains information about all known traits of this crate.
274 /// Implementations of a crate should inherit the documentation of the
275 /// parent trait if no extra documentation is specified, and default methods
276 /// should show up in documentation about trait implementations.
277 pub traits: FxHashMap<DefId, clean::Trait>,
279 /// When rendering traits, it's often useful to be able to list all
280 /// implementors of the trait, and this mapping is exactly, that: a mapping
281 /// of trait ids to the list of known implementors of the trait
282 pub implementors: FxHashMap<DefId, Vec<Impl>>,
284 /// Cache of where external crate documentation can be found.
285 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
287 /// Cache of where documentation for primitives can be found.
288 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
290 // Note that external items for which `doc(hidden)` applies to are shown as
291 // non-reachable while local items aren't. This is because we're reusing
292 // the access levels from crateanalysis.
293 pub access_levels: Arc<AccessLevels<DefId>>,
295 /// The version of the crate being documented, if given fron the `--crate-version` flag.
296 pub crate_version: Option<String>,
298 // Private fields only used when initially crawling a crate to build a cache
301 parent_stack: Vec<DefId>,
302 parent_is_trait_impl: bool,
303 search_index: Vec<IndexItem>,
305 deref_trait_did: Option<DefId>,
306 deref_mut_trait_did: Option<DefId>,
307 owned_box_did: Option<DefId>,
308 masked_crates: FxHashSet<CrateNum>,
310 // In rare case where a structure is defined in one module but implemented
311 // in another, if the implementing module is parsed before defining module,
312 // then the fully qualified name of the structure isn't presented in `paths`
313 // yet when its implementation methods are being indexed. Caches such methods
314 // and their parent id here and indexes them at the end of crate parsing.
315 orphan_impl_items: Vec<(DefId, clean::Item)>,
318 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
319 /// Later on moved into `CACHE_KEY`.
321 pub struct RenderInfo {
322 pub inlined: FxHashSet<DefId>,
323 pub external_paths: ::core::ExternalPaths,
324 pub external_typarams: FxHashMap<DefId, String>,
325 pub deref_trait_did: Option<DefId>,
326 pub deref_mut_trait_did: Option<DefId>,
327 pub owned_box_did: Option<DefId>,
330 /// Helper struct to render all source code to HTML pages
331 struct SourceCollector<'a> {
332 scx: &'a mut SharedContext,
334 /// Root destination to place all HTML output into
338 /// Wrapper struct to render the source code of a file. This will do things like
339 /// adding line numbers to the left-hand side.
340 struct Source<'a>(&'a str);
342 // Helper structs for rendering items/sidebars and carrying along contextual
345 #[derive(Copy, Clone)]
348 item: &'a clean::Item,
351 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
353 /// Struct representing one entry in the JS search index. These are all emitted
354 /// by hand to a large JS file at the end of cache-creation.
360 parent: Option<DefId>,
361 parent_idx: Option<usize>,
362 search_type: Option<IndexItemFunctionType>,
365 impl ToJson for IndexItem {
366 fn to_json(&self) -> Json {
367 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
369 let mut data = Vec::with_capacity(6);
370 data.push((self.ty as usize).to_json());
371 data.push(self.name.to_json());
372 data.push(self.path.to_json());
373 data.push(self.desc.to_json());
374 data.push(self.parent_idx.to_json());
375 data.push(self.search_type.to_json());
381 /// A type used for the search index.
383 name: Option<String>,
384 generics: Option<Vec<String>>,
387 impl ToJson for Type {
388 fn to_json(&self) -> Json {
391 let mut data = BTreeMap::new();
392 data.insert("name".to_owned(), name.to_json());
393 if let Some(ref generics) = self.generics {
394 data.insert("generics".to_owned(), generics.to_json());
403 /// Full type of functions/methods in the search index.
404 struct IndexItemFunctionType {
409 impl ToJson for IndexItemFunctionType {
410 fn to_json(&self) -> Json {
411 // If we couldn't figure out a type, just write `null`.
412 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
415 let mut data = BTreeMap::new();
416 data.insert("inputs".to_owned(), self.inputs.to_json());
417 data.insert("output".to_owned(), self.output.to_json());
423 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
424 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
425 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
427 fn init_ids() -> FxHashMap<String, usize> {
443 ].into_iter().map(|id| (String::from(*id), 1)).collect()
446 /// This method resets the local table of used ID attributes. This is typically
447 /// used at the beginning of rendering an entire HTML page to reset from the
448 /// previous state (if any).
449 pub fn reset_ids(embedded: bool) {
450 USED_ID_MAP.with(|s| {
451 *s.borrow_mut() = if embedded {
459 pub fn derive_id(candidate: String) -> String {
460 USED_ID_MAP.with(|map| {
461 let id = match map.borrow_mut().get_mut(&candidate) {
464 let id = format!("{}-{}", candidate, *a);
470 map.borrow_mut().insert(id.clone(), 1);
475 /// Generates the documentation for `crate` into the directory `dst`
476 pub fn run(mut krate: clean::Crate,
477 external_html: &ExternalHtml,
478 playground_url: Option<String>,
480 passes: FxHashSet<String>,
481 css_file_extension: Option<PathBuf>,
482 renderinfo: RenderInfo,
483 sort_modules_alphabetically: bool,
484 themes: Vec<PathBuf>) -> Result<(), Error> {
485 let src_root = match krate.src {
486 FileName::Real(ref p) => match p.parent() {
487 Some(p) => p.to_path_buf(),
488 None => PathBuf::new(),
492 let mut scx = SharedContext {
495 include_sources: true,
496 local_sources: FxHashMap(),
497 issue_tracker_base_url: None,
498 layout: layout::Layout {
499 logo: "".to_string(),
500 favicon: "".to_string(),
501 external_html: external_html.clone(),
502 krate: krate.name.clone(),
504 css_file_extension: css_file_extension.clone(),
505 created_dirs: RefCell::new(FxHashSet()),
506 sort_modules_alphabetically,
510 // If user passed in `--playground-url` arg, we fill in crate name here
511 if let Some(url) = playground_url {
512 markdown::PLAYGROUND.with(|slot| {
513 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
517 // Crawl the crate attributes looking for attributes which control how we're
518 // going to emit HTML
519 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
520 for attr in attrs.lists("doc") {
521 let name = attr.name().map(|s| s.as_str());
522 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
523 (Some("html_favicon_url"), Some(s)) => {
524 scx.layout.favicon = s.to_string();
526 (Some("html_logo_url"), Some(s)) => {
527 scx.layout.logo = s.to_string();
529 (Some("html_playground_url"), Some(s)) => {
530 markdown::PLAYGROUND.with(|slot| {
531 let name = krate.name.clone();
532 *slot.borrow_mut() = Some((Some(name), s.to_string()));
535 (Some("issue_tracker_base_url"), Some(s)) => {
536 scx.issue_tracker_base_url = Some(s.to_string());
538 (Some("html_no_source"), None) if attr.is_word() => {
539 scx.include_sources = false;
545 try_err!(fs::create_dir_all(&dst), &dst);
546 krate = render_sources(&dst, &mut scx, krate)?;
550 render_redirect_pages: false,
551 shared: Arc::new(scx),
554 // Crawl the crate to build various caches used for the output
564 let external_paths = external_paths.into_iter()
565 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
568 let mut cache = Cache {
572 implementors: FxHashMap(),
574 parent_stack: Vec::new(),
575 search_index: Vec::new(),
576 parent_is_trait_impl: false,
577 extern_locations: FxHashMap(),
578 primitive_locations: FxHashMap(),
580 access_levels: krate.access_levels.clone(),
581 crate_version: krate.version.take(),
582 orphan_impl_items: Vec::new(),
583 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
587 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
588 typarams: external_typarams,
591 // Cache where all our extern crates are located
592 for &(n, ref e) in &krate.externs {
593 let src_root = match e.src {
594 FileName::Real(ref p) => match p.parent() {
595 Some(p) => p.to_path_buf(),
596 None => PathBuf::new(),
600 cache.extern_locations.insert(n, (e.name.clone(), src_root,
601 extern_location(e, &cx.dst)));
603 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
604 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
607 // Cache where all known primitives have their documentation located.
609 // Favor linking to as local extern as possible, so iterate all crates in
610 // reverse topological order.
611 for &(_, ref e) in krate.externs.iter().rev() {
612 for &(def_id, prim, _) in &e.primitives {
613 cache.primitive_locations.insert(prim, def_id);
616 for &(def_id, prim, _) in &krate.primitives {
617 cache.primitive_locations.insert(prim, def_id);
620 cache.stack.push(krate.name.clone());
621 krate = cache.fold_crate(krate);
623 // Build our search index
624 let index = build_index(&krate, &mut cache);
626 // Freeze the cache now that the index has been built. Put an Arc into TLS
627 // for future parallelization opportunities
628 let cache = Arc::new(cache);
629 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
630 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
632 write_shared(&cx, &krate, &*cache, index)?;
634 // And finally render the whole crate's documentation
638 /// Build the search index from the collected metadata
639 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
640 let mut nodeid_to_pathid = FxHashMap();
641 let mut crate_items = Vec::with_capacity(cache.search_index.len());
642 let mut crate_paths = Vec::<Json>::new();
644 let Cache { ref mut search_index,
645 ref orphan_impl_items,
646 ref mut paths, .. } = *cache;
648 // Attach all orphan items to the type's definition if the type
649 // has since been learned.
650 for &(did, ref item) in orphan_impl_items {
651 if let Some(&(ref fqp, _)) = paths.get(&did) {
652 search_index.push(IndexItem {
654 name: item.name.clone().unwrap(),
655 path: fqp[..fqp.len() - 1].join("::"),
656 desc: plain_summary_line(item.doc_value()),
659 search_type: get_index_search_type(&item),
664 // Reduce `NodeId` in paths into smaller sequential numbers,
665 // and prune the paths that do not appear in the index.
666 let mut lastpath = String::new();
667 let mut lastpathid = 0usize;
669 for item in search_index {
670 item.parent_idx = item.parent.map(|nodeid| {
671 if nodeid_to_pathid.contains_key(&nodeid) {
672 *nodeid_to_pathid.get(&nodeid).unwrap()
674 let pathid = lastpathid;
675 nodeid_to_pathid.insert(nodeid, pathid);
678 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
679 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
684 // Omit the parent path if it is same to that of the prior item.
685 if lastpath == item.path {
688 lastpath = item.path.clone();
690 crate_items.push(item.to_json());
693 let crate_doc = krate.module.as_ref().map(|module| {
694 plain_summary_line(module.doc_value())
695 }).unwrap_or(String::new());
697 let mut crate_data = BTreeMap::new();
698 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
699 crate_data.insert("items".to_owned(), Json::Array(crate_items));
700 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
702 // Collect the index into a string
703 format!("searchIndex[{}] = {};",
704 as_json(&krate.name),
705 Json::Object(crate_data))
708 fn write_shared(cx: &Context,
709 krate: &clean::Crate,
711 search_index: String) -> Result<(), Error> {
712 // Write out the shared files. Note that these are shared among all rustdoc
713 // docs placed in the output directory, so this needs to be a synchronized
714 // operation with respect to all other rustdocs running around.
715 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
717 // Add all the static files. These may already exist, but we just
718 // overwrite them anyway to make sure that they're fresh and up-to-date.
720 write(cx.dst.join("rustdoc.css"),
721 include_bytes!("static/rustdoc.css"))?;
723 // To avoid "main.css" to be overwritten, we'll first run over the received themes and only
724 // then we'll run over the "official" styles.
725 let mut themes: HashSet<String> = HashSet::new();
727 for entry in &cx.shared.themes {
728 let mut content = Vec::with_capacity(100000);
730 let mut f = try_err!(File::open(&entry), &entry);
731 try_err!(f.read_to_end(&mut content), &entry);
732 write(cx.dst.join(try_none!(entry.file_name(), &entry)), content.as_slice())?;
733 themes.insert(try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry).to_owned());
736 write(cx.dst.join("brush.svg"),
737 include_bytes!("static/brush.svg"))?;
738 write(cx.dst.join("main.css"),
739 include_bytes!("static/themes/main.css"))?;
740 themes.insert("main".to_owned());
741 write(cx.dst.join("dark.css"),
742 include_bytes!("static/themes/dark.css"))?;
743 themes.insert("dark".to_owned());
745 let mut themes: Vec<&String> = themes.iter().collect();
747 // To avoid theme switch latencies as much as possible, we put everything theme related
748 // at the beginning of the html files into another js file.
749 write(cx.dst.join("theme.js"), format!(
750 r#"var themes = document.getElementById("theme-choices");
751 var themePicker = document.getElementById("theme-picker");
752 themePicker.onclick = function() {{
753 if (themes.style.display === "block") {{
754 themes.style.display = "none";
755 themePicker.style.borderBottomRightRadius = "3px";
756 themePicker.style.borderBottomLeftRadius = "3px";
758 themes.style.display = "block";
759 themePicker.style.borderBottomRightRadius = "0";
760 themePicker.style.borderBottomLeftRadius = "0";
763 [{}].forEach(function(item) {{
764 var but = document.createElement('button');
765 but.innerHTML = item;
766 but.onclick = function(el) {{
767 switchTheme(currentTheme, mainTheme, item);
769 themes.appendChild(but);
772 .map(|s| format!("\"{}\"", s))
773 .collect::<Vec<String>>()
774 .join(",")).as_bytes())?;
776 write(cx.dst.join("main.js"), include_bytes!("static/main.js"))?;
777 write(cx.dst.join("storage.js"), include_bytes!("static/storage.js"))?;
779 if let Some(ref css) = cx.shared.css_file_extension {
780 let out = cx.dst.join("theme.css");
781 try_err!(fs::copy(css, out), css);
783 write(cx.dst.join("normalize.css"),
784 include_bytes!("static/normalize.css"))?;
785 write(cx.dst.join("FiraSans-Regular.woff"),
786 include_bytes!("static/FiraSans-Regular.woff"))?;
787 write(cx.dst.join("FiraSans-Medium.woff"),
788 include_bytes!("static/FiraSans-Medium.woff"))?;
789 write(cx.dst.join("FiraSans-LICENSE.txt"),
790 include_bytes!("static/FiraSans-LICENSE.txt"))?;
791 write(cx.dst.join("Heuristica-Italic.woff"),
792 include_bytes!("static/Heuristica-Italic.woff"))?;
793 write(cx.dst.join("Heuristica-LICENSE.txt"),
794 include_bytes!("static/Heuristica-LICENSE.txt"))?;
795 write(cx.dst.join("SourceSerifPro-Regular.woff"),
796 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
797 write(cx.dst.join("SourceSerifPro-Bold.woff"),
798 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
799 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
800 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
801 write(cx.dst.join("SourceCodePro-Regular.woff"),
802 include_bytes!("static/SourceCodePro-Regular.woff"))?;
803 write(cx.dst.join("SourceCodePro-Semibold.woff"),
804 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
805 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
806 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
807 write(cx.dst.join("LICENSE-MIT.txt"),
808 include_bytes!("static/LICENSE-MIT.txt"))?;
809 write(cx.dst.join("LICENSE-APACHE.txt"),
810 include_bytes!("static/LICENSE-APACHE.txt"))?;
811 write(cx.dst.join("COPYRIGHT.txt"),
812 include_bytes!("static/COPYRIGHT.txt"))?;
814 fn collect(path: &Path, krate: &str,
815 key: &str) -> io::Result<Vec<String>> {
816 let mut ret = Vec::new();
818 for line in BufReader::new(File::open(path)?).lines() {
820 if !line.starts_with(key) {
823 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
826 ret.push(line.to_string());
832 // Update the search index
833 let dst = cx.dst.join("search-index.js");
834 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
835 all_indexes.push(search_index);
836 // Sort the indexes by crate so the file will be generated identically even
837 // with rustdoc running in parallel.
839 let mut w = try_err!(File::create(&dst), &dst);
840 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
841 for index in &all_indexes {
842 try_err!(writeln!(&mut w, "{}", *index), &dst);
844 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
846 // Update the list of all implementors for traits
847 let dst = cx.dst.join("implementors");
848 for (&did, imps) in &cache.implementors {
849 // Private modules can leak through to this phase of rustdoc, which
850 // could contain implementations for otherwise private types. In some
851 // rare cases we could find an implementation for an item which wasn't
852 // indexed, so we just skip this step in that case.
854 // FIXME: this is a vague explanation for why this can't be a `get`, in
855 // theory it should be...
856 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
858 None => match cache.external_paths.get(&did) {
864 let mut have_impls = false;
865 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
867 // If the trait and implementation are in the same crate, then
868 // there's no need to emit information about it (there's inlining
869 // going on). If they're in different crates then the crate defining
870 // the trait will be interested in our implementation.
871 if imp.impl_item.def_id.krate == did.krate { continue }
872 // If the implementation is from another crate then that crate
874 if !imp.impl_item.def_id.is_local() { continue }
876 write!(implementors, "{},", as_json(&imp.inner_impl().to_string())).unwrap();
878 implementors.push_str("];");
880 // Only create a js file if we have impls to add to it. If the trait is
881 // documented locally though we always create the file to avoid dead
883 if !have_impls && !cache.paths.contains_key(&did) {
887 let mut mydst = dst.clone();
888 for part in &remote_path[..remote_path.len() - 1] {
891 try_err!(fs::create_dir_all(&mydst), &mydst);
892 mydst.push(&format!("{}.{}.js",
893 remote_item_type.css_class(),
894 remote_path[remote_path.len() - 1]));
896 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
897 all_implementors.push(implementors);
898 // Sort the implementors by crate so the file will be generated
899 // identically even with rustdoc running in parallel.
900 all_implementors.sort();
902 let mut f = try_err!(File::create(&mydst), &mydst);
903 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
904 for implementor in &all_implementors {
905 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
907 try_err!(writeln!(&mut f, "{}", r"
908 if (window.register_implementors) {
909 window.register_implementors(implementors);
911 window.pending_implementors = implementors;
914 try_err!(writeln!(&mut f, r"}})()"), &mydst);
919 fn render_sources(dst: &Path, scx: &mut SharedContext,
920 krate: clean::Crate) -> Result<clean::Crate, Error> {
921 info!("emitting source files");
922 let dst = dst.join("src").join(&krate.name);
923 try_err!(fs::create_dir_all(&dst), &dst);
924 let mut folder = SourceCollector {
928 Ok(folder.fold_crate(krate))
931 /// Writes the entire contents of a string to a destination, not attempting to
932 /// catch any errors.
933 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
934 Ok(try_err!(fs::write(&dst, contents), &dst))
937 /// Takes a path to a source file and cleans the path to it. This canonicalizes
938 /// things like ".." to components which preserve the "top down" hierarchy of a
939 /// static HTML tree. Each component in the cleaned path will be passed as an
940 /// argument to `f`. The very last component of the path (ie the file name) will
941 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
942 // FIXME (#9639): The closure should deal with &[u8] instead of &str
943 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
944 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
947 // make it relative, if possible
948 let p = p.strip_prefix(src_root).unwrap_or(p);
950 let mut iter = p.components().peekable();
952 while let Some(c) = iter.next() {
953 if !keep_filename && iter.peek().is_none() {
958 Component::ParentDir => f("up"),
959 Component::Normal(c) => f(c.to_str().unwrap()),
965 /// Attempts to find where an external crate is located, given that we're
966 /// rendering in to the specified source destination.
967 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
968 // See if there's documentation generated into the local directory
969 let local_location = dst.join(&e.name);
970 if local_location.is_dir() {
974 // Failing that, see if there's an attribute specifying where to find this
977 .filter(|a| a.check_name("html_root_url"))
978 .filter_map(|a| a.value_str())
980 let mut url = url.to_string();
981 if !url.ends_with("/") {
985 }).next().unwrap_or(Unknown) // Well, at least we tried.
988 impl<'a> DocFolder for SourceCollector<'a> {
989 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
990 // If we're including source files, and we haven't seen this file yet,
991 // then we need to render it out to the filesystem.
992 if self.scx.include_sources
993 // skip all invalid or macro spans
994 && item.source.filename.is_real()
995 // skip non-local items
996 && item.def_id.is_local() {
998 // If it turns out that we couldn't read this file, then we probably
999 // can't read any of the files (generating html output from json or
1000 // something like that), so just don't include sources for the
1001 // entire crate. The other option is maintaining this mapping on a
1002 // per-file basis, but that's probably not worth it...
1004 .include_sources = match self.emit_source(&item.source.filename) {
1007 println!("warning: source code was requested to be rendered, \
1008 but processing `{}` had an error: {}",
1009 item.source.filename, e);
1010 println!(" skipping rendering of source code");
1015 self.fold_item_recur(item)
1019 impl<'a> SourceCollector<'a> {
1020 /// Renders the given filename into its corresponding HTML source file.
1021 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1022 let p = match *filename {
1023 FileName::Real(ref file) => file,
1026 if self.scx.local_sources.contains_key(&**p) {
1027 // We've already emitted this source
1031 let contents = fs::read_string(&p)?;
1033 // Remove the utf-8 BOM if any
1034 let contents = if contents.starts_with("\u{feff}") {
1040 // Create the intermediate directories
1041 let mut cur = self.dst.clone();
1042 let mut root_path = String::from("../../");
1043 let mut href = String::new();
1044 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1045 cur.push(component);
1046 fs::create_dir_all(&cur).unwrap();
1047 root_path.push_str("../");
1048 href.push_str(component);
1051 let mut fname = p.file_name().expect("source has no filename")
1053 fname.push(".html");
1055 href.push_str(&fname.to_string_lossy());
1057 let mut w = BufWriter::new(File::create(&cur)?);
1058 let title = format!("{} -- source", cur.file_name().unwrap()
1059 .to_string_lossy());
1060 let desc = format!("Source to the Rust file `{}`.", filename);
1061 let page = layout::Page {
1063 css_class: "source",
1064 root_path: &root_path,
1066 keywords: BASIC_KEYWORDS,
1068 layout::render(&mut w, &self.scx.layout,
1069 &page, &(""), &Source(contents),
1070 self.scx.css_file_extension.is_some(),
1073 self.scx.local_sources.insert(p.clone(), href);
1078 impl DocFolder for Cache {
1079 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1080 // If this is a stripped module,
1081 // we don't want it or its children in the search index.
1082 let orig_stripped_mod = match item.inner {
1083 clean::StrippedItem(box clean::ModuleItem(..)) => {
1084 mem::replace(&mut self.stripped_mod, true)
1086 _ => self.stripped_mod,
1089 // If the impl is from a masked crate or references something from a
1090 // masked crate then remove it completely.
1091 if let clean::ImplItem(ref i) = item.inner {
1092 if self.masked_crates.contains(&item.def_id.krate) ||
1093 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1094 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1099 // Register any generics to their corresponding string. This is used
1100 // when pretty-printing types.
1101 if let Some(generics) = item.inner.generics() {
1102 self.generics(generics);
1105 // Propagate a trait method's documentation to all implementors of the
1107 if let clean::TraitItem(ref t) = item.inner {
1108 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1111 // Collect all the implementors of traits.
1112 if let clean::ImplItem(ref i) = item.inner {
1113 if let Some(did) = i.trait_.def_id() {
1114 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1115 impl_item: item.clone(),
1120 // Index this method for searching later on.
1121 if let Some(ref s) = item.name {
1122 let (parent, is_inherent_impl_item) = match item.inner {
1123 clean::StrippedItem(..) => ((None, None), false),
1124 clean::AssociatedConstItem(..) |
1125 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1126 // skip associated items in trait impls
1127 ((None, None), false)
1129 clean::AssociatedTypeItem(..) |
1130 clean::TyMethodItem(..) |
1131 clean::StructFieldItem(..) |
1132 clean::VariantItem(..) => {
1133 ((Some(*self.parent_stack.last().unwrap()),
1134 Some(&self.stack[..self.stack.len() - 1])),
1137 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1138 if self.parent_stack.is_empty() {
1139 ((None, None), false)
1141 let last = self.parent_stack.last().unwrap();
1143 let path = match self.paths.get(&did) {
1144 // The current stack not necessarily has correlation
1145 // for where the type was defined. On the other
1146 // hand, `paths` always has the right
1147 // information if present.
1148 Some(&(ref fqp, ItemType::Trait)) |
1149 Some(&(ref fqp, ItemType::Struct)) |
1150 Some(&(ref fqp, ItemType::Union)) |
1151 Some(&(ref fqp, ItemType::Enum)) =>
1152 Some(&fqp[..fqp.len() - 1]),
1153 Some(..) => Some(&*self.stack),
1156 ((Some(*last), path), true)
1159 _ => ((None, Some(&*self.stack)), false)
1163 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1164 debug_assert!(!item.is_stripped());
1166 // A crate has a module at its root, containing all items,
1167 // which should not be indexed. The crate-item itself is
1168 // inserted later on when serializing the search-index.
1169 if item.def_id.index != CRATE_DEF_INDEX {
1170 self.search_index.push(IndexItem {
1172 name: s.to_string(),
1173 path: path.join("::").to_string(),
1174 desc: plain_summary_line(item.doc_value()),
1177 search_type: get_index_search_type(&item),
1181 (Some(parent), None) if is_inherent_impl_item => {
1182 // We have a parent, but we don't know where they're
1183 // defined yet. Wait for later to index this item.
1184 self.orphan_impl_items.push((parent, item.clone()));
1190 // Keep track of the fully qualified path for this item.
1191 let pushed = match item.name {
1192 Some(ref n) if !n.is_empty() => {
1193 self.stack.push(n.to_string());
1200 clean::StructItem(..) | clean::EnumItem(..) |
1201 clean::TypedefItem(..) | clean::TraitItem(..) |
1202 clean::FunctionItem(..) | clean::ModuleItem(..) |
1203 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1204 clean::ConstantItem(..) | clean::StaticItem(..) |
1205 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1206 if !self.stripped_mod => {
1207 // Re-exported items mean that the same id can show up twice
1208 // in the rustdoc ast that we're looking at. We know,
1209 // however, that a re-exported item doesn't show up in the
1210 // `public_items` map, so we can skip inserting into the
1211 // paths map if there was already an entry present and we're
1212 // not a public item.
1214 !self.paths.contains_key(&item.def_id) ||
1215 self.access_levels.is_public(item.def_id)
1217 self.paths.insert(item.def_id,
1218 (self.stack.clone(), item.type_()));
1221 // Link variants to their parent enum because pages aren't emitted
1222 // for each variant.
1223 clean::VariantItem(..) if !self.stripped_mod => {
1224 let mut stack = self.stack.clone();
1226 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1229 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1230 self.paths.insert(item.def_id, (self.stack.clone(),
1237 // Maintain the parent stack
1238 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1239 let parent_pushed = match item.inner {
1240 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1241 clean::StructItem(..) | clean::UnionItem(..) => {
1242 self.parent_stack.push(item.def_id);
1243 self.parent_is_trait_impl = false;
1246 clean::ImplItem(ref i) => {
1247 self.parent_is_trait_impl = i.trait_.is_some();
1249 clean::ResolvedPath{ did, .. } => {
1250 self.parent_stack.push(did);
1254 let prim_did = t.primitive_type().and_then(|t| {
1255 self.primitive_locations.get(&t).cloned()
1259 self.parent_stack.push(did);
1270 // Once we've recursively found all the generics, hoard off all the
1271 // implementations elsewhere.
1272 let ret = self.fold_item_recur(item).and_then(|item| {
1273 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1274 // Figure out the id of this impl. This may map to a
1275 // primitive rather than always to a struct/enum.
1276 // Note: matching twice to restrict the lifetime of the `i` borrow.
1277 let mut dids = FxHashSet();
1278 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1280 clean::ResolvedPath { did, .. } |
1281 clean::BorrowedRef {
1282 type_: box clean::ResolvedPath { did, .. }, ..
1287 let did = t.primitive_type().and_then(|t| {
1288 self.primitive_locations.get(&t).cloned()
1291 if let Some(did) = did {
1297 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1298 for bound in generics {
1299 if let Some(did) = bound.def_id() {
1308 self.impls.entry(did).or_insert(vec![]).push(Impl {
1309 impl_item: item.clone(),
1318 if pushed { self.stack.pop().unwrap(); }
1319 if parent_pushed { self.parent_stack.pop().unwrap(); }
1320 self.stripped_mod = orig_stripped_mod;
1321 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1327 fn generics(&mut self, generics: &clean::Generics) {
1328 for param in &generics.params {
1329 if let clean::GenericParam::Type(ref typ) = *param {
1330 self.typarams.insert(typ.did, typ.name.clone());
1337 /// String representation of how to get back to the root path of the 'doc/'
1338 /// folder in terms of a relative URL.
1339 fn root_path(&self) -> String {
1340 repeat("../").take(self.current.len()).collect::<String>()
1343 /// Recurse in the directory structure and change the "root path" to make
1344 /// sure it always points to the top (relatively).
1345 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1346 F: FnOnce(&mut Context) -> T,
1349 panic!("Unexpected empty destination: {:?}", self.current);
1351 let prev = self.dst.clone();
1353 self.current.push(s);
1355 info!("Recursing into {}", self.dst.display());
1359 info!("Recursed; leaving {}", self.dst.display());
1361 // Go back to where we were at
1363 self.current.pop().unwrap();
1368 /// Main method for rendering a crate.
1370 /// This currently isn't parallelized, but it'd be pretty easy to add
1371 /// parallelization to this function.
1372 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1373 let mut item = match krate.module.take() {
1375 None => return Ok(()),
1377 item.name = Some(krate.name);
1379 // Render the crate documentation
1380 let mut work = vec![(self, item)];
1382 while let Some((mut cx, item)) = work.pop() {
1383 cx.item(item, |cx, item| {
1384 work.push((cx.clone(), item))
1390 fn render_item(&self,
1391 writer: &mut io::Write,
1395 // A little unfortunate that this is done like this, but it sure
1396 // does make formatting *a lot* nicer.
1397 CURRENT_LOCATION_KEY.with(|slot| {
1398 *slot.borrow_mut() = self.current.clone();
1401 let mut title = if it.is_primitive() {
1402 // No need to include the namespace for primitive types
1405 self.current.join("::")
1408 if !title.is_empty() {
1409 title.push_str("::");
1411 title.push_str(it.name.as_ref().unwrap());
1413 title.push_str(" - Rust");
1414 let tyname = it.type_().css_class();
1415 let desc = if it.is_crate() {
1416 format!("API documentation for the Rust `{}` crate.",
1417 self.shared.layout.krate)
1419 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1420 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1422 let keywords = make_item_keywords(it);
1423 let page = layout::Page {
1425 root_path: &self.root_path(),
1428 keywords: &keywords,
1433 if !self.render_redirect_pages {
1434 layout::render(writer, &self.shared.layout, &page,
1435 &Sidebar{ cx: self, item: it },
1436 &Item{ cx: self, item: it },
1437 self.shared.css_file_extension.is_some(),
1438 &self.shared.themes)?;
1440 let mut url = self.root_path();
1441 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1442 for name in &names[..names.len() - 1] {
1446 url.push_str(&item_path(ty, names.last().unwrap()));
1447 layout::redirect(writer, &url)?;
1453 /// Non-parallelized version of rendering an item. This will take the input
1454 /// item, render its contents, and then invoke the specified closure with
1455 /// all sub-items which need to be rendered.
1457 /// The rendering driver uses this closure to queue up more work.
1458 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1459 F: FnMut(&mut Context, clean::Item),
1461 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1462 // if they contain impls for public types. These modules can also
1463 // contain items such as publicly re-exported structures.
1465 // External crates will provide links to these structures, so
1466 // these modules are recursed into, but not rendered normally
1467 // (a flag on the context).
1468 if !self.render_redirect_pages {
1469 self.render_redirect_pages = item.is_stripped();
1473 // modules are special because they add a namespace. We also need to
1474 // recurse into the items of the module as well.
1475 let name = item.name.as_ref().unwrap().to_string();
1476 let mut item = Some(item);
1477 self.recurse(name, |this| {
1478 let item = item.take().unwrap();
1480 let mut buf = Vec::new();
1481 this.render_item(&mut buf, &item, false).unwrap();
1482 // buf will be empty if the module is stripped and there is no redirect for it
1483 if !buf.is_empty() {
1484 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1485 let joint_dst = this.dst.join("index.html");
1486 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1487 try_err!(dst.write_all(&buf), &joint_dst);
1490 let m = match item.inner {
1491 clean::StrippedItem(box clean::ModuleItem(m)) |
1492 clean::ModuleItem(m) => m,
1496 // Render sidebar-items.js used throughout this module.
1497 if !this.render_redirect_pages {
1498 let items = this.build_sidebar_items(&m);
1499 let js_dst = this.dst.join("sidebar-items.js");
1500 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1501 try_err!(write!(&mut js_out, "initSidebarItems({});",
1502 as_json(&items)), &js_dst);
1505 for item in m.items {
1511 } else if item.name.is_some() {
1512 let mut buf = Vec::new();
1513 self.render_item(&mut buf, &item, true).unwrap();
1514 // buf will be empty if the item is stripped and there is no redirect for it
1515 if !buf.is_empty() {
1516 let name = item.name.as_ref().unwrap();
1517 let item_type = item.type_();
1518 let file_name = &item_path(item_type, name);
1519 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1520 let joint_dst = self.dst.join(file_name);
1521 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1522 try_err!(dst.write_all(&buf), &joint_dst);
1524 // Redirect from a sane URL using the namespace to Rustdoc's
1525 // URL for the page.
1526 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1527 let redir_dst = self.dst.join(redir_name);
1528 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1531 let mut redirect_out = BufWriter::new(redirect_out);
1532 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1535 // If the item is a macro, redirect from the old macro URL (with !)
1536 // to the new one (without).
1537 // FIXME(#35705) remove this redirect.
1538 if item_type == ItemType::Macro {
1539 let redir_name = format!("{}.{}!.html", item_type, name);
1540 let redir_dst = self.dst.join(redir_name);
1541 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1542 let mut redirect_out = BufWriter::new(redirect_out);
1543 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1550 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1551 // BTreeMap instead of HashMap to get a sorted output
1552 let mut map = BTreeMap::new();
1553 for item in &m.items {
1554 if item.is_stripped() { continue }
1556 let short = item.type_().css_class();
1557 let myname = match item.name {
1559 Some(ref s) => s.to_string(),
1561 let short = short.to_string();
1562 map.entry(short).or_insert(vec![])
1563 .push((myname, Some(plain_summary_line(item.doc_value()))));
1566 if self.shared.sort_modules_alphabetically {
1567 for (_, items) in &mut map {
1576 /// Generate a url appropriate for an `href` attribute back to the source of
1579 /// The url generated, when clicked, will redirect the browser back to the
1580 /// original source code.
1582 /// If `None` is returned, then a source link couldn't be generated. This
1583 /// may happen, for example, with externally inlined items where the source
1584 /// of their crate documentation isn't known.
1585 fn src_href(&self) -> Option<String> {
1586 let mut root = self.cx.root_path();
1588 let cache = cache();
1589 let mut path = String::new();
1591 // We can safely ignore macros from other libraries
1592 let file = match self.item.source.filename {
1593 FileName::Real(ref path) => path,
1597 let (krate, path) = if self.item.def_id.is_local() {
1598 if let Some(path) = self.cx.shared.local_sources.get(file) {
1599 (&self.cx.shared.layout.krate, path)
1604 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1605 Some(&(ref name, ref src, Local)) => (name, src),
1606 Some(&(ref name, ref src, Remote(ref s))) => {
1607 root = s.to_string();
1610 Some(&(_, _, Unknown)) | None => return None,
1613 clean_srcpath(&src_root, file, false, |component| {
1614 path.push_str(component);
1617 let mut fname = file.file_name().expect("source has no filename")
1619 fname.push(".html");
1620 path.push_str(&fname.to_string_lossy());
1624 let lines = if self.item.source.loline == self.item.source.hiline {
1625 format!("{}", self.item.source.loline)
1627 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1629 Some(format!("{root}src/{krate}/{path}#{lines}",
1630 root = Escape(&root),
1637 impl<'a> fmt::Display for Item<'a> {
1638 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1639 debug_assert!(!self.item.is_stripped());
1640 // Write the breadcrumb trail header for the top
1641 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1642 match self.item.inner {
1643 clean::ModuleItem(ref m) => if m.is_crate {
1644 write!(fmt, "Crate ")?;
1646 write!(fmt, "Module ")?;
1648 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1649 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1650 clean::StructItem(..) => write!(fmt, "Struct ")?,
1651 clean::UnionItem(..) => write!(fmt, "Union ")?,
1652 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1653 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1654 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1655 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1656 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1657 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1658 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1660 // We don't generate pages for any other type.
1664 if !self.item.is_primitive() {
1665 let cur = &self.cx.current;
1666 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1667 for (i, component) in cur.iter().enumerate().take(amt) {
1668 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1669 repeat("../").take(cur.len() - i - 1)
1670 .collect::<String>(),
1674 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1675 self.item.type_(), self.item.name.as_ref().unwrap())?;
1677 write!(fmt, "</span>")?; // in-band
1678 write!(fmt, "<span class='out-of-band'>")?;
1679 if let Some(version) = self.item.stable_since() {
1680 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1684 r##"<span id='render-detail'>
1685 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1686 [<span class='inner'>−</span>]
1692 // When this item is part of a `pub use` in a downstream crate, the
1693 // [src] link in the downstream documentation will actually come back to
1694 // this page, and this link will be auto-clicked. The `id` attribute is
1695 // used to find the link to auto-click.
1696 if self.cx.shared.include_sources && !self.item.is_primitive() {
1697 if let Some(l) = self.src_href() {
1698 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1699 l, "goto source code")?;
1703 write!(fmt, "</span>")?; // out-of-band
1705 write!(fmt, "</h1>\n")?;
1707 match self.item.inner {
1708 clean::ModuleItem(ref m) => {
1709 item_module(fmt, self.cx, self.item, &m.items)
1711 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1712 item_function(fmt, self.cx, self.item, f),
1713 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1714 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1715 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1716 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1717 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1718 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1719 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1720 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1721 item_static(fmt, self.cx, self.item, i),
1722 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1723 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1725 // We don't generate pages for any other type.
1732 fn item_path(ty: ItemType, name: &str) -> String {
1734 ItemType::Module => format!("{}/index.html", name),
1735 _ => format!("{}.{}.html", ty.css_class(), name),
1739 fn full_path(cx: &Context, item: &clean::Item) -> String {
1740 let mut s = cx.current.join("::");
1742 s.push_str(item.name.as_ref().unwrap());
1746 fn shorter<'a>(s: Option<&'a str>) -> String {
1748 Some(s) => s.lines()
1749 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1751 (*line).chars().any(|chr|{
1752 !chr.is_whitespace()
1754 }).collect::<Vec<_>>().join("\n"),
1755 None => "".to_string()
1760 fn plain_summary_line(s: Option<&str>) -> String {
1761 let line = shorter(s).replace("\n", " ");
1762 markdown::plain_summary_line(&line[..])
1765 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1766 if let Some(ref name) = item.name {
1767 info!("Documenting {}", name);
1769 document_stability(w, cx, item)?;
1770 let prefix = render_assoc_const_value(item);
1771 document_full(w, item, cx, &prefix)?;
1775 /// Render md_text as markdown.
1776 fn render_markdown(w: &mut fmt::Formatter,
1778 links: Vec<(String, String)>,
1781 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1784 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1785 prefix: &str) -> fmt::Result {
1786 if let Some(s) = item.doc_value() {
1787 let markdown = if s.contains('\n') {
1788 format!("{} [Read more]({})",
1789 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1791 format!("{}", &plain_summary_line(Some(s)))
1793 render_markdown(w, &markdown, item.links(), prefix)?;
1794 } else if !prefix.is_empty() {
1795 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1800 fn render_assoc_const_value(item: &clean::Item) -> String {
1802 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1803 highlight::render_with_highlighting(
1804 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1815 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1816 cx: &Context, prefix: &str) -> fmt::Result {
1817 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1818 debug!("Doc block: =====\n{}\n=====", s);
1819 render_markdown(w, &*s, item.links(), prefix)?;
1820 } else if !prefix.is_empty() {
1821 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1826 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1827 let stabilities = short_stability(item, cx, true);
1828 if !stabilities.is_empty() {
1829 write!(w, "<div class='stability'>")?;
1830 for stability in stabilities {
1831 write!(w, "{}", stability)?;
1833 write!(w, "</div>")?;
1838 fn name_key(name: &str) -> (&str, u64, usize) {
1839 // find number at end
1840 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1842 // count leading zeroes
1844 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1846 // sort leading zeroes last
1847 let num_zeroes = after_zeroes - split;
1849 match name[split..].parse() {
1850 Ok(n) => (&name[..split], n, num_zeroes),
1851 Err(_) => (name, 0, num_zeroes),
1855 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1856 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1857 document(w, cx, item)?;
1859 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped())
1860 .collect::<Vec<usize>>();
1862 // the order of item types in the listing
1863 fn reorder(ty: ItemType) -> u8 {
1865 ItemType::ExternCrate => 0,
1866 ItemType::Import => 1,
1867 ItemType::Primitive => 2,
1868 ItemType::Module => 3,
1869 ItemType::Macro => 4,
1870 ItemType::Struct => 5,
1871 ItemType::Enum => 6,
1872 ItemType::Constant => 7,
1873 ItemType::Static => 8,
1874 ItemType::Trait => 9,
1875 ItemType::Function => 10,
1876 ItemType::Typedef => 12,
1877 ItemType::Union => 13,
1882 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1883 let ty1 = i1.type_();
1884 let ty2 = i2.type_();
1886 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1888 let s1 = i1.stability.as_ref().map(|s| s.level);
1889 let s2 = i2.stability.as_ref().map(|s| s.level);
1891 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1892 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1895 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1896 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1897 name_key(lhs).cmp(&name_key(rhs))
1900 if cx.shared.sort_modules_alphabetically {
1901 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1903 // This call is to remove re-export duplicates in cases such as:
1908 // pub trait Double { fn foo(); }
1912 // pub use foo::bar::*;
1916 // `Double` will appear twice in the generated docs.
1918 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1919 // can be identical even if the elements are different (mostly in imports).
1920 // So in case this is an import, we keep everything by adding a "unique id"
1921 // (which is the position in the vector).
1922 indices.dedup_by_key(|i| (items[*i].def_id,
1923 if items[*i].name.as_ref().is_some() {
1924 Some(full_path(cx, &items[*i]).clone())
1929 if items[*i].is_import() {
1935 debug!("{:?}", indices);
1936 let mut curty = None;
1937 for &idx in &indices {
1938 let myitem = &items[idx];
1939 if myitem.is_stripped() {
1943 let myty = Some(myitem.type_());
1944 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1945 // Put `extern crate` and `use` re-exports in the same section.
1947 } else if myty != curty {
1948 if curty.is_some() {
1949 write!(w, "</table>")?;
1952 let (short, name) = match myty.unwrap() {
1953 ItemType::ExternCrate |
1954 ItemType::Import => ("reexports", "Re-exports"),
1955 ItemType::Module => ("modules", "Modules"),
1956 ItemType::Struct => ("structs", "Structs"),
1957 ItemType::Union => ("unions", "Unions"),
1958 ItemType::Enum => ("enums", "Enums"),
1959 ItemType::Function => ("functions", "Functions"),
1960 ItemType::Typedef => ("types", "Type Definitions"),
1961 ItemType::Static => ("statics", "Statics"),
1962 ItemType::Constant => ("constants", "Constants"),
1963 ItemType::Trait => ("traits", "Traits"),
1964 ItemType::Impl => ("impls", "Implementations"),
1965 ItemType::TyMethod => ("tymethods", "Type Methods"),
1966 ItemType::Method => ("methods", "Methods"),
1967 ItemType::StructField => ("fields", "Struct Fields"),
1968 ItemType::Variant => ("variants", "Variants"),
1969 ItemType::Macro => ("macros", "Macros"),
1970 ItemType::Primitive => ("primitives", "Primitive Types"),
1971 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1972 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1973 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
1975 write!(w, "<h2 id='{id}' class='section-header'>\
1976 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1977 id = derive_id(short.to_owned()), name = name)?;
1980 match myitem.inner {
1981 clean::ExternCrateItem(ref name, ref src) => {
1982 use html::format::HRef;
1986 write!(w, "<tr><td><code>{}extern crate {} as {};",
1987 VisSpace(&myitem.visibility),
1988 HRef::new(myitem.def_id, src),
1992 write!(w, "<tr><td><code>{}extern crate {};",
1993 VisSpace(&myitem.visibility),
1994 HRef::new(myitem.def_id, name))?
1997 write!(w, "</code></td></tr>")?;
2000 clean::ImportItem(ref import) => {
2001 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2002 VisSpace(&myitem.visibility), *import)?;
2006 if myitem.name.is_none() { continue }
2008 let stabilities = short_stability(myitem, cx, false);
2010 let stab_docs = if !stabilities.is_empty() {
2012 .map(|s| format!("[{}]", s))
2013 .collect::<Vec<_>>()
2020 let unsafety_flag = match myitem.inner {
2021 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2022 if func.unsafety == hir::Unsafety::Unsafe => {
2023 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2028 let doc_value = myitem.doc_value().unwrap_or("");
2030 <tr class='{stab} module-item'>
2031 <td><a class=\"{class}\" href=\"{href}\"
2032 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2033 <td class='docblock-short'>
2037 name = *myitem.name.as_ref().unwrap(),
2038 stab_docs = stab_docs,
2039 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2040 class = myitem.type_(),
2041 stab = myitem.stability_class().unwrap_or("".to_string()),
2042 unsafety_flag = unsafety_flag,
2043 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2044 title_type = myitem.type_(),
2045 title = full_path(cx, myitem))?;
2050 if curty.is_some() {
2051 write!(w, "</table>")?;
2056 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2057 let mut stability = vec![];
2059 if let Some(stab) = item.stability.as_ref() {
2060 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2061 format!(": {}", stab.deprecated_reason)
2065 if !stab.deprecated_since.is_empty() {
2066 let since = if show_reason {
2067 format!(" since {}", Escape(&stab.deprecated_since))
2071 let text = format!("Deprecated{}{}",
2073 MarkdownHtml(&deprecated_reason));
2074 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2077 if stab.level == stability::Unstable {
2079 let unstable_extra = match (!stab.feature.is_empty(),
2080 &cx.shared.issue_tracker_base_url,
2082 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2083 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2084 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2085 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2086 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2089 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2092 if stab.unstable_reason.is_empty() {
2093 stability.push(format!("<div class='stab unstable'>\
2094 <span class=microscope>🔬</span> \
2095 This is a nightly-only experimental API. {}\
2099 let text = format!("<summary><span class=microscope>🔬</span> \
2100 This is a nightly-only experimental API. {}\
2103 MarkdownHtml(&stab.unstable_reason));
2104 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2108 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2111 } else if let Some(depr) = item.deprecation.as_ref() {
2112 let note = if show_reason && !depr.note.is_empty() {
2113 format!(": {}", depr.note)
2117 let since = if show_reason && !depr.since.is_empty() {
2118 format!(" since {}", Escape(&depr.since))
2123 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e));
2124 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2127 if let Some(ref cfg) = item.attrs.cfg {
2128 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2129 cfg.render_long_html()
2131 cfg.render_short_html()
2138 struct Initializer<'a>(&'a str);
2140 impl<'a> fmt::Display for Initializer<'a> {
2141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2142 let Initializer(s) = *self;
2143 if s.is_empty() { return Ok(()); }
2144 write!(f, "<code> = </code>")?;
2145 write!(f, "<code>{}</code>", Escape(s))
2149 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2150 c: &clean::Constant) -> fmt::Result {
2151 write!(w, "<pre class='rust const'>")?;
2152 render_attributes(w, it)?;
2153 write!(w, "{vis}const \
2154 {name}: {typ}{init}</pre>",
2155 vis = VisSpace(&it.visibility),
2156 name = it.name.as_ref().unwrap(),
2158 init = Initializer(&c.expr))?;
2162 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2163 s: &clean::Static) -> fmt::Result {
2164 write!(w, "<pre class='rust static'>")?;
2165 render_attributes(w, it)?;
2166 write!(w, "{vis}static {mutability}\
2167 {name}: {typ}{init}</pre>",
2168 vis = VisSpace(&it.visibility),
2169 mutability = MutableSpace(s.mutability),
2170 name = it.name.as_ref().unwrap(),
2172 init = Initializer(&s.expr))?;
2176 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2177 f: &clean::Function) -> fmt::Result {
2178 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2179 VisSpace(&it.visibility),
2180 ConstnessSpace(f.constness),
2181 UnsafetySpace(f.unsafety),
2183 it.name.as_ref().unwrap(),
2185 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2186 render_attributes(w, it)?;
2188 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2189 vis = VisSpace(&it.visibility),
2190 constness = ConstnessSpace(f.constness),
2191 unsafety = UnsafetySpace(f.unsafety),
2192 abi = AbiSpace(f.abi),
2193 name = it.name.as_ref().unwrap(),
2194 generics = f.generics,
2195 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2204 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2205 t: &clean::Trait) -> fmt::Result {
2206 let mut bounds = String::new();
2207 let mut bounds_plain = String::new();
2208 if !t.bounds.is_empty() {
2209 if !bounds.is_empty() {
2211 bounds_plain.push(' ');
2213 bounds.push_str(": ");
2214 bounds_plain.push_str(": ");
2215 for (i, p) in t.bounds.iter().enumerate() {
2217 bounds.push_str(" + ");
2218 bounds_plain.push_str(" + ");
2220 bounds.push_str(&format!("{}", *p));
2221 bounds_plain.push_str(&format!("{:#}", *p));
2225 // Output the trait definition
2226 write!(w, "<pre class='rust trait'>")?;
2227 render_attributes(w, it)?;
2228 write!(w, "{}{}{}trait {}{}{}",
2229 VisSpace(&it.visibility),
2230 UnsafetySpace(t.unsafety),
2231 if t.is_auto { "auto " } else { "" },
2232 it.name.as_ref().unwrap(),
2236 if !t.generics.where_predicates.is_empty() {
2237 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2242 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2243 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2244 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2245 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2247 if t.items.is_empty() {
2248 write!(w, "{{ }}")?;
2250 // FIXME: we should be using a derived_id for the Anchors here
2254 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2257 if !types.is_empty() && !consts.is_empty() {
2262 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2265 if !consts.is_empty() && !required.is_empty() {
2268 for (pos, m) in required.iter().enumerate() {
2270 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2273 if pos < required.len() - 1 {
2274 write!(w, "<div class='item-spacer'></div>")?;
2277 if !required.is_empty() && !provided.is_empty() {
2280 for (pos, m) in provided.iter().enumerate() {
2282 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2284 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2285 write!(w, ",\n {{ ... }}\n")?;
2288 write!(w, " {{ ... }}\n")?;
2291 if pos < provided.len() - 1 {
2292 write!(w, "<div class='item-spacer'></div>")?;
2297 write!(w, "</pre>")?;
2299 // Trait documentation
2300 document(w, cx, it)?;
2302 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2304 let name = m.name.as_ref().unwrap();
2305 let item_type = m.type_();
2306 let id = derive_id(format!("{}.{}", item_type, name));
2307 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2308 write!(w, "{extra}<h3 id='{id}' class='method'>\
2309 <span id='{ns_id}' class='invisible'><code>",
2310 extra = render_spotlight_traits(m)?,
2313 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2314 write!(w, "</code>")?;
2315 render_stability_since(w, m, t)?;
2316 write!(w, "</span></h3>")?;
2317 document(w, cx, m)?;
2321 if !types.is_empty() {
2323 <h2 id='associated-types' class='small-section-header'>
2324 Associated Types<a href='#associated-types' class='anchor'></a>
2326 <div class='methods'>
2329 trait_item(w, cx, *t, it)?;
2331 write!(w, "</div>")?;
2334 if !consts.is_empty() {
2336 <h2 id='associated-const' class='small-section-header'>
2337 Associated Constants<a href='#associated-const' class='anchor'></a>
2339 <div class='methods'>
2342 trait_item(w, cx, *t, it)?;
2344 write!(w, "</div>")?;
2347 // Output the documentation for each function individually
2348 if !required.is_empty() {
2350 <h2 id='required-methods' class='small-section-header'>
2351 Required Methods<a href='#required-methods' class='anchor'></a>
2353 <div class='methods'>
2355 for m in &required {
2356 trait_item(w, cx, *m, it)?;
2358 write!(w, "</div>")?;
2360 if !provided.is_empty() {
2362 <h2 id='provided-methods' class='small-section-header'>
2363 Provided Methods<a href='#provided-methods' class='anchor'></a>
2365 <div class='methods'>
2367 for m in &provided {
2368 trait_item(w, cx, *m, it)?;
2370 write!(w, "</div>")?;
2373 // If there are methods directly on this trait object, render them here.
2374 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2376 let cache = cache();
2378 <h2 id='implementors' class='small-section-header'>
2379 Implementors<a href='#implementors' class='anchor'></a>
2381 <ul class='item-list' id='implementors-list'>
2383 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2384 // The DefId is for the first Type found with that name. The bool is
2385 // if any Types with the same name but different DefId have been found.
2386 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2387 for implementor in implementors {
2388 match implementor.inner_impl().for_ {
2389 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2390 clean::BorrowedRef {
2391 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2394 let &mut (prev_did, ref mut has_duplicates) =
2395 implementor_dups.entry(path.last_name()).or_insert((did, false));
2396 if prev_did != did {
2397 *has_duplicates = true;
2404 let (local, foreign) = implementors.iter()
2405 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2406 .map_or(true, |d| cache.paths.contains_key(&d)));
2408 if !foreign.is_empty() {
2410 <h2 id='foreign-impls' class='small-section-header'>
2411 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2415 for implementor in foreign {
2416 let assoc_link = AssocItemLink::GotoSource(
2417 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2419 render_impl(w, cx, &implementor, assoc_link,
2420 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2424 write!(w, "{}", impl_header)?;
2426 for implementor in local {
2428 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2429 write!(w, "<div class='out-of-band'>")?;
2430 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2431 l, "goto source code")?;
2432 write!(w, "</div>")?;
2434 write!(w, "<code>")?;
2435 // If there's already another implementor that has the same abbridged name, use the
2436 // full path, for example in `std::iter::ExactSizeIterator`
2437 let use_absolute = match implementor.inner_impl().for_ {
2438 clean::ResolvedPath { ref path, is_generic: false, .. } |
2439 clean::BorrowedRef {
2440 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2442 } => implementor_dups[path.last_name()].1,
2445 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2446 for it in &implementor.inner_impl().items {
2447 if let clean::TypedefItem(ref tydef, _) = it.inner {
2448 write!(w, "<span class=\"where fmt-newline\"> ")?;
2449 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2450 write!(w, ";</span>")?;
2453 writeln!(w, "</code></li>")?;
2456 // even without any implementations to write in, we still want the heading and list, so the
2457 // implementors javascript file pulled in below has somewhere to write the impls into
2458 write!(w, "{}", impl_header)?;
2460 write!(w, "</ul>")?;
2461 write!(w, r#"<script type="text/javascript" async
2462 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2464 root_path = vec![".."; cx.current.len()].join("/"),
2465 path = if it.def_id.is_local() {
2466 cx.current.join("/")
2468 let (ref path, _) = cache.external_paths[&it.def_id];
2469 path[..path.len() - 1].join("/")
2471 ty = it.type_().css_class(),
2472 name = *it.name.as_ref().unwrap())?;
2476 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2477 use html::item_type::ItemType::*;
2479 let name = it.name.as_ref().unwrap();
2480 let ty = match it.type_() {
2481 Typedef | AssociatedType => AssociatedType,
2485 let anchor = format!("#{}.{}", ty, name);
2487 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2488 AssocItemLink::Anchor(None) => anchor,
2489 AssocItemLink::GotoSource(did, _) => {
2490 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2495 fn assoc_const(w: &mut fmt::Formatter,
2498 _default: Option<&String>,
2499 link: AssocItemLink) -> fmt::Result {
2500 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2501 VisSpace(&it.visibility),
2502 naive_assoc_href(it, link),
2503 it.name.as_ref().unwrap(),
2508 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2509 bounds: &Vec<clean::TyParamBound>,
2510 default: Option<&clean::Type>,
2511 link: AssocItemLink) -> fmt::Result {
2512 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2513 naive_assoc_href(it, link),
2514 it.name.as_ref().unwrap())?;
2515 if !bounds.is_empty() {
2516 write!(w, ": {}", TyParamBounds(bounds))?
2518 if let Some(default) = default {
2519 write!(w, " = {}", default)?;
2524 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2525 ver: Option<&'a str>,
2526 containing_ver: Option<&'a str>) -> fmt::Result {
2527 if let Some(v) = ver {
2528 if containing_ver != ver && v.len() > 0 {
2529 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2536 fn render_stability_since(w: &mut fmt::Formatter,
2538 containing_item: &clean::Item) -> fmt::Result {
2539 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2542 fn render_assoc_item(w: &mut fmt::Formatter,
2544 link: AssocItemLink,
2545 parent: ItemType) -> fmt::Result {
2546 fn method(w: &mut fmt::Formatter,
2548 unsafety: hir::Unsafety,
2549 constness: hir::Constness,
2551 g: &clean::Generics,
2553 link: AssocItemLink,
2556 let name = meth.name.as_ref().unwrap();
2557 let anchor = format!("#{}.{}", meth.type_(), name);
2558 let href = match link {
2559 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2560 AssocItemLink::Anchor(None) => anchor,
2561 AssocItemLink::GotoSource(did, provided_methods) => {
2562 // We're creating a link from an impl-item to the corresponding
2563 // trait-item and need to map the anchored type accordingly.
2564 let ty = if provided_methods.contains(name) {
2570 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2573 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2574 VisSpace(&meth.visibility),
2575 ConstnessSpace(constness),
2576 UnsafetySpace(unsafety),
2580 let (indent, end_newline) = if parent == ItemType::Trait {
2586 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2587 {generics}{decl}{where_clause}",
2588 VisSpace(&meth.visibility),
2589 ConstnessSpace(constness),
2590 UnsafetySpace(unsafety),
2600 where_clause = WhereClause {
2607 clean::StrippedItem(..) => Ok(()),
2608 clean::TyMethodItem(ref m) => {
2609 method(w, item, m.unsafety, hir::Constness::NotConst,
2610 m.abi, &m.generics, &m.decl, link, parent)
2612 clean::MethodItem(ref m) => {
2613 method(w, item, m.unsafety, m.constness,
2614 m.abi, &m.generics, &m.decl, link, parent)
2616 clean::AssociatedConstItem(ref ty, ref default) => {
2617 assoc_const(w, item, ty, default.as_ref(), link)
2619 clean::AssociatedTypeItem(ref bounds, ref default) => {
2620 assoc_type(w, item, bounds, default.as_ref(), link)
2622 _ => panic!("render_assoc_item called on non-associated-item")
2626 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2627 s: &clean::Struct) -> fmt::Result {
2628 write!(w, "<pre class='rust struct'>")?;
2629 render_attributes(w, it)?;
2637 write!(w, "</pre>")?;
2639 document(w, cx, it)?;
2640 let mut fields = s.fields.iter().filter_map(|f| {
2642 clean::StructFieldItem(ref ty) => Some((f, ty)),
2646 if let doctree::Plain = s.struct_type {
2647 if fields.peek().is_some() {
2648 write!(w, "<h2 id='fields' class='fields small-section-header'>
2649 Fields<a href='#fields' class='anchor'></a></h2>")?;
2650 for (field, ty) in fields {
2651 let id = derive_id(format!("{}.{}",
2652 ItemType::StructField,
2653 field.name.as_ref().unwrap()));
2654 let ns_id = derive_id(format!("{}.{}",
2655 field.name.as_ref().unwrap(),
2656 ItemType::StructField.name_space()));
2657 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2658 <a href=\"#{id}\" class=\"anchor field\"></a>
2659 <span id=\"{ns_id}\" class='invisible'>
2660 <code>{name}: {ty}</code>
2662 item_type = ItemType::StructField,
2665 name = field.name.as_ref().unwrap(),
2667 if let Some(stability_class) = field.stability_class() {
2668 write!(w, "<span class='stab {stab}'></span>",
2669 stab = stability_class)?;
2671 document(w, cx, field)?;
2675 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2678 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2679 s: &clean::Union) -> fmt::Result {
2680 write!(w, "<pre class='rust union'>")?;
2681 render_attributes(w, it)?;
2688 write!(w, "</pre>")?;
2690 document(w, cx, it)?;
2691 let mut fields = s.fields.iter().filter_map(|f| {
2693 clean::StructFieldItem(ref ty) => Some((f, ty)),
2697 if fields.peek().is_some() {
2698 write!(w, "<h2 id='fields' class='fields small-section-header'>
2699 Fields<a href='#fields' class='anchor'></a></h2>")?;
2700 for (field, ty) in fields {
2701 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2703 shortty = ItemType::StructField,
2704 name = field.name.as_ref().unwrap(),
2706 if let Some(stability_class) = field.stability_class() {
2707 write!(w, "<span class='stab {stab}'></span>",
2708 stab = stability_class)?;
2710 document(w, cx, field)?;
2713 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2716 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2717 e: &clean::Enum) -> fmt::Result {
2718 write!(w, "<pre class='rust enum'>")?;
2719 render_attributes(w, it)?;
2720 write!(w, "{}enum {}{}{}",
2721 VisSpace(&it.visibility),
2722 it.name.as_ref().unwrap(),
2724 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2725 if e.variants.is_empty() && !e.variants_stripped {
2726 write!(w, " {{}}")?;
2728 write!(w, " {{\n")?;
2729 for v in &e.variants {
2731 let name = v.name.as_ref().unwrap();
2733 clean::VariantItem(ref var) => {
2735 clean::VariantKind::CLike => write!(w, "{}", name)?,
2736 clean::VariantKind::Tuple(ref tys) => {
2737 write!(w, "{}(", name)?;
2738 for (i, ty) in tys.iter().enumerate() {
2740 write!(w, ", ")?
2742 write!(w, "{}", *ty)?;
2746 clean::VariantKind::Struct(ref s) => {
2762 if e.variants_stripped {
2763 write!(w, " // some variants omitted\n")?;
2767 write!(w, "</pre>")?;
2769 document(w, cx, it)?;
2770 if !e.variants.is_empty() {
2771 write!(w, "<h2 id='variants' class='variants small-section-header'>
2772 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2773 for variant in &e.variants {
2774 let id = derive_id(format!("{}.{}",
2776 variant.name.as_ref().unwrap()));
2777 let ns_id = derive_id(format!("{}.{}",
2778 variant.name.as_ref().unwrap(),
2779 ItemType::Variant.name_space()));
2780 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2781 <a href=\"#{id}\" class=\"anchor field\"></a>\
2782 <span id='{ns_id}' class='invisible'><code>{name}",
2785 name = variant.name.as_ref().unwrap())?;
2786 if let clean::VariantItem(ref var) = variant.inner {
2787 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2789 for (i, ty) in tys.iter().enumerate() {
2791 write!(w, ", ")?;
2793 write!(w, "{}", *ty)?;
2798 write!(w, "</code></span></span>")?;
2799 document(w, cx, variant)?;
2801 use clean::{Variant, VariantKind};
2802 if let clean::VariantItem(Variant {
2803 kind: VariantKind::Struct(ref s)
2804 }) = variant.inner {
2805 let variant_id = derive_id(format!("{}.{}.fields",
2807 variant.name.as_ref().unwrap()));
2808 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2810 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2811 <table>", name = variant.name.as_ref().unwrap())?;
2812 for field in &s.fields {
2813 use clean::StructFieldItem;
2814 if let StructFieldItem(ref ty) = field.inner {
2815 let id = derive_id(format!("variant.{}.field.{}",
2816 variant.name.as_ref().unwrap(),
2817 field.name.as_ref().unwrap()));
2818 let ns_id = derive_id(format!("{}.{}.{}.{}",
2819 variant.name.as_ref().unwrap(),
2820 ItemType::Variant.name_space(),
2821 field.name.as_ref().unwrap(),
2822 ItemType::StructField.name_space()));
2823 write!(w, "<tr><td \
2825 <span id='{ns_id}' class='invisible'>\
2826 <code>{f}: {t}</code></span></td><td>",
2829 f = field.name.as_ref().unwrap(),
2831 document(w, cx, field)?;
2832 write!(w, "</td></tr>")?;
2835 write!(w, "</table></span>")?;
2837 render_stability_since(w, variant, it)?;
2840 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2844 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2845 let name = attr.name();
2848 Some(format!("{}", name))
2849 } else if let Some(v) = attr.value_str() {
2850 Some(format!("{} = {:?}", name, v.as_str()))
2851 } else if let Some(values) = attr.meta_item_list() {
2852 let display: Vec<_> = values.iter().filter_map(|attr| {
2853 attr.meta_item().and_then(|mi| render_attribute(mi))
2856 if display.len() > 0 {
2857 Some(format!("{}({})", name, display.join(", ")))
2866 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2873 "unsafe_destructor_blind_to_params"
2876 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2877 let mut attrs = String::new();
2879 for attr in &it.attrs.other_attrs {
2880 let name = attr.name().unwrap();
2881 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2884 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2885 attrs.push_str(&format!("#[{}]\n", s));
2888 if attrs.len() > 0 {
2889 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2894 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2895 g: Option<&clean::Generics>,
2896 ty: doctree::StructType,
2897 fields: &[clean::Item],
2899 structhead: bool) -> fmt::Result {
2901 VisSpace(&it.visibility),
2902 if structhead {"struct "} else {""},
2903 it.name.as_ref().unwrap())?;
2904 if let Some(g) = g {
2909 if let Some(g) = g {
2910 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2912 let mut has_visible_fields = false;
2914 for field in fields {
2915 if let clean::StructFieldItem(ref ty) = field.inner {
2916 write!(w, "\n{} {}{}: {},",
2918 VisSpace(&field.visibility),
2919 field.name.as_ref().unwrap(),
2921 has_visible_fields = true;
2925 if has_visible_fields {
2926 if it.has_stripped_fields().unwrap() {
2927 write!(w, "\n{} // some fields omitted", tab)?;
2929 write!(w, "\n{}", tab)?;
2930 } else if it.has_stripped_fields().unwrap() {
2931 // If there are no visible fields we can just display
2932 // `{ /* fields omitted */ }` to save space.
2933 write!(w, " /* fields omitted */ ")?;
2939 for (i, field) in fields.iter().enumerate() {
2944 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2947 clean::StructFieldItem(ref ty) => {
2948 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2954 if let Some(g) = g {
2955 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2960 // Needed for PhantomData.
2961 if let Some(g) = g {
2962 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2970 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2971 g: Option<&clean::Generics>,
2972 fields: &[clean::Item],
2974 structhead: bool) -> fmt::Result {
2976 VisSpace(&it.visibility),
2977 if structhead {"union "} else {""},
2978 it.name.as_ref().unwrap())?;
2979 if let Some(g) = g {
2980 write!(w, "{}", g)?;
2981 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
2984 write!(w, " {{\n{}", tab)?;
2985 for field in fields {
2986 if let clean::StructFieldItem(ref ty) = field.inner {
2987 write!(w, " {}{}: {},\n{}",
2988 VisSpace(&field.visibility),
2989 field.name.as_ref().unwrap(),
2995 if it.has_stripped_fields().unwrap() {
2996 write!(w, " // some fields omitted\n{}", tab)?;
3002 #[derive(Copy, Clone)]
3003 enum AssocItemLink<'a> {
3004 Anchor(Option<&'a str>),
3005 GotoSource(DefId, &'a FxHashSet<String>),
3008 impl<'a> AssocItemLink<'a> {
3009 fn anchor(&self, id: &'a String) -> Self {
3011 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3012 ref other => *other,
3017 enum AssocItemRender<'a> {
3019 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3022 #[derive(Copy, Clone, PartialEq)]
3025 ForDeref { mut_: bool },
3028 fn render_assoc_items(w: &mut fmt::Formatter,
3030 containing_item: &clean::Item,
3032 what: AssocItemRender) -> fmt::Result {
3034 let v = match c.impls.get(&it) {
3036 None => return Ok(()),
3038 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3039 i.inner_impl().trait_.is_none()
3041 if !non_trait.is_empty() {
3042 let render_mode = match what {
3043 AssocItemRender::All => {
3045 <h2 id='methods' class='small-section-header'>
3046 Methods<a href='#methods' class='anchor'></a>
3051 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3053 <h2 id='deref-methods' class='small-section-header'>
3054 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3057 RenderMode::ForDeref { mut_: deref_mut_ }
3060 for i in &non_trait {
3061 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3062 containing_item.stable_since(), true)?;
3065 if let AssocItemRender::DerefFor { .. } = what {
3068 if !traits.is_empty() {
3069 let deref_impl = traits.iter().find(|t| {
3070 t.inner_impl().trait_.def_id() == c.deref_trait_did
3072 if let Some(impl_) = deref_impl {
3073 let has_deref_mut = traits.iter().find(|t| {
3074 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3076 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3079 <h2 id='implementations' class='small-section-header'>
3080 Trait Implementations<a href='#implementations' class='anchor'></a>
3084 let did = i.trait_did().unwrap();
3085 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3086 render_impl(w, cx, i, assoc_link,
3087 RenderMode::Normal, containing_item.stable_since(), true)?;
3093 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3094 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3095 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3096 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3098 clean::TypedefItem(ref t, true) => Some(&t.type_),
3101 }).next().expect("Expected associated type binding");
3102 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3103 deref_mut_: deref_mut };
3104 if let Some(did) = target.def_id() {
3105 render_assoc_items(w, cx, container_item, did, what)
3107 if let Some(prim) = target.primitive_type() {
3108 if let Some(&did) = cache().primitive_locations.get(&prim) {
3109 render_assoc_items(w, cx, container_item, did, what)?;
3116 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3117 let self_type_opt = match item.inner {
3118 clean::MethodItem(ref method) => method.decl.self_type(),
3119 clean::TyMethodItem(ref method) => method.decl.self_type(),
3123 if let Some(self_ty) = self_type_opt {
3124 let (by_mut_ref, by_box, by_value) = match self_ty {
3125 SelfTy::SelfBorrowed(_, mutability) |
3126 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3127 (mutability == Mutability::Mutable, false, false)
3129 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3130 (false, Some(did) == cache().owned_box_did, false)
3132 SelfTy::SelfValue => (false, false, true),
3133 _ => (false, false, false),
3136 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3142 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3143 let mut out = String::new();
3146 clean::FunctionItem(clean::Function { ref decl, .. }) |
3147 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3148 clean::MethodItem(clean::Method { ref decl, .. }) |
3149 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3150 out = spotlight_decl(decl)?;
3158 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3159 let mut out = String::new();
3160 let mut trait_ = String::new();
3162 if let Some(did) = decl.output.def_id() {
3164 if let Some(impls) = c.impls.get(&did) {
3166 let impl_ = i.inner_impl();
3167 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3170 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3171 <code class=\"content\">",
3173 trait_.push_str(&format!("{}", impl_.for_));
3176 //use the "where" class here to make it small
3177 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3178 let t_did = impl_.trait_.def_id().unwrap();
3179 for it in &impl_.items {
3180 if let clean::TypedefItem(ref tydef, _) = it.inner {
3181 out.push_str("<span class=\"where fmt-newline\"> ");
3182 assoc_type(&mut out, it, &vec![],
3184 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3185 out.push_str(";</span>");
3193 if !out.is_empty() {
3194 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3195 <span class='tooltiptext'>Important traits for {}</span></div>\
3196 <div class=\"content hidden\">",
3198 out.push_str("</code></div></div>");
3204 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3205 render_mode: RenderMode, outer_version: Option<&str>,
3206 show_def_docs: bool) -> fmt::Result {
3207 if render_mode == RenderMode::Normal {
3208 let id = derive_id(match i.inner_impl().trait_ {
3209 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3210 None => "impl".to_string(),
3212 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3213 id, i.inner_impl())?;
3214 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3215 write!(w, "</span><span class='out-of-band'>")?;
3216 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3217 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3218 write!(w, "<div class='ghost'></div>")?;
3219 render_stability_since_raw(w, since, outer_version)?;
3220 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3221 l, "goto source code")?;
3223 render_stability_since_raw(w, since, outer_version)?;
3225 write!(w, "</span>")?;
3226 write!(w, "</h3>\n")?;
3227 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3228 write!(w, "<div class='docblock'>{}</div>",
3229 Markdown(&*dox, &i.impl_item.links()))?;
3233 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3234 link: AssocItemLink, render_mode: RenderMode,
3235 is_default_item: bool, outer_version: Option<&str>,
3236 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3237 let item_type = item.type_();
3238 let name = item.name.as_ref().unwrap();
3240 let render_method_item: bool = match render_mode {
3241 RenderMode::Normal => true,
3242 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3246 clean::MethodItem(clean::Method { ref decl, .. }) |
3247 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3248 // Only render when the method is not static or we allow static methods
3249 if render_method_item {
3250 let id = derive_id(format!("{}.{}", item_type, name));
3251 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3252 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3253 write!(w, "{}", spotlight_decl(decl)?)?;
3254 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3255 write!(w, "<code>")?;
3256 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3257 write!(w, "</code>")?;
3258 if let Some(l) = (Item { cx, item }).src_href() {
3259 write!(w, "</span><span class='out-of-band'>")?;
3260 write!(w, "<div class='ghost'></div>")?;
3261 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3262 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3263 l, "goto source code")?;
3265 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3267 write!(w, "</span></h4>\n")?;
3270 clean::TypedefItem(ref tydef, _) => {
3271 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3272 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3273 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3274 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3275 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3276 write!(w, "</code></span></h4>\n")?;
3278 clean::AssociatedConstItem(ref ty, ref default) => {
3279 let id = derive_id(format!("{}.{}", item_type, name));
3280 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3281 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3282 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3283 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3284 write!(w, "</code></span></h4>\n")?;
3286 clean::AssociatedTypeItem(ref bounds, ref default) => {
3287 let id = derive_id(format!("{}.{}", item_type, name));
3288 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3289 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3290 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3291 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3292 write!(w, "</code></span></h4>\n")?;
3294 clean::StrippedItem(..) => return Ok(()),
3295 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3298 if render_method_item || render_mode == RenderMode::Normal {
3299 let prefix = render_assoc_const_value(item);
3301 if !is_default_item {
3302 if let Some(t) = trait_ {
3303 // The trait item may have been stripped so we might not
3304 // find any documentation or stability for it.
3305 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3306 // We need the stability of the item from the trait
3307 // because impls can't have a stability.
3308 document_stability(w, cx, it)?;
3309 if item.doc_value().is_some() {
3310 document_full(w, item, cx, &prefix)?;
3311 } else if show_def_docs {
3312 // In case the item isn't documented,
3313 // provide short documentation from the trait.
3314 document_short(w, it, link, &prefix)?;
3318 document_stability(w, cx, item)?;
3320 document_full(w, item, cx, &prefix)?;
3324 document_stability(w, cx, item)?;
3326 document_short(w, item, link, &prefix)?;
3333 let traits = &cache().traits;
3334 let trait_ = i.trait_did().map(|did| &traits[&did]);
3337 write!(w, "<span class='docblock autohide'>")?;
3340 write!(w, "<div class='impl-items'>")?;
3341 for trait_item in &i.inner_impl().items {
3342 doc_impl_item(w, cx, trait_item, link, render_mode,
3343 false, outer_version, trait_, show_def_docs)?;
3346 fn render_default_items(w: &mut fmt::Formatter,
3350 render_mode: RenderMode,
3351 outer_version: Option<&str>,
3352 show_def_docs: bool) -> fmt::Result {
3353 for trait_item in &t.items {
3354 let n = trait_item.name.clone();
3355 if i.items.iter().find(|m| m.name == n).is_some() {
3358 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3359 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3361 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3362 outer_version, None, show_def_docs)?;
3367 // If we've implemented a trait, then also emit documentation for all
3368 // default items which weren't overridden in the implementation block.
3369 if let Some(t) = trait_ {
3370 render_default_items(w, cx, t, &i.inner_impl(),
3371 render_mode, outer_version, show_def_docs)?;
3373 write!(w, "</div>")?;
3376 write!(w, "</span>")?;
3382 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3383 t: &clean::Typedef) -> fmt::Result {
3384 write!(w, "<pre class='rust typedef'>")?;
3385 render_attributes(w, it)?;
3386 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3387 it.name.as_ref().unwrap(),
3389 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3392 document(w, cx, it)?;
3394 // Render any items associated directly to this alias, as otherwise they
3395 // won't be visible anywhere in the docs. It would be nice to also show
3396 // associated items from the aliased type (see discussion in #32077), but
3397 // we need #14072 to make sense of the generics.
3398 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3401 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3402 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3403 render_attributes(w, it)?;
3406 " {}type {};\n}}</pre>",
3407 VisSpace(&it.visibility),
3408 it.name.as_ref().unwrap(),
3411 document(w, cx, it)?;
3413 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3416 impl<'a> fmt::Display for Sidebar<'a> {
3417 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3420 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3421 let mut should_close = false;
3423 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3424 || it.is_enum() || it.is_mod() || it.is_typedef()
3426 write!(fmt, "<p class='location'>")?;
3428 clean::StructItem(..) => write!(fmt, "Struct ")?,
3429 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3430 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3431 clean::UnionItem(..) => write!(fmt, "Union ")?,
3432 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3433 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3434 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3435 clean::ModuleItem(..) => if it.is_crate() {
3436 write!(fmt, "Crate ")?;
3438 write!(fmt, "Module ")?;
3442 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3443 write!(fmt, "</p>")?;
3446 if let Some(ref version) = cache().crate_version {
3448 "<div class='block version'>\
3455 write!(fmt, "<div class=\"sidebar-elems\">")?;
3456 should_close = true;
3458 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3459 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3460 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3461 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3462 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3463 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3464 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3465 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3470 // The sidebar is designed to display sibling functions, modules and
3471 // other miscellaneous information. since there are lots of sibling
3472 // items (and that causes quadratic growth in large modules),
3473 // we refactor common parts into a shared JavaScript file per module.
3474 // still, we don't move everything into JS because we want to preserve
3475 // as much HTML as possible in order to allow non-JS-enabled browsers
3476 // to navigate the documentation (though slightly inefficiently).
3478 write!(fmt, "<p class='location'>")?;
3479 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3481 write!(fmt, "::<wbr>")?;
3483 write!(fmt, "<a href='{}index.html'>{}</a>",
3484 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3487 write!(fmt, "</p>")?;
3489 // Sidebar refers to the enclosing module, not this module.
3490 let relpath = if it.is_mod() { "../" } else { "" };
3492 "<script>window.sidebarCurrent = {{\
3497 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3498 ty = it.type_().css_class(),
3501 // There is no sidebar-items.js beyond the crate root path
3502 // FIXME maybe dynamic crate loading can be merged here
3504 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3508 // Closes sidebar-elems div.
3509 write!(fmt, "</div>")?;
3516 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3517 i.items.iter().filter_map(|item| {
3519 // Maybe check with clean::Visibility::Public as well?
3520 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3521 if !for_deref || should_render_item(item, false) {
3522 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3529 }).collect::<Vec<_>>()
3532 // The point is to url encode any potential character from a type with genericity.
3533 fn small_url_encode(s: &str) -> String {
3534 s.replace("<", "%3C")
3535 .replace(">", "%3E")
3536 .replace(" ", "%20")
3537 .replace("?", "%3F")
3538 .replace("'", "%27")
3539 .replace("&", "%26")
3540 .replace(",", "%2C")
3541 .replace(":", "%3A")
3542 .replace(";", "%3B")
3543 .replace("[", "%5B")
3544 .replace("]", "%5D")
3545 .replace("\"", "%22")
3548 fn sidebar_assoc_items(it: &clean::Item) -> String {
3549 let mut out = String::new();
3551 if let Some(v) = c.impls.get(&it.def_id) {
3553 .filter(|i| i.inner_impl().trait_.is_none())
3554 .flat_map(|i| get_methods(i.inner_impl(), false))
3555 .collect::<String>();
3556 if !ret.is_empty() {
3557 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3558 </a><div class=\"sidebar-links\">{}</div>", ret));
3561 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3562 if let Some(impl_) = v.iter()
3563 .filter(|i| i.inner_impl().trait_.is_some())
3564 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3565 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3567 clean::TypedefItem(ref t, true) => Some(&t.type_),
3571 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3572 c.primitive_locations.get(&prim).cloned()
3573 })).and_then(|did| c.impls.get(&did));
3574 if let Some(impls) = inner_impl {
3575 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3576 out.push_str(&format!("Methods from {}<Target={}>",
3577 Escape(&format!("{:#}",
3578 impl_.inner_impl().trait_.as_ref().unwrap())),
3579 Escape(&format!("{:#}", target))));
3580 out.push_str("</a>");
3581 let ret = impls.iter()
3582 .filter(|i| i.inner_impl().trait_.is_none())
3583 .flat_map(|i| get_methods(i.inner_impl(), true))
3584 .collect::<String>();
3585 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3589 let mut links = HashSet::new();
3592 let is_negative_impl = is_negative_impl(i.inner_impl());
3593 if let Some(ref i) = i.inner_impl().trait_ {
3594 let i_display = format!("{:#}", i);
3595 let out = Escape(&i_display);
3596 let encoded = small_url_encode(&format!("{:#}", i));
3597 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3599 if is_negative_impl { "!" } else { "" },
3601 if !links.contains(&generated) && links.insert(generated.clone()) {
3610 .collect::<String>();
3611 if !ret.is_empty() {
3612 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3613 Trait Implementations</a>");
3614 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3622 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3623 s: &clean::Struct) -> fmt::Result {
3624 let mut sidebar = String::new();
3625 let fields = get_struct_fields_name(&s.fields);
3627 if !fields.is_empty() {
3628 if let doctree::Plain = s.struct_type {
3629 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3630 <div class=\"sidebar-links\">{}</div>", fields));
3634 sidebar.push_str(&sidebar_assoc_items(it));
3636 if !sidebar.is_empty() {
3637 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3642 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3644 clean::ItemEnum::ImplItem(ref i) => {
3645 if let Some(ref trait_) = i.trait_ {
3646 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3655 fn is_negative_impl(i: &clean::Impl) -> bool {
3656 i.polarity == Some(clean::ImplPolarity::Negative)
3659 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3660 t: &clean::Trait) -> fmt::Result {
3661 let mut sidebar = String::new();
3667 Some(ref name) if m.is_associated_type() => {
3668 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3674 .collect::<String>();
3675 let consts = t.items
3679 Some(ref name) if m.is_associated_const() => {
3680 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3686 .collect::<String>();
3687 let required = t.items
3691 Some(ref name) if m.is_ty_method() => {
3692 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3698 .collect::<String>();
3699 let provided = t.items
3703 Some(ref name) if m.is_method() => {
3704 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3709 .collect::<String>();
3711 if !types.is_empty() {
3712 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3713 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3716 if !consts.is_empty() {
3717 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3718 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3721 if !required.is_empty() {
3722 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3723 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3726 if !provided.is_empty() {
3727 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3728 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3734 if let Some(implementors) = c.implementors.get(&it.def_id) {
3735 let res = implementors.iter()
3736 .filter(|i| i.inner_impl().for_.def_id()
3737 .map_or(false, |d| !c.paths.contains_key(&d)))
3739 match extract_for_impl_name(&i.impl_item) {
3740 Some((ref name, ref url)) => {
3741 Some(format!("<a href=\"#impl-{}\">{}</a>",
3742 small_url_encode(url),
3748 .collect::<String>();
3749 if !res.is_empty() {
3750 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3751 Implementations on Foreign Types</a><div \
3752 class=\"sidebar-links\">{}</div>",
3757 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3759 sidebar.push_str(&sidebar_assoc_items(it));
3761 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3764 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3765 _p: &clean::PrimitiveType) -> fmt::Result {
3766 let sidebar = sidebar_assoc_items(it);
3768 if !sidebar.is_empty() {
3769 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3774 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3775 _t: &clean::Typedef) -> fmt::Result {
3776 let sidebar = sidebar_assoc_items(it);
3778 if !sidebar.is_empty() {
3779 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3784 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3786 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3791 .filter_map(|f| match f.name {
3792 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3793 {name}</a>", name=name)),
3799 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3800 u: &clean::Union) -> fmt::Result {
3801 let mut sidebar = String::new();
3802 let fields = get_struct_fields_name(&u.fields);
3804 if !fields.is_empty() {
3805 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3806 <div class=\"sidebar-links\">{}</div>", fields));
3809 sidebar.push_str(&sidebar_assoc_items(it));
3811 if !sidebar.is_empty() {
3812 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3817 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3818 e: &clean::Enum) -> fmt::Result {
3819 let mut sidebar = String::new();
3821 let variants = e.variants.iter()
3822 .filter_map(|v| match v.name {
3823 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3824 </a>", name = name)),
3827 .collect::<String>();
3828 if !variants.is_empty() {
3829 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3830 <div class=\"sidebar-links\">{}</div>", variants));
3833 sidebar.push_str(&sidebar_assoc_items(it));
3835 if !sidebar.is_empty() {
3836 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3841 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3842 items: &[clean::Item]) -> fmt::Result {
3843 let mut sidebar = String::new();
3845 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3846 it.type_() == ItemType::Import) {
3847 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3849 name = "Re-exports"));
3852 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3853 // to print its headings
3854 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3855 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3856 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3857 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3858 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3859 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3860 let (short, name) = match myty {
3861 ItemType::ExternCrate |
3862 ItemType::Import => ("reexports", "Re-exports"),
3863 ItemType::Module => ("modules", "Modules"),
3864 ItemType::Struct => ("structs", "Structs"),
3865 ItemType::Union => ("unions", "Unions"),
3866 ItemType::Enum => ("enums", "Enums"),
3867 ItemType::Function => ("functions", "Functions"),
3868 ItemType::Typedef => ("types", "Type Definitions"),
3869 ItemType::Static => ("statics", "Statics"),
3870 ItemType::Constant => ("constants", "Constants"),
3871 ItemType::Trait => ("traits", "Traits"),
3872 ItemType::Impl => ("impls", "Implementations"),
3873 ItemType::TyMethod => ("tymethods", "Type Methods"),
3874 ItemType::Method => ("methods", "Methods"),
3875 ItemType::StructField => ("fields", "Struct Fields"),
3876 ItemType::Variant => ("variants", "Variants"),
3877 ItemType::Macro => ("macros", "Macros"),
3878 ItemType::Primitive => ("primitives", "Primitive Types"),
3879 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3880 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3881 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
3883 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3889 if !sidebar.is_empty() {
3890 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3895 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3896 let sidebar = sidebar_assoc_items(it);
3897 if !sidebar.is_empty() {
3898 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3903 impl<'a> fmt::Display for Source<'a> {
3904 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3905 let Source(s) = *self;
3906 let lines = s.lines().count();
3908 let mut tmp = lines;
3913 write!(fmt, "<pre class=\"line-numbers\">")?;
3914 for i in 1..lines + 1 {
3915 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3917 write!(fmt, "</pre>")?;
3919 highlight::render_with_highlighting(s, None, None, None, None))?;
3924 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3925 t: &clean::Macro) -> fmt::Result {
3926 w.write_str(&highlight::render_with_highlighting(&t.source,
3934 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3936 _p: &clean::PrimitiveType) -> fmt::Result {
3937 document(w, cx, it)?;
3938 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3941 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3943 fn make_item_keywords(it: &clean::Item) -> String {
3944 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3947 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3948 let decl = match item.inner {
3949 clean::FunctionItem(ref f) => &f.decl,
3950 clean::MethodItem(ref m) => &m.decl,
3951 clean::TyMethodItem(ref m) => &m.decl,
3955 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3956 let output = match decl.output {
3957 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3961 Some(IndexItemFunctionType { inputs: inputs, output: output })
3964 fn get_index_type(clean_type: &clean::Type) -> Type {
3966 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
3967 generics: get_generics(clean_type),
3972 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
3974 clean::ResolvedPath { ref path, .. } => {
3975 let segments = &path.segments;
3976 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
3977 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
3978 clean_type, accept_generic
3980 Some(path_segment.name.clone())
3982 clean::Generic(ref s) if accept_generic => Some(s.clone()),
3983 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3984 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
3985 // FIXME: add all from clean::Type.
3990 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
3991 clean_type.generics()
3993 let r = types.iter()
3994 .filter_map(|t| get_index_type_name(t, false))
3995 .map(|s| s.to_ascii_lowercase())
3996 .collect::<Vec<_>>();
4005 pub fn cache() -> Arc<Cache> {
4006 CACHE_KEY.with(|c| c.borrow().clone())
4011 fn test_unique_id() {
4012 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4013 "method.into_iter", "foo", "main", "search", "methods",
4014 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4015 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4016 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4017 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4020 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4021 assert_eq!(&actual[..], expected);
4030 fn test_name_key() {
4031 assert_eq!(name_key("0"), ("", 0, 1));
4032 assert_eq!(name_key("123"), ("", 123, 0));
4033 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4034 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4035 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4036 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4037 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4038 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4043 fn test_name_sorting() {
4044 let names = ["Apple",
4046 "Fruit", "Fruit0", "Fruit00",
4047 "Fruit1", "Fruit01",
4048 "Fruit2", "Fruit02",
4052 let mut sorted = names.to_owned();
4053 sorted.sort_by_key(|&s| name_key(s));
4054 assert_eq!(names, sorted);