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::ascii::AsciiExt;
40 use std::cell::RefCell;
41 use std::cmp::Ordering;
42 use std::collections::{BTreeMap, HashSet};
43 use std::default::Default;
45 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
46 use std::fs::{self, File, OpenOptions};
47 use std::io::prelude::*;
48 use std::io::{self, BufWriter, BufReader};
49 use std::iter::repeat;
51 use std::path::{PathBuf, Path, Component};
55 use externalfiles::ExternalHtml;
57 use serialize::json::{ToJson, Json, as_json};
58 use syntax::{abi, ast};
59 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
60 use rustc::middle::privacy::AccessLevels;
61 use rustc::middle::stability;
63 use rustc::util::nodemap::{FxHashMap, FxHashSet};
64 use rustc_data_structures::flock;
66 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability, Span};
69 use html::escape::Escape;
70 use html::format::{ConstnessSpace};
71 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
72 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
73 use html::format::fmt_impl_for_trait_page;
74 use html::item_type::ItemType;
75 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, RenderType};
76 use html::{highlight, layout};
80 /// A pair of name and its optional document.
81 pub type NameDoc = (String, Option<String>);
83 /// Major driving force in all rustdoc rendering. This contains information
84 /// about where in the tree-like hierarchy rendering is occurring and controls
85 /// how the current page is being rendered.
87 /// It is intended that this context is a lightweight object which can be fairly
88 /// easily cloned because it is cloned per work-job (about once per item in the
92 /// Current hierarchy of components leading down to what's currently being
94 pub current: Vec<String>,
95 /// The current destination folder of where HTML artifacts should be placed.
96 /// This changes as the context descends into the module hierarchy.
98 /// A flag, which when `true`, will render pages which redirect to the
99 /// real location of an item. This is used to allow external links to
100 /// publicly reused items to redirect to the right location.
101 pub render_redirect_pages: bool,
102 pub shared: Arc<SharedContext>,
103 pub render_type: RenderType,
106 pub struct SharedContext {
107 /// The path to the crate root source minus the file name.
108 /// Used for simplifying paths to the highlighted source code files.
109 pub src_root: PathBuf,
110 /// This describes the layout of each page, and is not modified after
111 /// creation of the context (contains info like the favicon and added html).
112 pub layout: layout::Layout,
113 /// This flag indicates whether [src] links should be generated or not. If
114 /// the source files are present in the html rendering, then this will be
116 pub include_sources: bool,
117 /// The local file sources we've emitted and their respective url-paths.
118 pub local_sources: FxHashMap<PathBuf, String>,
119 /// All the passes that were run on this crate.
120 pub passes: FxHashSet<String>,
121 /// The base-URL of the issue tracker for when an item has been tagged with
123 pub issue_tracker_base_url: Option<String>,
124 /// The given user css file which allow to customize the generated
125 /// documentation theme.
126 pub css_file_extension: Option<PathBuf>,
127 /// Warnings for the user if rendering would differ using different markdown
129 pub markdown_warnings: RefCell<Vec<(Span, String, Vec<html_diff::Difference>)>>,
130 /// The directories that have already been created in this doc run. Used to reduce the number
131 /// of spurious `create_dir_all` calls.
132 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
136 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
137 let mut dirs = self.created_dirs.borrow_mut();
138 if !dirs.contains(dst) {
139 fs::create_dir_all(dst)?;
140 dirs.insert(dst.to_path_buf());
148 /// Returns whether the `collapse-docs` pass was run on this crate.
149 pub fn was_collapsed(&self) -> bool {
150 self.passes.contains("collapse-docs")
153 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
154 /// `collapsed_doc_value` of the given item.
155 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
156 if self.was_collapsed() {
157 item.collapsed_doc_value().map(|s| s.into())
159 item.doc_value().map(|s| s.into())
164 /// Indicates where an external crate can be found.
165 pub enum ExternalLocation {
166 /// Remote URL root of the external crate
168 /// This external crate can be found in the local doc/ folder
170 /// The external crate could not be found.
174 /// Metadata about an implementor of a trait.
175 pub struct Implementor {
177 pub stability: Option<clean::Stability>,
178 pub impl_: clean::Impl,
181 /// Metadata about implementations for a type.
184 pub impl_item: clean::Item,
188 fn inner_impl(&self) -> &clean::Impl {
189 match self.impl_item.inner {
190 clean::ImplItem(ref impl_) => impl_,
191 _ => panic!("non-impl item found in impl")
195 fn trait_did(&self) -> Option<DefId> {
196 self.inner_impl().trait_.def_id()
206 impl error::Error for Error {
207 fn description(&self) -> &str {
208 self.error.description()
212 impl Display for Error {
213 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
214 write!(f, "\"{}\": {}", self.file.display(), self.error)
219 pub fn new(e: io::Error, file: &Path) -> Error {
221 file: file.to_path_buf(),
227 macro_rules! try_err {
228 ($e:expr, $file:expr) => ({
231 Err(e) => return Err(Error::new(e, $file)),
236 /// This cache is used to store information about the `clean::Crate` being
237 /// rendered in order to provide more useful documentation. This contains
238 /// information like all implementors of a trait, all traits a type implements,
239 /// documentation for all known traits, etc.
241 /// This structure purposefully does not implement `Clone` because it's intended
242 /// to be a fairly large and expensive structure to clone. Instead this adheres
243 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
244 /// rendering threads.
247 /// Mapping of typaram ids to the name of the type parameter. This is used
248 /// when pretty-printing a type (so pretty printing doesn't have to
249 /// painfully maintain a context like this)
250 pub typarams: FxHashMap<DefId, String>,
252 /// Maps a type id to all known implementations for that type. This is only
253 /// recognized for intra-crate `ResolvedPath` types, and is used to print
254 /// out extra documentation on the page of an enum/struct.
256 /// The values of the map are a list of implementations and documentation
257 /// found on that implementation.
258 pub impls: FxHashMap<DefId, Vec<Impl>>,
260 /// Maintains a mapping of local crate node ids to the fully qualified name
261 /// and "short type description" of that node. This is used when generating
262 /// URLs when a type is being linked to. External paths are not located in
263 /// this map because the `External` type itself has all the information
265 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
267 /// Similar to `paths`, but only holds external paths. This is only used for
268 /// generating explicit hyperlinks to other crates.
269 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
271 /// This map contains information about all known traits of this crate.
272 /// Implementations of a crate should inherit the documentation of the
273 /// parent trait if no extra documentation is specified, and default methods
274 /// should show up in documentation about trait implementations.
275 pub traits: FxHashMap<DefId, clean::Trait>,
277 /// When rendering traits, it's often useful to be able to list all
278 /// implementors of the trait, and this mapping is exactly, that: a mapping
279 /// of trait ids to the list of known implementors of the trait
280 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
282 /// Cache of where external crate documentation can be found.
283 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
285 /// Cache of where documentation for primitives can be found.
286 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
288 // Note that external items for which `doc(hidden)` applies to are shown as
289 // non-reachable while local items aren't. This is because we're reusing
290 // the access levels from crateanalysis.
291 pub access_levels: Arc<AccessLevels<DefId>>,
293 /// The version of the crate being documented, if given fron the `--crate-version` flag.
294 pub crate_version: Option<String>,
296 // Private fields only used when initially crawling a crate to build a cache
299 parent_stack: Vec<DefId>,
300 parent_is_trait_impl: bool,
301 search_index: Vec<IndexItem>,
303 deref_trait_did: Option<DefId>,
304 deref_mut_trait_did: Option<DefId>,
305 owned_box_did: Option<DefId>,
306 masked_crates: FxHashSet<CrateNum>,
308 // In rare case where a structure is defined in one module but implemented
309 // in another, if the implementing module is parsed before defining module,
310 // then the fully qualified name of the structure isn't presented in `paths`
311 // yet when its implementation methods are being indexed. Caches such methods
312 // and their parent id here and indexes them at the end of crate parsing.
313 orphan_impl_items: Vec<(DefId, clean::Item)>,
316 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
317 /// Later on moved into `CACHE_KEY`.
319 pub struct RenderInfo {
320 pub inlined: FxHashSet<DefId>,
321 pub external_paths: ::core::ExternalPaths,
322 pub external_typarams: FxHashMap<DefId, String>,
323 pub deref_trait_did: Option<DefId>,
324 pub deref_mut_trait_did: Option<DefId>,
325 pub owned_box_did: Option<DefId>,
328 /// Helper struct to render all source code to HTML pages
329 struct SourceCollector<'a> {
330 scx: &'a mut SharedContext,
332 /// Root destination to place all HTML output into
336 /// Wrapper struct to render the source code of a file. This will do things like
337 /// adding line numbers to the left-hand side.
338 struct Source<'a>(&'a str);
340 // Helper structs for rendering items/sidebars and carrying along contextual
343 #[derive(Copy, Clone)]
346 item: &'a clean::Item,
349 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
351 /// Struct representing one entry in the JS search index. These are all emitted
352 /// by hand to a large JS file at the end of cache-creation.
358 parent: Option<DefId>,
359 parent_idx: Option<usize>,
360 search_type: Option<IndexItemFunctionType>,
363 impl ToJson for IndexItem {
364 fn to_json(&self) -> Json {
365 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
367 let mut data = Vec::with_capacity(6);
368 data.push((self.ty as usize).to_json());
369 data.push(self.name.to_json());
370 data.push(self.path.to_json());
371 data.push(self.desc.to_json());
372 data.push(self.parent_idx.to_json());
373 data.push(self.search_type.to_json());
379 /// A type used for the search index.
381 name: Option<String>,
382 generics: Option<Vec<String>>,
385 impl ToJson for Type {
386 fn to_json(&self) -> Json {
389 let mut data = BTreeMap::new();
390 data.insert("name".to_owned(), name.to_json());
391 if let Some(ref generics) = self.generics {
392 data.insert("generics".to_owned(), generics.to_json());
401 /// Full type of functions/methods in the search index.
402 struct IndexItemFunctionType {
407 impl ToJson for IndexItemFunctionType {
408 fn to_json(&self) -> Json {
409 // If we couldn't figure out a type, just write `null`.
410 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
413 let mut data = BTreeMap::new();
414 data.insert("inputs".to_owned(), self.inputs.to_json());
415 data.insert("output".to_owned(), self.output.to_json());
421 // TLS keys used to carry information around during rendering.
423 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
424 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
425 RefCell::new(Vec::new()));
426 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
427 RefCell::new(init_ids()));
429 fn init_ids() -> FxHashMap<String, usize> {
445 ].into_iter().map(|id| (String::from(*id), 1)).collect()
448 /// This method resets the local table of used ID attributes. This is typically
449 /// used at the beginning of rendering an entire HTML page to reset from the
450 /// previous state (if any).
451 pub fn reset_ids(embedded: bool) {
452 USED_ID_MAP.with(|s| {
453 *s.borrow_mut() = if embedded {
461 pub fn derive_id(candidate: String) -> String {
462 USED_ID_MAP.with(|map| {
463 let id = match map.borrow_mut().get_mut(&candidate) {
466 let id = format!("{}-{}", candidate, *a);
472 map.borrow_mut().insert(id.clone(), 1);
477 /// Generates the documentation for `crate` into the directory `dst`
478 pub fn run(mut krate: clean::Crate,
479 external_html: &ExternalHtml,
480 playground_url: Option<String>,
482 passes: FxHashSet<String>,
483 css_file_extension: Option<PathBuf>,
484 renderinfo: RenderInfo,
485 render_type: RenderType) -> Result<(), Error> {
486 let src_root = match krate.src.parent() {
487 Some(p) => p.to_path_buf(),
488 None => PathBuf::new(),
490 let mut scx = SharedContext {
493 include_sources: true,
494 local_sources: FxHashMap(),
495 issue_tracker_base_url: None,
496 layout: layout::Layout {
497 logo: "".to_string(),
498 favicon: "".to_string(),
499 external_html: external_html.clone(),
500 krate: krate.name.clone(),
502 css_file_extension: css_file_extension.clone(),
503 markdown_warnings: RefCell::new(vec![]),
504 created_dirs: RefCell::new(FxHashSet()),
507 // If user passed in `--playground-url` arg, we fill in crate name here
508 if let Some(url) = playground_url {
509 markdown::PLAYGROUND.with(|slot| {
510 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
514 // Crawl the crate attributes looking for attributes which control how we're
515 // going to emit HTML
516 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
517 for attr in attrs.lists("doc") {
518 let name = attr.name().map(|s| s.as_str());
519 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
520 (Some("html_favicon_url"), Some(s)) => {
521 scx.layout.favicon = s.to_string();
523 (Some("html_logo_url"), Some(s)) => {
524 scx.layout.logo = s.to_string();
526 (Some("html_playground_url"), Some(s)) => {
527 markdown::PLAYGROUND.with(|slot| {
528 let name = krate.name.clone();
529 *slot.borrow_mut() = Some((Some(name), s.to_string()));
532 (Some("issue_tracker_base_url"), Some(s)) => {
533 scx.issue_tracker_base_url = Some(s.to_string());
535 (Some("html_no_source"), None) if attr.is_word() => {
536 scx.include_sources = false;
542 try_err!(fs::create_dir_all(&dst), &dst);
543 krate = render_sources(&dst, &mut scx, krate)?;
547 render_redirect_pages: false,
548 shared: Arc::new(scx),
552 // Crawl the crate to build various caches used for the output
562 let external_paths = external_paths.into_iter()
563 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
566 let mut cache = Cache {
570 implementors: FxHashMap(),
572 parent_stack: Vec::new(),
573 search_index: Vec::new(),
574 parent_is_trait_impl: false,
575 extern_locations: FxHashMap(),
576 primitive_locations: FxHashMap(),
578 access_levels: krate.access_levels.clone(),
579 crate_version: krate.version.take(),
580 orphan_impl_items: Vec::new(),
581 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
585 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
586 typarams: external_typarams,
589 // Cache where all our extern crates are located
590 for &(n, ref e) in &krate.externs {
591 let src_root = match Path::new(&e.src).parent() {
592 Some(p) => p.to_path_buf(),
593 None => PathBuf::new(),
595 cache.extern_locations.insert(n, (e.name.clone(), src_root,
596 extern_location(e, &cx.dst)));
598 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
599 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
602 // Cache where all known primitives have their documentation located.
604 // Favor linking to as local extern as possible, so iterate all crates in
605 // reverse topological order.
606 for &(_, ref e) in krate.externs.iter().rev() {
607 for &(def_id, prim, _) in &e.primitives {
608 cache.primitive_locations.insert(prim, def_id);
611 for &(def_id, prim, _) in &krate.primitives {
612 cache.primitive_locations.insert(prim, def_id);
615 cache.stack.push(krate.name.clone());
616 krate = cache.fold_crate(krate);
618 // Build our search index
619 let index = build_index(&krate, &mut cache);
621 // Freeze the cache now that the index has been built. Put an Arc into TLS
622 // for future parallelization opportunities
623 let cache = Arc::new(cache);
624 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
625 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
627 write_shared(&cx, &krate, &*cache, index)?;
629 let scx = cx.shared.clone();
631 // And finally render the whole crate's documentation
632 let result = cx.krate(krate);
634 let markdown_warnings = scx.markdown_warnings.borrow();
635 if !markdown_warnings.is_empty() {
636 let mut intro_msg = false;
637 for &(ref span, ref text, ref diffs) in &*markdown_warnings {
639 render_difference(d, &mut intro_msg, span, text);
647 // A short, single-line view of `s`.
648 fn concise_str(mut s: &str) -> String {
649 if s.contains('\n') {
650 s = s.lines().next().expect("Impossible! We just found a newline");
654 let mut hi = s.len() - 20;
655 while !s.is_char_boundary(lo) {
658 while !s.is_char_boundary(hi) {
661 return format!("{} ... {}", &s[..lo], &s[hi..]);
666 // Returns short versions of s1 and s2, starting from where the strings differ.
667 fn concise_compared_strs(s1: &str, s2: &str) -> (String, String) {
670 if !s1.contains('\n') && !s2.contains('\n') && s1.len() <= 70 && s2.len() <= 70 {
671 return (s1.to_owned(), s2.to_owned());
674 let mut start_byte = 0;
675 for (c1, c2) in s1.chars().zip(s2.chars()) {
680 start_byte += c1.len_utf8();
684 return (concise_str(s1), concise_str(s2));
687 let s1 = &s1[start_byte..];
688 let s2 = &s2[start_byte..];
689 (format!("...{}", concise_str(s1)), format!("...{}", concise_str(s2)))
692 fn print_message(msg: &str, intro_msg: &mut bool, span: &Span, text: &str) {
694 println!("WARNING: documentation for this crate may be rendered \
695 differently using the new Pulldown renderer.");
696 println!(" See https://github.com/rust-lang/rust/issues/44229 for details.");
699 println!("WARNING: rendering difference in `{}`", concise_str(text));
700 println!(" --> {}:{}:{}", span.filename, span.loline, span.locol);
704 fn render_difference(diff: &html_diff::Difference, intro_msg: &mut bool, span: &Span, text: &str) {
706 html_diff::Difference::NodeType { ref elem, ref opposite_elem } => {
707 print_message(&format!(" {} Types differ: expected: `{}`, found: `{}`",
708 elem.path, elem.element_name, opposite_elem.element_name),
709 intro_msg, span, text);
711 html_diff::Difference::NodeName { ref elem, ref opposite_elem } => {
712 print_message(&format!(" {} Tags differ: expected: `{}`, found: `{}`",
713 elem.path, elem.element_name, opposite_elem.element_name),
714 intro_msg, span, text);
716 html_diff::Difference::NodeAttributes { ref elem,
718 ref opposite_elem_attributes,
720 print_message(&format!(" {} Attributes differ in `{}`: expected: `{:?}`, \
722 elem.path, elem.element_name, elem_attributes,
723 opposite_elem_attributes),
724 intro_msg, span, text);
726 html_diff::Difference::NodeText { ref elem, ref elem_text, ref opposite_elem_text, .. } => {
727 if elem_text.split("\n")
728 .zip(opposite_elem_text.split("\n"))
729 .any(|(a, b)| a.trim() != b.trim()) {
730 let (s1, s2) = concise_compared_strs(elem_text, opposite_elem_text);
731 print_message(&format!(" {} Text differs:\n expected: `{}`\n \
734 intro_msg, span, text);
737 html_diff::Difference::NotPresent { ref elem, ref opposite_elem } => {
738 if let Some(ref elem) = *elem {
739 print_message(&format!(" {} One element is missing: expected: `{}`",
740 elem.path, elem.element_name),
741 intro_msg, span, text);
742 } else if let Some(ref elem) = *opposite_elem {
743 if elem.element_name.is_empty() {
744 print_message(&format!(" {} One element is missing: expected: `{}`",
745 elem.path, concise_str(&elem.element_content)),
746 intro_msg, span, text);
748 print_message(&format!(" {} Unexpected element `{}`: found: `{}`",
749 elem.path, elem.element_name,
750 concise_str(&elem.element_content)),
751 intro_msg, span, text);
758 /// Build the search index from the collected metadata
759 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
760 let mut nodeid_to_pathid = FxHashMap();
761 let mut crate_items = Vec::with_capacity(cache.search_index.len());
762 let mut crate_paths = Vec::<Json>::new();
764 let Cache { ref mut search_index,
765 ref orphan_impl_items,
766 ref mut paths, .. } = *cache;
768 // Attach all orphan items to the type's definition if the type
769 // has since been learned.
770 for &(did, ref item) in orphan_impl_items {
771 if let Some(&(ref fqp, _)) = paths.get(&did) {
772 search_index.push(IndexItem {
774 name: item.name.clone().unwrap(),
775 path: fqp[..fqp.len() - 1].join("::"),
776 desc: plain_summary_line(item.doc_value()),
779 search_type: get_index_search_type(&item),
784 // Reduce `NodeId` in paths into smaller sequential numbers,
785 // and prune the paths that do not appear in the index.
786 let mut lastpath = String::new();
787 let mut lastpathid = 0usize;
789 for item in search_index {
790 item.parent_idx = item.parent.map(|nodeid| {
791 if nodeid_to_pathid.contains_key(&nodeid) {
792 *nodeid_to_pathid.get(&nodeid).unwrap()
794 let pathid = lastpathid;
795 nodeid_to_pathid.insert(nodeid, pathid);
798 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
799 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
804 // Omit the parent path if it is same to that of the prior item.
805 if lastpath == item.path {
808 lastpath = item.path.clone();
810 crate_items.push(item.to_json());
813 let crate_doc = krate.module.as_ref().map(|module| {
814 plain_summary_line(module.doc_value())
815 }).unwrap_or(String::new());
817 let mut crate_data = BTreeMap::new();
818 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
819 crate_data.insert("items".to_owned(), Json::Array(crate_items));
820 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
822 // Collect the index into a string
823 format!("searchIndex[{}] = {};",
824 as_json(&krate.name),
825 Json::Object(crate_data))
828 fn write_shared(cx: &Context,
829 krate: &clean::Crate,
831 search_index: String) -> Result<(), Error> {
832 // Write out the shared files. Note that these are shared among all rustdoc
833 // docs placed in the output directory, so this needs to be a synchronized
834 // operation with respect to all other rustdocs running around.
835 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
837 // Add all the static files. These may already exist, but we just
838 // overwrite them anyway to make sure that they're fresh and up-to-date.
840 write(cx.dst.join("main.js"),
841 include_bytes!("static/main.js"))?;
842 write(cx.dst.join("rustdoc.css"),
843 include_bytes!("static/rustdoc.css"))?;
844 write(cx.dst.join("main.css"),
845 include_bytes!("static/styles/main.css"))?;
846 if let Some(ref css) = cx.shared.css_file_extension {
847 let mut content = String::new();
848 let css = css.as_path();
849 let mut f = try_err!(File::open(css), css);
851 try_err!(f.read_to_string(&mut content), css);
852 let css = cx.dst.join("theme.css");
853 let css = css.as_path();
854 let mut f = try_err!(File::create(css), css);
855 try_err!(write!(f, "{}", &content), css);
857 write(cx.dst.join("normalize.css"),
858 include_bytes!("static/normalize.css"))?;
859 write(cx.dst.join("FiraSans-Regular.woff"),
860 include_bytes!("static/FiraSans-Regular.woff"))?;
861 write(cx.dst.join("FiraSans-Medium.woff"),
862 include_bytes!("static/FiraSans-Medium.woff"))?;
863 write(cx.dst.join("FiraSans-LICENSE.txt"),
864 include_bytes!("static/FiraSans-LICENSE.txt"))?;
865 write(cx.dst.join("Heuristica-Italic.woff"),
866 include_bytes!("static/Heuristica-Italic.woff"))?;
867 write(cx.dst.join("Heuristica-LICENSE.txt"),
868 include_bytes!("static/Heuristica-LICENSE.txt"))?;
869 write(cx.dst.join("SourceSerifPro-Regular.woff"),
870 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
871 write(cx.dst.join("SourceSerifPro-Bold.woff"),
872 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
873 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
874 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
875 write(cx.dst.join("SourceCodePro-Regular.woff"),
876 include_bytes!("static/SourceCodePro-Regular.woff"))?;
877 write(cx.dst.join("SourceCodePro-Semibold.woff"),
878 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
879 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
880 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
881 write(cx.dst.join("LICENSE-MIT.txt"),
882 include_bytes!("static/LICENSE-MIT.txt"))?;
883 write(cx.dst.join("LICENSE-APACHE.txt"),
884 include_bytes!("static/LICENSE-APACHE.txt"))?;
885 write(cx.dst.join("COPYRIGHT.txt"),
886 include_bytes!("static/COPYRIGHT.txt"))?;
888 fn collect(path: &Path, krate: &str,
889 key: &str) -> io::Result<Vec<String>> {
890 let mut ret = Vec::new();
892 for line in BufReader::new(File::open(path)?).lines() {
894 if !line.starts_with(key) {
897 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
900 ret.push(line.to_string());
906 // Update the search index
907 let dst = cx.dst.join("search-index.js");
908 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
909 all_indexes.push(search_index);
910 // Sort the indexes by crate so the file will be generated identically even
911 // with rustdoc running in parallel.
913 let mut w = try_err!(File::create(&dst), &dst);
914 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
915 for index in &all_indexes {
916 try_err!(writeln!(&mut w, "{}", *index), &dst);
918 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
920 // Update the list of all implementors for traits
921 let dst = cx.dst.join("implementors");
922 for (&did, imps) in &cache.implementors {
923 // Private modules can leak through to this phase of rustdoc, which
924 // could contain implementations for otherwise private types. In some
925 // rare cases we could find an implementation for an item which wasn't
926 // indexed, so we just skip this step in that case.
928 // FIXME: this is a vague explanation for why this can't be a `get`, in
929 // theory it should be...
930 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
932 None => match cache.external_paths.get(&did) {
938 let mut have_impls = false;
939 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
941 // If the trait and implementation are in the same crate, then
942 // there's no need to emit information about it (there's inlining
943 // going on). If they're in different crates then the crate defining
944 // the trait will be interested in our implementation.
945 if imp.def_id.krate == did.krate { continue }
946 // If the implementation is from another crate then that crate
948 if !imp.def_id.is_local() { continue }
950 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
952 implementors.push_str("];");
954 // Only create a js file if we have impls to add to it. If the trait is
955 // documented locally though we always create the file to avoid dead
957 if !have_impls && !cache.paths.contains_key(&did) {
961 let mut mydst = dst.clone();
962 for part in &remote_path[..remote_path.len() - 1] {
965 try_err!(fs::create_dir_all(&mydst), &mydst);
966 mydst.push(&format!("{}.{}.js",
967 remote_item_type.css_class(),
968 remote_path[remote_path.len() - 1]));
970 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
971 all_implementors.push(implementors);
972 // Sort the implementors by crate so the file will be generated
973 // identically even with rustdoc running in parallel.
974 all_implementors.sort();
976 let mut f = try_err!(File::create(&mydst), &mydst);
977 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
978 for implementor in &all_implementors {
979 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
981 try_err!(writeln!(&mut f, "{}", r"
982 if (window.register_implementors) {
983 window.register_implementors(implementors);
985 window.pending_implementors = implementors;
988 try_err!(writeln!(&mut f, r"}})()"), &mydst);
993 fn render_sources(dst: &Path, scx: &mut SharedContext,
994 krate: clean::Crate) -> Result<clean::Crate, Error> {
995 info!("emitting source files");
996 let dst = dst.join("src").join(&krate.name);
997 try_err!(fs::create_dir_all(&dst), &dst);
998 let mut folder = SourceCollector {
1002 Ok(folder.fold_crate(krate))
1005 /// Writes the entire contents of a string to a destination, not attempting to
1006 /// catch any errors.
1007 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1008 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
1011 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1012 /// things like ".." to components which preserve the "top down" hierarchy of a
1013 /// static HTML tree. Each component in the cleaned path will be passed as an
1014 /// argument to `f`. The very last component of the path (ie the file name) will
1015 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1016 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1017 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1018 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1021 // make it relative, if possible
1022 let p = p.strip_prefix(src_root).unwrap_or(p);
1024 let mut iter = p.components().peekable();
1026 while let Some(c) = iter.next() {
1027 if !keep_filename && iter.peek().is_none() {
1032 Component::ParentDir => f("up"),
1033 Component::Normal(c) => f(c.to_str().unwrap()),
1039 /// Attempts to find where an external crate is located, given that we're
1040 /// rendering in to the specified source destination.
1041 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1042 // See if there's documentation generated into the local directory
1043 let local_location = dst.join(&e.name);
1044 if local_location.is_dir() {
1048 // Failing that, see if there's an attribute specifying where to find this
1050 e.attrs.lists("doc")
1051 .filter(|a| a.check_name("html_root_url"))
1052 .filter_map(|a| a.value_str())
1054 let mut url = url.to_string();
1055 if !url.ends_with("/") {
1059 }).next().unwrap_or(Unknown) // Well, at least we tried.
1062 impl<'a> DocFolder for SourceCollector<'a> {
1063 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1064 // If we're including source files, and we haven't seen this file yet,
1065 // then we need to render it out to the filesystem.
1066 if self.scx.include_sources
1067 // skip all invalid spans
1068 && item.source.filename != ""
1069 // skip non-local items
1070 && item.def_id.is_local()
1071 // Macros from other libraries get special filenames which we can
1073 && !(item.source.filename.starts_with("<")
1074 && item.source.filename.ends_with("macros>")) {
1076 // If it turns out that we couldn't read this file, then we probably
1077 // can't read any of the files (generating html output from json or
1078 // something like that), so just don't include sources for the
1079 // entire crate. The other option is maintaining this mapping on a
1080 // per-file basis, but that's probably not worth it...
1082 .include_sources = match self.emit_source(&item.source.filename) {
1085 println!("warning: source code was requested to be rendered, \
1086 but processing `{}` had an error: {}",
1087 item.source.filename, e);
1088 println!(" skipping rendering of source code");
1093 self.fold_item_recur(item)
1097 impl<'a> SourceCollector<'a> {
1098 /// Renders the given filename into its corresponding HTML source file.
1099 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
1100 let p = PathBuf::from(filename);
1101 if self.scx.local_sources.contains_key(&p) {
1102 // We've already emitted this source
1106 let mut contents = Vec::new();
1107 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
1109 let contents = str::from_utf8(&contents).unwrap();
1111 // Remove the utf-8 BOM if any
1112 let contents = if contents.starts_with("\u{feff}") {
1118 // Create the intermediate directories
1119 let mut cur = self.dst.clone();
1120 let mut root_path = String::from("../../");
1121 let mut href = String::new();
1122 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1123 cur.push(component);
1124 fs::create_dir_all(&cur).unwrap();
1125 root_path.push_str("../");
1126 href.push_str(component);
1129 let mut fname = p.file_name().expect("source has no filename")
1131 fname.push(".html");
1133 href.push_str(&fname.to_string_lossy());
1135 let mut w = BufWriter::new(File::create(&cur)?);
1136 let title = format!("{} -- source", cur.file_name().unwrap()
1137 .to_string_lossy());
1138 let desc = format!("Source to the Rust file `{}`.", filename);
1139 let page = layout::Page {
1141 css_class: "source",
1142 root_path: &root_path,
1144 keywords: BASIC_KEYWORDS,
1146 layout::render(&mut w, &self.scx.layout,
1147 &page, &(""), &Source(contents),
1148 self.scx.css_file_extension.is_some())?;
1150 self.scx.local_sources.insert(p, href);
1155 impl DocFolder for Cache {
1156 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1157 // If this is a stripped module,
1158 // we don't want it or its children in the search index.
1159 let orig_stripped_mod = match item.inner {
1160 clean::StrippedItem(box clean::ModuleItem(..)) => {
1161 mem::replace(&mut self.stripped_mod, true)
1163 _ => self.stripped_mod,
1166 // Register any generics to their corresponding string. This is used
1167 // when pretty-printing types.
1168 if let Some(generics) = item.inner.generics() {
1169 self.generics(generics);
1172 // Propagate a trait method's documentation to all implementors of the
1174 if let clean::TraitItem(ref t) = item.inner {
1175 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1178 // Collect all the implementors of traits.
1179 if let clean::ImplItem(ref i) = item.inner {
1180 if !self.masked_crates.contains(&item.def_id.krate) {
1181 if let Some(did) = i.trait_.def_id() {
1182 if i.for_.def_id().map_or(true, |d| !self.masked_crates.contains(&d.krate)) {
1183 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1184 def_id: item.def_id,
1185 stability: item.stability.clone(),
1193 // Index this method for searching later on.
1194 if let Some(ref s) = item.name {
1195 let (parent, is_inherent_impl_item) = match item.inner {
1196 clean::StrippedItem(..) => ((None, None), false),
1197 clean::AssociatedConstItem(..) |
1198 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1199 // skip associated items in trait impls
1200 ((None, None), false)
1202 clean::AssociatedTypeItem(..) |
1203 clean::TyMethodItem(..) |
1204 clean::StructFieldItem(..) |
1205 clean::VariantItem(..) => {
1206 ((Some(*self.parent_stack.last().unwrap()),
1207 Some(&self.stack[..self.stack.len() - 1])),
1210 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1211 if self.parent_stack.is_empty() {
1212 ((None, None), false)
1214 let last = self.parent_stack.last().unwrap();
1216 let path = match self.paths.get(&did) {
1217 // The current stack not necessarily has correlation
1218 // for where the type was defined. On the other
1219 // hand, `paths` always has the right
1220 // information if present.
1221 Some(&(ref fqp, ItemType::Trait)) |
1222 Some(&(ref fqp, ItemType::Struct)) |
1223 Some(&(ref fqp, ItemType::Union)) |
1224 Some(&(ref fqp, ItemType::Enum)) =>
1225 Some(&fqp[..fqp.len() - 1]),
1226 Some(..) => Some(&*self.stack),
1229 ((Some(*last), path), true)
1232 _ => ((None, Some(&*self.stack)), false)
1236 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1237 debug_assert!(!item.is_stripped());
1239 // A crate has a module at its root, containing all items,
1240 // which should not be indexed. The crate-item itself is
1241 // inserted later on when serializing the search-index.
1242 if item.def_id.index != CRATE_DEF_INDEX {
1243 self.search_index.push(IndexItem {
1245 name: s.to_string(),
1246 path: path.join("::").to_string(),
1247 desc: plain_summary_line(item.doc_value()),
1250 search_type: get_index_search_type(&item),
1254 (Some(parent), None) if is_inherent_impl_item => {
1255 // We have a parent, but we don't know where they're
1256 // defined yet. Wait for later to index this item.
1257 self.orphan_impl_items.push((parent, item.clone()));
1263 // Keep track of the fully qualified path for this item.
1264 let pushed = match item.name {
1265 Some(ref n) if !n.is_empty() => {
1266 self.stack.push(n.to_string());
1273 clean::StructItem(..) | clean::EnumItem(..) |
1274 clean::TypedefItem(..) | clean::TraitItem(..) |
1275 clean::FunctionItem(..) | clean::ModuleItem(..) |
1276 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1277 clean::ConstantItem(..) | clean::StaticItem(..) |
1278 clean::UnionItem(..) | clean::ForeignTypeItem
1279 if !self.stripped_mod => {
1280 // Reexported items mean that the same id can show up twice
1281 // in the rustdoc ast that we're looking at. We know,
1282 // however, that a reexported item doesn't show up in the
1283 // `public_items` map, so we can skip inserting into the
1284 // paths map if there was already an entry present and we're
1285 // not a public item.
1287 !self.paths.contains_key(&item.def_id) ||
1288 self.access_levels.is_public(item.def_id)
1290 self.paths.insert(item.def_id,
1291 (self.stack.clone(), item.type_()));
1294 // Link variants to their parent enum because pages aren't emitted
1295 // for each variant.
1296 clean::VariantItem(..) if !self.stripped_mod => {
1297 let mut stack = self.stack.clone();
1299 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1302 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1303 self.paths.insert(item.def_id, (self.stack.clone(),
1310 // Maintain the parent stack
1311 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1312 let parent_pushed = match item.inner {
1313 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1314 clean::StructItem(..) | clean::UnionItem(..) => {
1315 self.parent_stack.push(item.def_id);
1316 self.parent_is_trait_impl = false;
1319 clean::ImplItem(ref i) => {
1320 self.parent_is_trait_impl = i.trait_.is_some();
1322 clean::ResolvedPath{ did, .. } => {
1323 self.parent_stack.push(did);
1327 let prim_did = t.primitive_type().and_then(|t| {
1328 self.primitive_locations.get(&t).cloned()
1332 self.parent_stack.push(did);
1343 // Once we've recursively found all the generics, hoard off all the
1344 // implementations elsewhere.
1345 let ret = self.fold_item_recur(item).and_then(|item| {
1346 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1347 // Figure out the id of this impl. This may map to a
1348 // primitive rather than always to a struct/enum.
1349 // Note: matching twice to restrict the lifetime of the `i` borrow.
1350 let mut dids = FxHashSet();
1351 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1352 let masked_trait = i.trait_.def_id().map_or(false,
1353 |d| self.masked_crates.contains(&d.krate));
1356 clean::ResolvedPath { did, .. } |
1357 clean::BorrowedRef {
1358 type_: box clean::ResolvedPath { did, .. }, ..
1363 let did = t.primitive_type().and_then(|t| {
1364 self.primitive_locations.get(&t).cloned()
1367 if let Some(did) = did {
1374 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1375 for bound in generics {
1376 if let Some(did) = bound.def_id() {
1385 self.impls.entry(did).or_insert(vec![]).push(Impl {
1386 impl_item: item.clone(),
1395 if pushed { self.stack.pop().unwrap(); }
1396 if parent_pushed { self.parent_stack.pop().unwrap(); }
1397 self.stripped_mod = orig_stripped_mod;
1398 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1404 fn generics(&mut self, generics: &clean::Generics) {
1405 for typ in &generics.type_params {
1406 self.typarams.insert(typ.did, typ.name.clone());
1412 /// String representation of how to get back to the root path of the 'doc/'
1413 /// folder in terms of a relative URL.
1414 fn root_path(&self) -> String {
1415 repeat("../").take(self.current.len()).collect::<String>()
1418 /// Recurse in the directory structure and change the "root path" to make
1419 /// sure it always points to the top (relatively).
1420 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1421 F: FnOnce(&mut Context) -> T,
1424 panic!("Unexpected empty destination: {:?}", self.current);
1426 let prev = self.dst.clone();
1428 self.current.push(s);
1430 info!("Recursing into {}", self.dst.display());
1434 info!("Recursed; leaving {}", self.dst.display());
1436 // Go back to where we were at
1438 self.current.pop().unwrap();
1443 /// Main method for rendering a crate.
1445 /// This currently isn't parallelized, but it'd be pretty easy to add
1446 /// parallelization to this function.
1447 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1448 let mut item = match krate.module.take() {
1450 None => return Ok(()),
1452 item.name = Some(krate.name);
1454 // Render the crate documentation
1455 let mut work = vec![(self, item)];
1457 while let Some((mut cx, item)) = work.pop() {
1458 cx.item(item, |cx, item| {
1459 work.push((cx.clone(), item))
1465 fn render_item(&self,
1466 writer: &mut io::Write,
1470 // A little unfortunate that this is done like this, but it sure
1471 // does make formatting *a lot* nicer.
1472 CURRENT_LOCATION_KEY.with(|slot| {
1473 *slot.borrow_mut() = self.current.clone();
1476 let mut title = if it.is_primitive() {
1477 // No need to include the namespace for primitive types
1480 self.current.join("::")
1483 if !title.is_empty() {
1484 title.push_str("::");
1486 title.push_str(it.name.as_ref().unwrap());
1488 title.push_str(" - Rust");
1489 let tyname = it.type_().css_class();
1490 let desc = if it.is_crate() {
1491 format!("API documentation for the Rust `{}` crate.",
1492 self.shared.layout.krate)
1494 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1495 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1497 let keywords = make_item_keywords(it);
1498 let page = layout::Page {
1500 root_path: &self.root_path(),
1503 keywords: &keywords,
1508 if !self.render_redirect_pages {
1509 layout::render(writer, &self.shared.layout, &page,
1510 &Sidebar{ cx: self, item: it },
1511 &Item{ cx: self, item: it },
1512 self.shared.css_file_extension.is_some())?;
1514 let mut url = self.root_path();
1515 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1516 for name in &names[..names.len() - 1] {
1520 url.push_str(&item_path(ty, names.last().unwrap()));
1521 layout::redirect(writer, &url)?;
1527 /// Non-parallelized version of rendering an item. This will take the input
1528 /// item, render its contents, and then invoke the specified closure with
1529 /// all sub-items which need to be rendered.
1531 /// The rendering driver uses this closure to queue up more work.
1532 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1533 F: FnMut(&mut Context, clean::Item),
1535 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1536 // if they contain impls for public types. These modules can also
1537 // contain items such as publicly reexported structures.
1539 // External crates will provide links to these structures, so
1540 // these modules are recursed into, but not rendered normally
1541 // (a flag on the context).
1542 if !self.render_redirect_pages {
1543 self.render_redirect_pages = item.is_stripped();
1547 // modules are special because they add a namespace. We also need to
1548 // recurse into the items of the module as well.
1549 let name = item.name.as_ref().unwrap().to_string();
1550 let mut item = Some(item);
1551 self.recurse(name, |this| {
1552 let item = item.take().unwrap();
1554 let mut buf = Vec::new();
1555 this.render_item(&mut buf, &item, false).unwrap();
1556 // buf will be empty if the module is stripped and there is no redirect for it
1557 if !buf.is_empty() {
1558 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1559 let joint_dst = this.dst.join("index.html");
1560 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1561 try_err!(dst.write_all(&buf), &joint_dst);
1564 let m = match item.inner {
1565 clean::StrippedItem(box clean::ModuleItem(m)) |
1566 clean::ModuleItem(m) => m,
1570 // Render sidebar-items.js used throughout this module.
1571 if !this.render_redirect_pages {
1572 let items = this.build_sidebar_items(&m);
1573 let js_dst = this.dst.join("sidebar-items.js");
1574 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1575 try_err!(write!(&mut js_out, "initSidebarItems({});",
1576 as_json(&items)), &js_dst);
1579 for item in m.items {
1585 } else if item.name.is_some() {
1586 let mut buf = Vec::new();
1587 self.render_item(&mut buf, &item, true).unwrap();
1588 // buf will be empty if the item is stripped and there is no redirect for it
1589 if !buf.is_empty() {
1590 let name = item.name.as_ref().unwrap();
1591 let item_type = item.type_();
1592 let file_name = &item_path(item_type, name);
1593 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1594 let joint_dst = self.dst.join(file_name);
1595 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1596 try_err!(dst.write_all(&buf), &joint_dst);
1598 // Redirect from a sane URL using the namespace to Rustdoc's
1599 // URL for the page.
1600 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1601 let redir_dst = self.dst.join(redir_name);
1602 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1605 let mut redirect_out = BufWriter::new(redirect_out);
1606 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1609 // If the item is a macro, redirect from the old macro URL (with !)
1610 // to the new one (without).
1611 // FIXME(#35705) remove this redirect.
1612 if item_type == ItemType::Macro {
1613 let redir_name = format!("{}.{}!.html", item_type, name);
1614 let redir_dst = self.dst.join(redir_name);
1615 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1616 let mut redirect_out = BufWriter::new(redirect_out);
1617 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1624 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1625 // BTreeMap instead of HashMap to get a sorted output
1626 let mut map = BTreeMap::new();
1627 for item in &m.items {
1628 if item.is_stripped() { continue }
1630 let short = item.type_().css_class();
1631 let myname = match item.name {
1633 Some(ref s) => s.to_string(),
1635 let short = short.to_string();
1636 map.entry(short).or_insert(vec![])
1637 .push((myname, Some(plain_summary_line(item.doc_value()))));
1640 for (_, items) in &mut map {
1648 /// Generate a url appropriate for an `href` attribute back to the source of
1651 /// The url generated, when clicked, will redirect the browser back to the
1652 /// original source code.
1654 /// If `None` is returned, then a source link couldn't be generated. This
1655 /// may happen, for example, with externally inlined items where the source
1656 /// of their crate documentation isn't known.
1657 fn src_href(&self) -> Option<String> {
1658 let mut root = self.cx.root_path();
1660 let cache = cache();
1661 let mut path = String::new();
1662 let (krate, path) = if self.item.def_id.is_local() {
1663 let path = PathBuf::from(&self.item.source.filename);
1664 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1665 (&self.cx.shared.layout.krate, path)
1670 // Macros from other libraries get special filenames which we can
1672 if self.item.source.filename.starts_with("<") &&
1673 self.item.source.filename.ends_with("macros>") {
1677 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1678 Some(&(ref name, ref src, Local)) => (name, src),
1679 Some(&(ref name, ref src, Remote(ref s))) => {
1680 root = s.to_string();
1683 Some(&(_, _, Unknown)) | None => return None,
1686 let file = Path::new(&self.item.source.filename);
1687 clean_srcpath(&src_root, file, false, |component| {
1688 path.push_str(component);
1691 let mut fname = file.file_name().expect("source has no filename")
1693 fname.push(".html");
1694 path.push_str(&fname.to_string_lossy());
1698 let lines = if self.item.source.loline == self.item.source.hiline {
1699 format!("{}", self.item.source.loline)
1701 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1703 Some(format!("{root}src/{krate}/{path}#{lines}",
1704 root = Escape(&root),
1711 impl<'a> fmt::Display for Item<'a> {
1712 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1713 debug_assert!(!self.item.is_stripped());
1714 // Write the breadcrumb trail header for the top
1715 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1716 match self.item.inner {
1717 clean::ModuleItem(ref m) => if m.is_crate {
1718 write!(fmt, "Crate ")?;
1720 write!(fmt, "Module ")?;
1722 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1723 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1724 clean::StructItem(..) => write!(fmt, "Struct ")?,
1725 clean::UnionItem(..) => write!(fmt, "Union ")?,
1726 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1727 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1728 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1729 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1730 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1731 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1732 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1734 // We don't generate pages for any other type.
1738 if !self.item.is_primitive() {
1739 let cur = &self.cx.current;
1740 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1741 for (i, component) in cur.iter().enumerate().take(amt) {
1742 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1743 repeat("../").take(cur.len() - i - 1)
1744 .collect::<String>(),
1748 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1749 self.item.type_(), self.item.name.as_ref().unwrap())?;
1751 write!(fmt, "</span>")?; // in-band
1752 write!(fmt, "<span class='out-of-band'>")?;
1753 if let Some(version) = self.item.stable_since() {
1754 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1758 r##"<span id='render-detail'>
1759 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1760 [<span class='inner'>−</span>]
1766 // When this item is part of a `pub use` in a downstream crate, the
1767 // [src] link in the downstream documentation will actually come back to
1768 // this page, and this link will be auto-clicked. The `id` attribute is
1769 // used to find the link to auto-click.
1770 if self.cx.shared.include_sources && !self.item.is_primitive() {
1771 if let Some(l) = self.src_href() {
1772 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1773 l, "goto source code")?;
1777 write!(fmt, "</span>")?; // out-of-band
1779 write!(fmt, "</h1>\n")?;
1781 match self.item.inner {
1782 clean::ModuleItem(ref m) => {
1783 item_module(fmt, self.cx, self.item, &m.items)
1785 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1786 item_function(fmt, self.cx, self.item, f),
1787 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1788 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1789 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1790 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1791 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1792 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1793 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1794 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1795 item_static(fmt, self.cx, self.item, i),
1796 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1797 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1799 // We don't generate pages for any other type.
1806 fn item_path(ty: ItemType, name: &str) -> String {
1808 ItemType::Module => format!("{}/index.html", name),
1809 _ => format!("{}.{}.html", ty.css_class(), name),
1813 fn full_path(cx: &Context, item: &clean::Item) -> String {
1814 let mut s = cx.current.join("::");
1816 s.push_str(item.name.as_ref().unwrap());
1820 fn shorter<'a>(s: Option<&'a str>) -> String {
1822 Some(s) => s.lines().take_while(|line|{
1823 (*line).chars().any(|chr|{
1824 !chr.is_whitespace()
1826 }).collect::<Vec<_>>().join("\n"),
1827 None => "".to_string()
1832 fn plain_summary_line(s: Option<&str>) -> String {
1833 let line = shorter(s).replace("\n", " ");
1834 markdown::plain_summary_line(&line[..])
1837 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1838 if let Some(ref name) = item.name {
1839 info!("Documenting {}", name);
1841 document_stability(w, cx, item)?;
1842 let prefix = render_assoc_const_value(item);
1843 document_full(w, item, cx, &prefix)?;
1847 /// Render md_text as markdown. Warns the user if there are difference in
1848 /// rendering between Pulldown and Hoedown.
1849 fn render_markdown(w: &mut fmt::Formatter,
1852 render_type: RenderType,
1854 scx: &SharedContext)
1856 // Save the state of USED_ID_MAP so it only gets updated once even
1857 // though we're rendering twice.
1858 let orig_used_id_map = USED_ID_MAP.with(|map| map.borrow().clone());
1859 let hoedown_output = format!("{}", Markdown(md_text, RenderType::Hoedown));
1860 USED_ID_MAP.with(|map| *map.borrow_mut() = orig_used_id_map);
1861 let pulldown_output = format!("{}", Markdown(md_text, RenderType::Pulldown));
1862 let mut differences = html_diff::get_differences(&pulldown_output, &hoedown_output);
1863 differences.retain(|s| {
1865 html_diff::Difference::NodeText { ref elem_text,
1866 ref opposite_elem_text,
1868 if elem_text.split_whitespace().eq(opposite_elem_text.split_whitespace()) => {
1875 if !differences.is_empty() {
1876 scx.markdown_warnings.borrow_mut().push((span, md_text.to_owned(), differences));
1879 write!(w, "<div class='docblock'>{}{}</div>",
1881 if render_type == RenderType::Pulldown { pulldown_output } else { hoedown_output })
1884 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1885 cx: &Context, prefix: &str) -> fmt::Result {
1886 if let Some(s) = item.doc_value() {
1887 let markdown = if s.contains('\n') {
1888 format!("{} [Read more]({})",
1889 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1891 format!("{}", &plain_summary_line(Some(s)))
1893 render_markdown(w, &markdown, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1894 } else if !prefix.is_empty() {
1895 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1900 fn render_assoc_const_value(item: &clean::Item) -> String {
1902 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1903 highlight::render_with_highlighting(
1904 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1915 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1916 cx: &Context, prefix: &str) -> fmt::Result {
1917 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1918 debug!("Doc block: =====\n{}\n=====", s);
1919 render_markdown(w, &*s, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1920 } else if !prefix.is_empty() {
1921 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1926 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1927 let stabilities = short_stability(item, cx, true);
1928 if !stabilities.is_empty() {
1929 write!(w, "<div class='stability'>")?;
1930 for stability in stabilities {
1931 write!(w, "{}", stability)?;
1933 write!(w, "</div>")?;
1938 fn name_key(name: &str) -> (&str, u64, usize) {
1939 // find number at end
1940 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1942 // count leading zeroes
1944 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1946 // sort leading zeroes last
1947 let num_zeroes = after_zeroes - split;
1949 match name[split..].parse() {
1950 Ok(n) => (&name[..split], n, num_zeroes),
1951 Err(_) => (name, 0, num_zeroes),
1955 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1956 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1957 document(w, cx, item)?;
1959 let mut indices = (0..items.len()).filter(|i| {
1960 if let clean::AutoImplItem(..) = items[*i].inner {
1963 !items[*i].is_stripped()
1964 }).collect::<Vec<usize>>();
1966 // the order of item types in the listing
1967 fn reorder(ty: ItemType) -> u8 {
1969 ItemType::ExternCrate => 0,
1970 ItemType::Import => 1,
1971 ItemType::Primitive => 2,
1972 ItemType::Module => 3,
1973 ItemType::Macro => 4,
1974 ItemType::Struct => 5,
1975 ItemType::Enum => 6,
1976 ItemType::Constant => 7,
1977 ItemType::Static => 8,
1978 ItemType::Trait => 9,
1979 ItemType::Function => 10,
1980 ItemType::Typedef => 12,
1981 ItemType::Union => 13,
1986 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1987 let ty1 = i1.type_();
1988 let ty2 = i2.type_();
1990 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1992 let s1 = i1.stability.as_ref().map(|s| s.level);
1993 let s2 = i2.stability.as_ref().map(|s| s.level);
1995 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1996 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1999 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2000 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2001 name_key(lhs).cmp(&name_key(rhs))
2004 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2005 // This call is to remove reexport duplicates in cases such as:
2010 // pub trait Double { fn foo(); }
2014 // pub use foo::bar::*;
2018 // `Double` will appear twice in the generated docs.
2020 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2021 // can be identical even if the elements are different (mostly in imports).
2022 // So in case this is an import, we keep everything by adding a "unique id"
2023 // (which is the position in the vector).
2024 indices.dedup_by_key(|i| (items[*i].def_id,
2025 if items[*i].name.as_ref().is_some() {
2026 Some(full_path(cx, &items[*i]).clone())
2031 if items[*i].is_import() {
2037 debug!("{:?}", indices);
2038 let mut curty = None;
2039 for &idx in &indices {
2040 let myitem = &items[idx];
2041 if myitem.is_stripped() {
2045 let myty = Some(myitem.type_());
2046 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2047 // Put `extern crate` and `use` re-exports in the same section.
2049 } else if myty != curty {
2050 if curty.is_some() {
2051 write!(w, "</table>")?;
2054 let (short, name) = match myty.unwrap() {
2055 ItemType::ExternCrate |
2056 ItemType::Import => ("reexports", "Reexports"),
2057 ItemType::Module => ("modules", "Modules"),
2058 ItemType::Struct => ("structs", "Structs"),
2059 ItemType::Union => ("unions", "Unions"),
2060 ItemType::Enum => ("enums", "Enums"),
2061 ItemType::Function => ("functions", "Functions"),
2062 ItemType::Typedef => ("types", "Type Definitions"),
2063 ItemType::Static => ("statics", "Statics"),
2064 ItemType::Constant => ("constants", "Constants"),
2065 ItemType::Trait => ("traits", "Traits"),
2066 ItemType::Impl => ("impls", "Implementations"),
2067 ItemType::TyMethod => ("tymethods", "Type Methods"),
2068 ItemType::Method => ("methods", "Methods"),
2069 ItemType::StructField => ("fields", "Struct Fields"),
2070 ItemType::Variant => ("variants", "Variants"),
2071 ItemType::Macro => ("macros", "Macros"),
2072 ItemType::Primitive => ("primitives", "Primitive Types"),
2073 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2074 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2075 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2077 write!(w, "<h2 id='{id}' class='section-header'>\
2078 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2079 id = derive_id(short.to_owned()), name = name)?;
2082 match myitem.inner {
2083 clean::ExternCrateItem(ref name, ref src) => {
2084 use html::format::HRef;
2088 write!(w, "<tr><td><code>{}extern crate {} as {};",
2089 VisSpace(&myitem.visibility),
2090 HRef::new(myitem.def_id, src),
2094 write!(w, "<tr><td><code>{}extern crate {};",
2095 VisSpace(&myitem.visibility),
2096 HRef::new(myitem.def_id, name))?
2099 write!(w, "</code></td></tr>")?;
2102 clean::ImportItem(ref import) => {
2103 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2104 VisSpace(&myitem.visibility), *import)?;
2108 if myitem.name.is_none() { continue }
2110 let stabilities = short_stability(myitem, cx, false);
2112 let stab_docs = if !stabilities.is_empty() {
2114 .map(|s| format!("[{}]", s))
2115 .collect::<Vec<_>>()
2122 let unsafety_flag = match myitem.inner {
2123 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2124 if func.unsafety == hir::Unsafety::Unsafe => {
2125 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2130 let doc_value = myitem.doc_value().unwrap_or("");
2132 <tr class='{stab} module-item'>
2133 <td><a class=\"{class}\" href=\"{href}\"
2134 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2135 <td class='docblock-short'>
2139 name = *myitem.name.as_ref().unwrap(),
2140 stab_docs = stab_docs,
2141 docs = if cx.render_type == RenderType::Hoedown {
2143 shorter(Some(&Markdown(doc_value,
2144 RenderType::Hoedown).to_string())))
2146 format!("{}", MarkdownSummaryLine(doc_value))
2148 class = myitem.type_(),
2149 stab = myitem.stability_class().unwrap_or("".to_string()),
2150 unsafety_flag = unsafety_flag,
2151 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2152 title_type = myitem.type_(),
2153 title = full_path(cx, myitem))?;
2158 if curty.is_some() {
2159 write!(w, "</table>")?;
2164 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2165 let mut stability = vec![];
2167 if let Some(stab) = item.stability.as_ref() {
2168 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2169 format!(": {}", stab.deprecated_reason)
2173 if !stab.deprecated_since.is_empty() {
2174 let since = if show_reason {
2175 format!(" since {}", Escape(&stab.deprecated_since))
2179 let text = format!("Deprecated{}{}",
2181 MarkdownHtml(&deprecated_reason, cx.render_type));
2182 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2185 if stab.level == stability::Unstable {
2187 let unstable_extra = match (!stab.feature.is_empty(),
2188 &cx.shared.issue_tracker_base_url,
2190 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2191 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2192 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2193 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2194 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2197 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2200 if stab.unstable_reason.is_empty() {
2201 stability.push(format!("<div class='stab unstable'>\
2202 <span class=microscope>🔬</span> \
2203 This is a nightly-only experimental API. {}\
2207 let text = format!("<summary><span class=microscope>🔬</span> \
2208 This is a nightly-only experimental API. {}\
2211 MarkdownHtml(&stab.unstable_reason, cx.render_type));
2212 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2216 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2219 } else if let Some(depr) = item.deprecation.as_ref() {
2220 let note = if show_reason && !depr.note.is_empty() {
2221 format!(": {}", depr.note)
2225 let since = if show_reason && !depr.since.is_empty() {
2226 format!(" since {}", Escape(&depr.since))
2231 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
2232 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2235 if let Some(ref cfg) = item.attrs.cfg {
2236 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2237 cfg.render_long_html()
2239 cfg.render_short_html()
2246 struct Initializer<'a>(&'a str);
2248 impl<'a> fmt::Display for Initializer<'a> {
2249 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2250 let Initializer(s) = *self;
2251 if s.is_empty() { return Ok(()); }
2252 write!(f, "<code> = </code>")?;
2253 write!(f, "<code>{}</code>", Escape(s))
2257 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2258 c: &clean::Constant) -> fmt::Result {
2259 write!(w, "<pre class='rust const'>")?;
2260 render_attributes(w, it)?;
2261 write!(w, "{vis}const \
2262 {name}: {typ}{init}</pre>",
2263 vis = VisSpace(&it.visibility),
2264 name = it.name.as_ref().unwrap(),
2266 init = Initializer(&c.expr))?;
2270 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2271 s: &clean::Static) -> fmt::Result {
2272 write!(w, "<pre class='rust static'>")?;
2273 render_attributes(w, it)?;
2274 write!(w, "{vis}static {mutability}\
2275 {name}: {typ}{init}</pre>",
2276 vis = VisSpace(&it.visibility),
2277 mutability = MutableSpace(s.mutability),
2278 name = it.name.as_ref().unwrap(),
2280 init = Initializer(&s.expr))?;
2284 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2285 f: &clean::Function) -> fmt::Result {
2286 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2287 VisSpace(&it.visibility),
2288 ConstnessSpace(f.constness),
2289 UnsafetySpace(f.unsafety),
2291 it.name.as_ref().unwrap(),
2293 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2294 render_attributes(w, it)?;
2295 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2296 {name}{generics}{decl}{where_clause}</pre>",
2297 vis = VisSpace(&it.visibility),
2298 constness = ConstnessSpace(f.constness),
2299 unsafety = UnsafetySpace(f.unsafety),
2300 abi = AbiSpace(f.abi),
2301 name = it.name.as_ref().unwrap(),
2302 generics = f.generics,
2303 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2312 fn implementor2item<'a>(cache: &'a Cache, imp : &Implementor) -> Option<&'a clean::Item> {
2313 if let Some(t_did) = imp.impl_.for_.def_id() {
2314 if let Some(impl_item) = cache.impls.get(&t_did).and_then(|i| i.iter()
2315 .find(|i| i.impl_item.def_id == imp.def_id))
2317 let i = &impl_item.impl_item;
2324 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2325 t: &clean::Trait) -> fmt::Result {
2326 let mut bounds = String::new();
2327 let mut bounds_plain = String::new();
2328 if !t.bounds.is_empty() {
2329 if !bounds.is_empty() {
2331 bounds_plain.push(' ');
2333 bounds.push_str(": ");
2334 bounds_plain.push_str(": ");
2335 for (i, p) in t.bounds.iter().enumerate() {
2337 bounds.push_str(" + ");
2338 bounds_plain.push_str(" + ");
2340 bounds.push_str(&format!("{}", *p));
2341 bounds_plain.push_str(&format!("{:#}", *p));
2345 // Output the trait definition
2346 write!(w, "<pre class='rust trait'>")?;
2347 render_attributes(w, it)?;
2348 write!(w, "{}{}trait {}{}{}",
2349 VisSpace(&it.visibility),
2350 UnsafetySpace(t.unsafety),
2351 it.name.as_ref().unwrap(),
2355 if !t.generics.where_predicates.is_empty() {
2356 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2361 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2362 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2363 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2364 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2366 if t.items.is_empty() {
2367 write!(w, "{{ }}")?;
2369 // FIXME: we should be using a derived_id for the Anchors here
2373 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2376 if !types.is_empty() && !consts.is_empty() {
2381 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2384 if !consts.is_empty() && !required.is_empty() {
2387 for (pos, m) in required.iter().enumerate() {
2389 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2392 if pos < required.len() - 1 {
2393 write!(w, "<div class='item-spacer'></div>")?;
2396 if !required.is_empty() && !provided.is_empty() {
2399 for (pos, m) in provided.iter().enumerate() {
2401 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2403 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2404 write!(w, ",\n {{ ... }}\n")?;
2407 write!(w, " {{ ... }}\n")?;
2410 if pos < provided.len() - 1 {
2411 write!(w, "<div class='item-spacer'></div>")?;
2416 write!(w, "</pre>")?;
2418 // Trait documentation
2419 document(w, cx, it)?;
2421 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2423 let name = m.name.as_ref().unwrap();
2424 let item_type = m.type_();
2425 let id = derive_id(format!("{}.{}", item_type, name));
2426 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2427 write!(w, "{extra}<h3 id='{id}' class='method'>\
2428 <span id='{ns_id}' class='invisible'><code>",
2429 extra = render_spotlight_traits(m)?,
2432 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2433 write!(w, "</code>")?;
2434 render_stability_since(w, m, t)?;
2435 write!(w, "</span></h3>")?;
2436 document(w, cx, m)?;
2440 if !types.is_empty() {
2442 <h2 id='associated-types' class='small-section-header'>
2443 Associated Types<a href='#associated-types' class='anchor'></a>
2445 <div class='methods'>
2448 trait_item(w, cx, *t, it)?;
2450 write!(w, "</div>")?;
2453 if !consts.is_empty() {
2455 <h2 id='associated-const' class='small-section-header'>
2456 Associated Constants<a href='#associated-const' class='anchor'></a>
2458 <div class='methods'>
2461 trait_item(w, cx, *t, it)?;
2463 write!(w, "</div>")?;
2466 // Output the documentation for each function individually
2467 if !required.is_empty() {
2469 <h2 id='required-methods' class='small-section-header'>
2470 Required Methods<a href='#required-methods' class='anchor'></a>
2472 <div class='methods'>
2474 for m in &required {
2475 trait_item(w, cx, *m, it)?;
2477 write!(w, "</div>")?;
2479 if !provided.is_empty() {
2481 <h2 id='provided-methods' class='small-section-header'>
2482 Provided Methods<a href='#provided-methods' class='anchor'></a>
2484 <div class='methods'>
2486 for m in &provided {
2487 trait_item(w, cx, *m, it)?;
2489 write!(w, "</div>")?;
2492 // If there are methods directly on this trait object, render them here.
2493 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2495 let cache = cache();
2497 <h2 id='implementors' class='small-section-header'>
2498 Implementors<a href='#implementors' class='anchor'></a>
2500 <ul class='item-list' id='implementors-list'>
2502 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2503 // The DefId is for the first Type found with that name. The bool is
2504 // if any Types with the same name but different DefId have been found.
2505 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2506 for implementor in implementors {
2507 match implementor.impl_.for_ {
2508 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2509 clean::BorrowedRef {
2510 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2513 let &mut (prev_did, ref mut has_duplicates) =
2514 implementor_dups.entry(path.last_name()).or_insert((did, false));
2515 if prev_did != did {
2516 *has_duplicates = true;
2523 let (local, foreign) = implementors.iter()
2524 .partition::<Vec<_>, _>(|i| i.impl_.for_.def_id()
2525 .map_or(true, |d| cache.paths.contains_key(&d)));
2527 if !foreign.is_empty() {
2529 <h2 id='foreign-impls' class='small-section-header'>
2530 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2534 for implementor in foreign {
2535 if let Some(i) = implementor2item(&cache, implementor) {
2536 let impl_ = Impl { impl_item: i.clone() };
2537 let assoc_link = AssocItemLink::GotoSource(
2538 i.def_id, &implementor.impl_.provided_trait_methods
2540 render_impl(w, cx, &impl_, assoc_link,
2541 RenderMode::Normal, i.stable_since(), false)?;
2546 write!(w, "{}", impl_header)?;
2548 for implementor in local {
2550 if let Some(item) = implementor2item(&cache, implementor) {
2551 if let Some(l) = (Item { cx, item }).src_href() {
2552 write!(w, "<div class='out-of-band'>")?;
2553 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2554 l, "goto source code")?;
2555 write!(w, "</div>")?;
2558 write!(w, "<code>")?;
2559 // If there's already another implementor that has the same abbridged name, use the
2560 // full path, for example in `std::iter::ExactSizeIterator`
2561 let use_absolute = match implementor.impl_.for_ {
2562 clean::ResolvedPath { ref path, is_generic: false, .. } |
2563 clean::BorrowedRef {
2564 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2566 } => implementor_dups[path.last_name()].1,
2569 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2570 for it in &implementor.impl_.items {
2571 if let clean::TypedefItem(ref tydef, _) = it.inner {
2572 write!(w, "<span class=\"where fmt-newline\"> ")?;
2573 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2574 write!(w, ";</span>")?;
2577 writeln!(w, "</code></li>")?;
2580 // even without any implementations to write in, we still want the heading and list, so the
2581 // implementors javascript file pulled in below has somewhere to write the impls into
2582 write!(w, "{}", impl_header)?;
2584 write!(w, "</ul>")?;
2585 write!(w, r#"<script type="text/javascript" async
2586 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2588 root_path = vec![".."; cx.current.len()].join("/"),
2589 path = if it.def_id.is_local() {
2590 cx.current.join("/")
2592 let (ref path, _) = cache.external_paths[&it.def_id];
2593 path[..path.len() - 1].join("/")
2595 ty = it.type_().css_class(),
2596 name = *it.name.as_ref().unwrap())?;
2600 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2601 use html::item_type::ItemType::*;
2603 let name = it.name.as_ref().unwrap();
2604 let ty = match it.type_() {
2605 Typedef | AssociatedType => AssociatedType,
2609 let anchor = format!("#{}.{}", ty, name);
2611 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2612 AssocItemLink::Anchor(None) => anchor,
2613 AssocItemLink::GotoSource(did, _) => {
2614 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2619 fn assoc_const(w: &mut fmt::Formatter,
2622 _default: Option<&String>,
2623 link: AssocItemLink) -> fmt::Result {
2624 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2625 VisSpace(&it.visibility),
2626 naive_assoc_href(it, link),
2627 it.name.as_ref().unwrap(),
2632 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2633 bounds: &Vec<clean::TyParamBound>,
2634 default: Option<&clean::Type>,
2635 link: AssocItemLink) -> fmt::Result {
2636 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2637 naive_assoc_href(it, link),
2638 it.name.as_ref().unwrap())?;
2639 if !bounds.is_empty() {
2640 write!(w, ": {}", TyParamBounds(bounds))?
2642 if let Some(default) = default {
2643 write!(w, " = {}", default)?;
2648 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2649 ver: Option<&'a str>,
2650 containing_ver: Option<&'a str>) -> fmt::Result {
2651 if let Some(v) = ver {
2652 if containing_ver != ver && v.len() > 0 {
2653 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2660 fn render_stability_since(w: &mut fmt::Formatter,
2662 containing_item: &clean::Item) -> fmt::Result {
2663 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2666 fn render_assoc_item(w: &mut fmt::Formatter,
2668 link: AssocItemLink,
2669 parent: ItemType) -> fmt::Result {
2670 fn method(w: &mut fmt::Formatter,
2672 unsafety: hir::Unsafety,
2673 constness: hir::Constness,
2675 g: &clean::Generics,
2677 link: AssocItemLink,
2680 let name = meth.name.as_ref().unwrap();
2681 let anchor = format!("#{}.{}", meth.type_(), name);
2682 let href = match link {
2683 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2684 AssocItemLink::Anchor(None) => anchor,
2685 AssocItemLink::GotoSource(did, provided_methods) => {
2686 // We're creating a link from an impl-item to the corresponding
2687 // trait-item and need to map the anchored type accordingly.
2688 let ty = if provided_methods.contains(name) {
2694 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2697 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2698 VisSpace(&meth.visibility),
2699 ConstnessSpace(constness),
2700 UnsafetySpace(unsafety),
2704 let (indent, end_newline) = if parent == ItemType::Trait {
2710 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2711 {generics}{decl}{where_clause}",
2712 VisSpace(&meth.visibility),
2713 ConstnessSpace(constness),
2714 UnsafetySpace(unsafety),
2724 where_clause = WhereClause {
2731 clean::StrippedItem(..) => Ok(()),
2732 clean::TyMethodItem(ref m) => {
2733 method(w, item, m.unsafety, hir::Constness::NotConst,
2734 m.abi, &m.generics, &m.decl, link, parent)
2736 clean::MethodItem(ref m) => {
2737 method(w, item, m.unsafety, m.constness,
2738 m.abi, &m.generics, &m.decl, link, parent)
2740 clean::AssociatedConstItem(ref ty, ref default) => {
2741 assoc_const(w, item, ty, default.as_ref(), link)
2743 clean::AssociatedTypeItem(ref bounds, ref default) => {
2744 assoc_type(w, item, bounds, default.as_ref(), link)
2746 _ => panic!("render_assoc_item called on non-associated-item")
2750 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2751 s: &clean::Struct) -> fmt::Result {
2752 write!(w, "<pre class='rust struct'>")?;
2753 render_attributes(w, it)?;
2761 write!(w, "</pre>")?;
2763 document(w, cx, it)?;
2764 let mut fields = s.fields.iter().filter_map(|f| {
2766 clean::StructFieldItem(ref ty) => Some((f, ty)),
2770 if let doctree::Plain = s.struct_type {
2771 if fields.peek().is_some() {
2772 write!(w, "<h2 id='fields' class='fields small-section-header'>
2773 Fields<a href='#fields' class='anchor'></a></h2>")?;
2774 for (field, ty) in fields {
2775 let id = derive_id(format!("{}.{}",
2776 ItemType::StructField,
2777 field.name.as_ref().unwrap()));
2778 let ns_id = derive_id(format!("{}.{}",
2779 field.name.as_ref().unwrap(),
2780 ItemType::StructField.name_space()));
2781 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2782 <a href=\"#{id}\" class=\"anchor field\"></a>
2783 <span id=\"{ns_id}\" class='invisible'>
2784 <code>{name}: {ty}</code>
2786 item_type = ItemType::StructField,
2789 name = field.name.as_ref().unwrap(),
2791 if let Some(stability_class) = field.stability_class() {
2792 write!(w, "<span class='stab {stab}'></span>",
2793 stab = stability_class)?;
2795 document(w, cx, field)?;
2799 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2802 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2803 s: &clean::Union) -> fmt::Result {
2804 write!(w, "<pre class='rust union'>")?;
2805 render_attributes(w, it)?;
2812 write!(w, "</pre>")?;
2814 document(w, cx, it)?;
2815 let mut fields = s.fields.iter().filter_map(|f| {
2817 clean::StructFieldItem(ref ty) => Some((f, ty)),
2821 if fields.peek().is_some() {
2822 write!(w, "<h2 id='fields' class='fields small-section-header'>
2823 Fields<a href='#fields' class='anchor'></a></h2>")?;
2824 for (field, ty) in fields {
2825 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2827 shortty = ItemType::StructField,
2828 name = field.name.as_ref().unwrap(),
2830 if let Some(stability_class) = field.stability_class() {
2831 write!(w, "<span class='stab {stab}'></span>",
2832 stab = stability_class)?;
2834 document(w, cx, field)?;
2837 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2840 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2841 e: &clean::Enum) -> fmt::Result {
2842 write!(w, "<pre class='rust enum'>")?;
2843 render_attributes(w, it)?;
2844 write!(w, "{}enum {}{}{}",
2845 VisSpace(&it.visibility),
2846 it.name.as_ref().unwrap(),
2848 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2849 if e.variants.is_empty() && !e.variants_stripped {
2850 write!(w, " {{}}")?;
2852 write!(w, " {{\n")?;
2853 for v in &e.variants {
2855 let name = v.name.as_ref().unwrap();
2857 clean::VariantItem(ref var) => {
2859 clean::VariantKind::CLike => write!(w, "{}", name)?,
2860 clean::VariantKind::Tuple(ref tys) => {
2861 write!(w, "{}(", name)?;
2862 for (i, ty) in tys.iter().enumerate() {
2864 write!(w, ", ")?
2866 write!(w, "{}", *ty)?;
2870 clean::VariantKind::Struct(ref s) => {
2886 if e.variants_stripped {
2887 write!(w, " // some variants omitted\n")?;
2891 write!(w, "</pre>")?;
2893 document(w, cx, it)?;
2894 if !e.variants.is_empty() {
2895 write!(w, "<h2 id='variants' class='variants small-section-header'>
2896 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2897 for variant in &e.variants {
2898 let id = derive_id(format!("{}.{}",
2900 variant.name.as_ref().unwrap()));
2901 let ns_id = derive_id(format!("{}.{}",
2902 variant.name.as_ref().unwrap(),
2903 ItemType::Variant.name_space()));
2904 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2905 <a href=\"#{id}\" class=\"anchor field\"></a>\
2906 <span id='{ns_id}' class='invisible'><code>{name}",
2909 name = variant.name.as_ref().unwrap())?;
2910 if let clean::VariantItem(ref var) = variant.inner {
2911 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2913 for (i, ty) in tys.iter().enumerate() {
2915 write!(w, ", ")?;
2917 write!(w, "{}", *ty)?;
2922 write!(w, "</code></span></span>")?;
2923 document(w, cx, variant)?;
2925 use clean::{Variant, VariantKind};
2926 if let clean::VariantItem(Variant {
2927 kind: VariantKind::Struct(ref s)
2928 }) = variant.inner {
2929 let variant_id = derive_id(format!("{}.{}.fields",
2931 variant.name.as_ref().unwrap()));
2932 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2934 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2935 <table>", name = variant.name.as_ref().unwrap())?;
2936 for field in &s.fields {
2937 use clean::StructFieldItem;
2938 if let StructFieldItem(ref ty) = field.inner {
2939 let id = derive_id(format!("variant.{}.field.{}",
2940 variant.name.as_ref().unwrap(),
2941 field.name.as_ref().unwrap()));
2942 let ns_id = derive_id(format!("{}.{}.{}.{}",
2943 variant.name.as_ref().unwrap(),
2944 ItemType::Variant.name_space(),
2945 field.name.as_ref().unwrap(),
2946 ItemType::StructField.name_space()));
2947 write!(w, "<tr><td \
2949 <span id='{ns_id}' class='invisible'>\
2950 <code>{f}: {t}</code></span></td><td>",
2953 f = field.name.as_ref().unwrap(),
2955 document(w, cx, field)?;
2956 write!(w, "</td></tr>")?;
2959 write!(w, "</table></span>")?;
2961 render_stability_since(w, variant, it)?;
2964 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2968 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2969 let name = attr.name();
2972 Some(format!("{}", name))
2973 } else if let Some(v) = attr.value_str() {
2974 Some(format!("{} = {:?}", name, v.as_str()))
2975 } else if let Some(values) = attr.meta_item_list() {
2976 let display: Vec<_> = values.iter().filter_map(|attr| {
2977 attr.meta_item().and_then(|mi| render_attribute(mi))
2980 if display.len() > 0 {
2981 Some(format!("{}({})", name, display.join(", ")))
2990 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2997 "unsafe_destructor_blind_to_params"
3000 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3001 let mut attrs = String::new();
3003 for attr in &it.attrs.other_attrs {
3004 let name = attr.name().unwrap();
3005 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3008 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3009 attrs.push_str(&format!("#[{}]\n", s));
3012 if attrs.len() > 0 {
3013 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3018 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3019 g: Option<&clean::Generics>,
3020 ty: doctree::StructType,
3021 fields: &[clean::Item],
3023 structhead: bool) -> fmt::Result {
3025 VisSpace(&it.visibility),
3026 if structhead {"struct "} else {""},
3027 it.name.as_ref().unwrap())?;
3028 if let Some(g) = g {
3033 if let Some(g) = g {
3034 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3036 let mut has_visible_fields = false;
3038 for field in fields {
3039 if let clean::StructFieldItem(ref ty) = field.inner {
3040 write!(w, "\n{} {}{}: {},",
3042 VisSpace(&field.visibility),
3043 field.name.as_ref().unwrap(),
3045 has_visible_fields = true;
3049 if has_visible_fields {
3050 if it.has_stripped_fields().unwrap() {
3051 write!(w, "\n{} // some fields omitted", tab)?;
3053 write!(w, "\n{}", tab)?;
3054 } else if it.has_stripped_fields().unwrap() {
3055 // If there are no visible fields we can just display
3056 // `{ /* fields omitted */ }` to save space.
3057 write!(w, " /* fields omitted */ ")?;
3063 for (i, field) in fields.iter().enumerate() {
3068 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3071 clean::StructFieldItem(ref ty) => {
3072 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3078 if let Some(g) = g {
3079 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3084 // Needed for PhantomData.
3085 if let Some(g) = g {
3086 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3094 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3095 g: Option<&clean::Generics>,
3096 fields: &[clean::Item],
3098 structhead: bool) -> fmt::Result {
3100 VisSpace(&it.visibility),
3101 if structhead {"union "} else {""},
3102 it.name.as_ref().unwrap())?;
3103 if let Some(g) = g {
3104 write!(w, "{}", g)?;
3105 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3108 write!(w, " {{\n{}", tab)?;
3109 for field in fields {
3110 if let clean::StructFieldItem(ref ty) = field.inner {
3111 write!(w, " {}{}: {},\n{}",
3112 VisSpace(&field.visibility),
3113 field.name.as_ref().unwrap(),
3119 if it.has_stripped_fields().unwrap() {
3120 write!(w, " // some fields omitted\n{}", tab)?;
3126 #[derive(Copy, Clone)]
3127 enum AssocItemLink<'a> {
3128 Anchor(Option<&'a str>),
3129 GotoSource(DefId, &'a FxHashSet<String>),
3132 impl<'a> AssocItemLink<'a> {
3133 fn anchor(&self, id: &'a String) -> Self {
3135 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3136 ref other => *other,
3141 enum AssocItemRender<'a> {
3143 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3146 #[derive(Copy, Clone, PartialEq)]
3149 ForDeref { mut_: bool },
3152 fn render_assoc_items(w: &mut fmt::Formatter,
3154 containing_item: &clean::Item,
3156 what: AssocItemRender) -> fmt::Result {
3158 let v = match c.impls.get(&it) {
3160 None => return Ok(()),
3162 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3163 i.inner_impl().trait_.is_none()
3165 if !non_trait.is_empty() {
3166 let render_mode = match what {
3167 AssocItemRender::All => {
3169 <h2 id='methods' class='small-section-header'>
3170 Methods<a href='#methods' class='anchor'></a>
3175 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3177 <h2 id='deref-methods' class='small-section-header'>
3178 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3181 RenderMode::ForDeref { mut_: deref_mut_ }
3184 for i in &non_trait {
3185 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3186 containing_item.stable_since(), true)?;
3189 if let AssocItemRender::DerefFor { .. } = what {
3192 if !traits.is_empty() {
3193 let deref_impl = traits.iter().find(|t| {
3194 t.inner_impl().trait_.def_id() == c.deref_trait_did
3196 if let Some(impl_) = deref_impl {
3197 let has_deref_mut = traits.iter().find(|t| {
3198 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3200 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3203 <h2 id='implementations' class='small-section-header'>
3204 Trait Implementations<a href='#implementations' class='anchor'></a>
3208 let did = i.trait_did().unwrap();
3209 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3210 render_impl(w, cx, i, assoc_link,
3211 RenderMode::Normal, containing_item.stable_since(), true)?;
3217 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3218 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3219 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3220 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3222 clean::TypedefItem(ref t, true) => Some(&t.type_),
3225 }).next().expect("Expected associated type binding");
3226 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3227 deref_mut_: deref_mut };
3228 if let Some(did) = target.def_id() {
3229 render_assoc_items(w, cx, container_item, did, what)
3231 if let Some(prim) = target.primitive_type() {
3232 if let Some(&did) = cache().primitive_locations.get(&prim) {
3233 render_assoc_items(w, cx, container_item, did, what)?;
3240 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3241 let self_type_opt = match item.inner {
3242 clean::MethodItem(ref method) => method.decl.self_type(),
3243 clean::TyMethodItem(ref method) => method.decl.self_type(),
3247 if let Some(self_ty) = self_type_opt {
3248 let (by_mut_ref, by_box, by_value) = match self_ty {
3249 SelfTy::SelfBorrowed(_, mutability) |
3250 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3251 (mutability == Mutability::Mutable, false, false)
3253 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3254 (false, Some(did) == cache().owned_box_did, false)
3256 SelfTy::SelfValue => (false, false, true),
3257 _ => (false, false, false),
3260 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3266 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3267 let mut out = String::new();
3270 clean::FunctionItem(clean::Function { ref decl, .. }) |
3271 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3272 clean::MethodItem(clean::Method { ref decl, .. }) |
3273 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3274 out = spotlight_decl(decl)?;
3282 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3283 let mut out = String::new();
3284 let mut trait_ = String::new();
3286 if let Some(did) = decl.output.def_id() {
3288 if let Some(impls) = c.impls.get(&did) {
3290 let impl_ = i.inner_impl();
3291 if impl_.trait_.def_id().and_then(|d| c.traits.get(&d))
3292 .map_or(false, |t| t.is_spotlight) {
3295 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3296 <code class=\"content\">",
3298 trait_.push_str(&format!("{}", impl_.for_));
3301 //use the "where" class here to make it small
3302 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3303 let t_did = impl_.trait_.def_id().unwrap();
3304 for it in &impl_.items {
3305 if let clean::TypedefItem(ref tydef, _) = it.inner {
3306 out.push_str("<span class=\"where fmt-newline\"> ");
3307 assoc_type(&mut out, it, &vec![],
3309 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3310 out.push_str(";</span>");
3318 if !out.is_empty() {
3319 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3320 <span class='tooltiptext'>Important traits for {}</span></div>\
3321 <div class=\"content hidden\">",
3323 out.push_str("</code></div></div>");
3329 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3330 render_mode: RenderMode, outer_version: Option<&str>,
3331 show_def_docs: bool) -> fmt::Result {
3332 if render_mode == RenderMode::Normal {
3333 let id = derive_id(match i.inner_impl().trait_ {
3334 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3335 None => "impl".to_string(),
3337 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3338 id, i.inner_impl())?;
3339 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3340 write!(w, "</span><span class='out-of-band'>")?;
3341 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3342 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3343 write!(w, "<div class='ghost'></div>")?;
3344 render_stability_since_raw(w, since, outer_version)?;
3345 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3346 l, "goto source code")?;
3348 render_stability_since_raw(w, since, outer_version)?;
3350 write!(w, "</span>")?;
3351 write!(w, "</h3>\n")?;
3352 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3353 write!(w, "<div class='docblock'>{}</div>", Markdown(&*dox, cx.render_type))?;
3357 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3358 link: AssocItemLink, render_mode: RenderMode,
3359 is_default_item: bool, outer_version: Option<&str>,
3360 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3361 let item_type = item.type_();
3362 let name = item.name.as_ref().unwrap();
3364 let render_method_item: bool = match render_mode {
3365 RenderMode::Normal => true,
3366 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3370 clean::MethodItem(clean::Method { ref decl, .. }) |
3371 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3372 // Only render when the method is not static or we allow static methods
3373 if render_method_item {
3374 let id = derive_id(format!("{}.{}", item_type, name));
3375 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3376 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3377 write!(w, "{}", spotlight_decl(decl)?)?;
3378 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3379 write!(w, "<code>")?;
3380 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3381 write!(w, "</code>")?;
3382 if let Some(l) = (Item { cx, item }).src_href() {
3383 write!(w, "</span><span class='out-of-band'>")?;
3384 write!(w, "<div class='ghost'></div>")?;
3385 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3386 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3387 l, "goto source code")?;
3389 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3391 write!(w, "</span></h4>\n")?;
3394 clean::TypedefItem(ref tydef, _) => {
3395 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3396 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3397 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3398 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3399 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3400 write!(w, "</code></span></h4>\n")?;
3402 clean::AssociatedConstItem(ref ty, ref default) => {
3403 let id = derive_id(format!("{}.{}", item_type, name));
3404 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3405 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3406 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3407 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3408 write!(w, "</code></span></h4>\n")?;
3410 clean::AssociatedTypeItem(ref bounds, ref default) => {
3411 let id = derive_id(format!("{}.{}", item_type, name));
3412 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3413 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3414 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3415 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3416 write!(w, "</code></span></h4>\n")?;
3418 clean::StrippedItem(..) => return Ok(()),
3419 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3422 if render_method_item || render_mode == RenderMode::Normal {
3423 let prefix = render_assoc_const_value(item);
3425 if !is_default_item {
3426 if let Some(t) = trait_ {
3427 // The trait item may have been stripped so we might not
3428 // find any documentation or stability for it.
3429 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3430 // We need the stability of the item from the trait
3431 // because impls can't have a stability.
3432 document_stability(w, cx, it)?;
3433 if item.doc_value().is_some() {
3434 document_full(w, item, cx, &prefix)?;
3435 } else if show_def_docs {
3436 // In case the item isn't documented,
3437 // provide short documentation from the trait.
3438 document_short(w, it, link, cx, &prefix)?;
3442 document_stability(w, cx, item)?;
3444 document_full(w, item, cx, &prefix)?;
3448 document_stability(w, cx, item)?;
3450 document_short(w, item, link, cx, &prefix)?;
3457 let traits = &cache().traits;
3458 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3461 write!(w, "<span class='docblock autohide'>")?;
3464 write!(w, "<div class='impl-items'>")?;
3465 for trait_item in &i.inner_impl().items {
3466 doc_impl_item(w, cx, trait_item, link, render_mode,
3467 false, outer_version, trait_, show_def_docs)?;
3470 fn render_default_items(w: &mut fmt::Formatter,
3474 render_mode: RenderMode,
3475 outer_version: Option<&str>,
3476 show_def_docs: bool) -> fmt::Result {
3477 for trait_item in &t.items {
3478 let n = trait_item.name.clone();
3479 if i.items.iter().find(|m| m.name == n).is_some() {
3482 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3483 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3485 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3486 outer_version, None, show_def_docs)?;
3491 // If we've implemented a trait, then also emit documentation for all
3492 // default items which weren't overridden in the implementation block.
3493 if let Some(t) = trait_ {
3494 render_default_items(w, cx, t, &i.inner_impl(),
3495 render_mode, outer_version, show_def_docs)?;
3497 write!(w, "</div>")?;
3500 write!(w, "</span>")?;
3506 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3507 t: &clean::Typedef) -> fmt::Result {
3508 write!(w, "<pre class='rust typedef'>")?;
3509 render_attributes(w, it)?;
3510 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3511 it.name.as_ref().unwrap(),
3513 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3516 document(w, cx, it)?;
3518 // Render any items associated directly to this alias, as otherwise they
3519 // won't be visible anywhere in the docs. It would be nice to also show
3520 // associated items from the aliased type (see discussion in #32077), but
3521 // we need #14072 to make sense of the generics.
3522 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3525 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3526 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3527 render_attributes(w, it)?;
3530 " {}type {};\n}}</pre>",
3531 VisSpace(&it.visibility),
3532 it.name.as_ref().unwrap(),
3535 document(w, cx, it)?;
3537 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3540 impl<'a> fmt::Display for Sidebar<'a> {
3541 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3544 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3546 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3547 || it.is_enum() || it.is_mod() || it.is_typedef()
3549 write!(fmt, "<p class='location'>")?;
3551 clean::StructItem(..) => write!(fmt, "Struct ")?,
3552 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3553 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3554 clean::UnionItem(..) => write!(fmt, "Union ")?,
3555 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3556 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3557 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3558 clean::ModuleItem(..) => if it.is_crate() {
3559 write!(fmt, "Crate ")?;
3561 write!(fmt, "Module ")?;
3565 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3566 write!(fmt, "</p>")?;
3569 if let Some(ref version) = cache().crate_version {
3571 "<div class='block version'>\
3579 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3580 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3581 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3582 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3583 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3584 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3585 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3586 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3591 // The sidebar is designed to display sibling functions, modules and
3592 // other miscellaneous information. since there are lots of sibling
3593 // items (and that causes quadratic growth in large modules),
3594 // we refactor common parts into a shared JavaScript file per module.
3595 // still, we don't move everything into JS because we want to preserve
3596 // as much HTML as possible in order to allow non-JS-enabled browsers
3597 // to navigate the documentation (though slightly inefficiently).
3599 write!(fmt, "<p class='location'>")?;
3600 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3602 write!(fmt, "::<wbr>")?;
3604 write!(fmt, "<a href='{}index.html'>{}</a>",
3605 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3608 write!(fmt, "</p>")?;
3610 // Sidebar refers to the enclosing module, not this module.
3611 let relpath = if it.is_mod() { "../" } else { "" };
3613 "<script>window.sidebarCurrent = {{\
3618 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3619 ty = it.type_().css_class(),
3622 // There is no sidebar-items.js beyond the crate root path
3623 // FIXME maybe dynamic crate loading can be merged here
3625 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3633 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3634 i.items.iter().filter_map(|item| {
3636 // Maybe check with clean::Visibility::Public as well?
3637 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3638 if !for_deref || should_render_item(item, false) {
3639 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3646 }).collect::<Vec<_>>()
3649 // The point is to url encode any potential character from a type with genericity.
3650 fn small_url_encode(s: &str) -> String {
3651 s.replace("<", "%3C")
3652 .replace(">", "%3E")
3653 .replace(" ", "%20")
3654 .replace("?", "%3F")
3655 .replace("'", "%27")
3656 .replace("&", "%26")
3657 .replace(",", "%2C")
3658 .replace(":", "%3A")
3659 .replace(";", "%3B")
3660 .replace("[", "%5B")
3661 .replace("]", "%5D")
3664 fn sidebar_assoc_items(it: &clean::Item) -> String {
3665 let mut out = String::new();
3667 if let Some(v) = c.impls.get(&it.def_id) {
3669 .filter(|i| i.inner_impl().trait_.is_none())
3670 .flat_map(|i| get_methods(i.inner_impl(), false))
3671 .collect::<String>();
3672 if !ret.is_empty() {
3673 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3674 </a><div class=\"sidebar-links\">{}</div>", ret));
3677 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3678 if let Some(impl_) = v.iter()
3679 .filter(|i| i.inner_impl().trait_.is_some())
3680 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3681 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3683 clean::TypedefItem(ref t, true) => Some(&t.type_),
3687 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3688 c.primitive_locations.get(&prim).cloned()
3689 })).and_then(|did| c.impls.get(&did));
3690 if let Some(impls) = inner_impl {
3691 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3692 out.push_str(&format!("Methods from {:#}<Target={:#}>",
3693 impl_.inner_impl().trait_.as_ref().unwrap(),
3695 out.push_str("</a>");
3696 let ret = impls.iter()
3697 .filter(|i| i.inner_impl().trait_.is_none())
3698 .flat_map(|i| get_methods(i.inner_impl(), true))
3699 .collect::<String>();
3700 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3704 let mut links = HashSet::new();
3707 let is_negative_impl = is_negative_impl(i.inner_impl());
3708 if let Some(ref i) = i.inner_impl().trait_ {
3709 let i_display = format!("{:#}", i);
3710 let out = Escape(&i_display);
3711 let encoded = small_url_encode(&format!("{:#}", i));
3712 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3714 if is_negative_impl { "!" } else { "" },
3716 if !links.contains(&generated) && links.insert(generated.clone()) {
3725 .collect::<String>();
3726 if !ret.is_empty() {
3727 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3728 Trait Implementations</a>");
3729 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3737 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3738 s: &clean::Struct) -> fmt::Result {
3739 let mut sidebar = String::new();
3740 let fields = get_struct_fields_name(&s.fields);
3742 if !fields.is_empty() {
3743 if let doctree::Plain = s.struct_type {
3744 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3745 <div class=\"sidebar-links\">{}</div>", fields));
3749 sidebar.push_str(&sidebar_assoc_items(it));
3751 if !sidebar.is_empty() {
3752 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3757 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3759 clean::ItemEnum::ImplItem(ref i) => {
3760 if let Some(ref trait_) = i.trait_ {
3761 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3770 fn is_negative_impl(i: &clean::Impl) -> bool {
3771 i.polarity == Some(clean::ImplPolarity::Negative)
3774 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3775 t: &clean::Trait) -> fmt::Result {
3776 let mut sidebar = String::new();
3782 Some(ref name) if m.is_associated_type() => {
3783 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3789 .collect::<String>();
3790 let consts = t.items
3794 Some(ref name) if m.is_associated_const() => {
3795 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3801 .collect::<String>();
3802 let required = t.items
3806 Some(ref name) if m.is_ty_method() => {
3807 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3813 .collect::<String>();
3814 let provided = t.items
3818 Some(ref name) if m.is_method() => {
3819 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3824 .collect::<String>();
3826 if !types.is_empty() {
3827 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3828 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3831 if !consts.is_empty() {
3832 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3833 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3836 if !required.is_empty() {
3837 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3838 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3841 if !provided.is_empty() {
3842 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3843 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3849 if let Some(implementors) = c.implementors.get(&it.def_id) {
3850 let res = implementors.iter()
3851 .filter(|i| i.impl_.for_.def_id()
3852 .map_or(false, |d| !c.paths.contains_key(&d)))
3854 if let Some(item) = implementor2item(&c, i) {
3855 match extract_for_impl_name(&item) {
3856 Some((ref name, ref url)) => {
3857 Some(format!("<a href=\"#impl-{}\">{}</a>",
3858 small_url_encode(url),
3867 .collect::<String>();
3868 if !res.is_empty() {
3869 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3870 Implementations on Foreign Types</a><div \
3871 class=\"sidebar-links\">{}</div>",
3876 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3878 sidebar.push_str(&sidebar_assoc_items(it));
3880 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3883 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3884 _p: &clean::PrimitiveType) -> fmt::Result {
3885 let sidebar = sidebar_assoc_items(it);
3887 if !sidebar.is_empty() {
3888 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3893 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3894 _t: &clean::Typedef) -> fmt::Result {
3895 let sidebar = sidebar_assoc_items(it);
3897 if !sidebar.is_empty() {
3898 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3903 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3905 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3910 .filter_map(|f| match f.name {
3911 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3912 {name}</a>", name=name)),
3918 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3919 u: &clean::Union) -> fmt::Result {
3920 let mut sidebar = String::new();
3921 let fields = get_struct_fields_name(&u.fields);
3923 if !fields.is_empty() {
3924 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3925 <div class=\"sidebar-links\">{}</div>", fields));
3928 sidebar.push_str(&sidebar_assoc_items(it));
3930 if !sidebar.is_empty() {
3931 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3936 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3937 e: &clean::Enum) -> fmt::Result {
3938 let mut sidebar = String::new();
3940 let variants = e.variants.iter()
3941 .filter_map(|v| match v.name {
3942 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3943 </a>", name = name)),
3946 .collect::<String>();
3947 if !variants.is_empty() {
3948 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3949 <div class=\"sidebar-links\">{}</div>", variants));
3952 sidebar.push_str(&sidebar_assoc_items(it));
3954 if !sidebar.is_empty() {
3955 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3960 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3961 items: &[clean::Item]) -> fmt::Result {
3962 let mut sidebar = String::new();
3964 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3965 it.type_() == ItemType::Import) {
3966 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3968 name = "Reexports"));
3971 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3972 // to print its headings
3973 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3974 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3975 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3976 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3977 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3978 if items.iter().any(|it| {
3979 if let clean::AutoImplItem(..) = it.inner {
3982 !it.is_stripped() && it.type_() == myty
3985 let (short, name) = match myty {
3986 ItemType::ExternCrate |
3987 ItemType::Import => ("reexports", "Reexports"),
3988 ItemType::Module => ("modules", "Modules"),
3989 ItemType::Struct => ("structs", "Structs"),
3990 ItemType::Union => ("unions", "Unions"),
3991 ItemType::Enum => ("enums", "Enums"),
3992 ItemType::Function => ("functions", "Functions"),
3993 ItemType::Typedef => ("types", "Type Definitions"),
3994 ItemType::Static => ("statics", "Statics"),
3995 ItemType::Constant => ("constants", "Constants"),
3996 ItemType::Trait => ("traits", "Traits"),
3997 ItemType::Impl => ("impls", "Implementations"),
3998 ItemType::TyMethod => ("tymethods", "Type Methods"),
3999 ItemType::Method => ("methods", "Methods"),
4000 ItemType::StructField => ("fields", "Struct Fields"),
4001 ItemType::Variant => ("variants", "Variants"),
4002 ItemType::Macro => ("macros", "Macros"),
4003 ItemType::Primitive => ("primitives", "Primitive Types"),
4004 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4005 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4006 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4008 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4014 if !sidebar.is_empty() {
4015 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4020 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4021 let sidebar = sidebar_assoc_items(it);
4022 if !sidebar.is_empty() {
4023 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4028 impl<'a> fmt::Display for Source<'a> {
4029 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4030 let Source(s) = *self;
4031 let lines = s.lines().count();
4033 let mut tmp = lines;
4038 write!(fmt, "<pre class=\"line-numbers\">")?;
4039 for i in 1..lines + 1 {
4040 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4042 write!(fmt, "</pre>")?;
4044 highlight::render_with_highlighting(s, None, None, None, None))?;
4049 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4050 t: &clean::Macro) -> fmt::Result {
4051 w.write_str(&highlight::render_with_highlighting(&t.source,
4059 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4061 _p: &clean::PrimitiveType) -> fmt::Result {
4062 document(w, cx, it)?;
4063 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4066 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4068 fn make_item_keywords(it: &clean::Item) -> String {
4069 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4072 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4073 let decl = match item.inner {
4074 clean::FunctionItem(ref f) => &f.decl,
4075 clean::MethodItem(ref m) => &m.decl,
4076 clean::TyMethodItem(ref m) => &m.decl,
4080 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4081 let output = match decl.output {
4082 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4086 Some(IndexItemFunctionType { inputs: inputs, output: output })
4089 fn get_index_type(clean_type: &clean::Type) -> Type {
4091 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4092 generics: get_generics(clean_type),
4097 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4099 clean::ResolvedPath { ref path, .. } => {
4100 let segments = &path.segments;
4101 Some(segments[segments.len() - 1].name.clone())
4103 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4104 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4105 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4106 // FIXME: add all from clean::Type.
4111 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4112 clean_type.generics()
4114 let r = types.iter()
4115 .filter_map(|t| get_index_type_name(t, false))
4116 .map(|s| s.to_ascii_lowercase())
4117 .collect::<Vec<_>>();
4126 pub fn cache() -> Arc<Cache> {
4127 CACHE_KEY.with(|c| c.borrow().clone())
4132 fn test_unique_id() {
4133 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4134 "method.into_iter", "foo", "main", "search", "methods",
4135 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4136 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4137 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4138 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4141 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4142 assert_eq!(&actual[..], expected);
4151 fn test_name_key() {
4152 assert_eq!(name_key("0"), ("", 0, 1));
4153 assert_eq!(name_key("123"), ("", 123, 0));
4154 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4155 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4156 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4157 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4158 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4159 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4164 fn test_name_sorting() {
4165 let names = ["Apple",
4167 "Fruit", "Fruit0", "Fruit00",
4168 "Fruit1", "Fruit01",
4169 "Fruit2", "Fruit02",
4173 let mut sorted = names.to_owned();
4174 sorted.sort_by_key(|&s| name_key(s));
4175 assert_eq!(names, sorted);