1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
35 pub use self::ExternalLocation::*;
37 use std::ascii::AsciiExt;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::BTreeMap;
41 use std::default::Default;
43 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
44 use std::fs::{self, File, OpenOptions};
45 use std::io::prelude::*;
46 use std::io::{self, BufWriter, BufReader};
47 use std::iter::repeat;
49 use std::path::{PathBuf, Path, Component};
53 use externalfiles::ExternalHtml;
55 use serialize::json::{ToJson, Json, as_json};
56 use syntax::{abi, ast};
57 use syntax::feature_gate::UnstableFeatures;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc::session::config::nightly_options::is_nightly_build;
64 use rustc_data_structures::flock;
66 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability, 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>)>>,
132 /// Indicates where an external crate can be found.
133 pub enum ExternalLocation {
134 /// Remote URL root of the external crate
136 /// This external crate can be found in the local doc/ folder
138 /// The external crate could not be found.
142 /// Metadata about an implementor of a trait.
143 pub struct Implementor {
145 pub stability: Option<clean::Stability>,
146 pub impl_: clean::Impl,
149 /// Metadata about implementations for a type.
152 pub impl_item: clean::Item,
156 fn inner_impl(&self) -> &clean::Impl {
157 match self.impl_item.inner {
158 clean::ImplItem(ref impl_) => impl_,
159 _ => panic!("non-impl item found in impl")
163 fn trait_did(&self) -> Option<DefId> {
164 self.inner_impl().trait_.def_id()
174 impl error::Error for Error {
175 fn description(&self) -> &str {
176 self.error.description()
180 impl Display for Error {
181 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
182 write!(f, "\"{}\": {}", self.file.display(), self.error)
187 pub fn new(e: io::Error, file: &Path) -> Error {
189 file: file.to_path_buf(),
195 macro_rules! try_err {
196 ($e:expr, $file:expr) => ({
199 Err(e) => return Err(Error::new(e, $file)),
204 /// This cache is used to store information about the `clean::Crate` being
205 /// rendered in order to provide more useful documentation. This contains
206 /// information like all implementors of a trait, all traits a type implements,
207 /// documentation for all known traits, etc.
209 /// This structure purposefully does not implement `Clone` because it's intended
210 /// to be a fairly large and expensive structure to clone. Instead this adheres
211 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
212 /// rendering threads.
215 /// Mapping of typaram ids to the name of the type parameter. This is used
216 /// when pretty-printing a type (so pretty printing doesn't have to
217 /// painfully maintain a context like this)
218 pub typarams: FxHashMap<DefId, String>,
220 /// Maps a type id to all known implementations for that type. This is only
221 /// recognized for intra-crate `ResolvedPath` types, and is used to print
222 /// out extra documentation on the page of an enum/struct.
224 /// The values of the map are a list of implementations and documentation
225 /// found on that implementation.
226 pub impls: FxHashMap<DefId, Vec<Impl>>,
228 /// Maintains a mapping of local crate node ids to the fully qualified name
229 /// and "short type description" of that node. This is used when generating
230 /// URLs when a type is being linked to. External paths are not located in
231 /// this map because the `External` type itself has all the information
233 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
235 /// Similar to `paths`, but only holds external paths. This is only used for
236 /// generating explicit hyperlinks to other crates.
237 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
239 /// This map contains information about all known traits of this crate.
240 /// Implementations of a crate should inherit the documentation of the
241 /// parent trait if no extra documentation is specified, and default methods
242 /// should show up in documentation about trait implementations.
243 pub traits: FxHashMap<DefId, clean::Trait>,
245 /// When rendering traits, it's often useful to be able to list all
246 /// implementors of the trait, and this mapping is exactly, that: a mapping
247 /// of trait ids to the list of known implementors of the trait
248 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
250 /// Cache of where external crate documentation can be found.
251 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
253 /// Cache of where documentation for primitives can be found.
254 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
256 // Note that external items for which `doc(hidden)` applies to are shown as
257 // non-reachable while local items aren't. This is because we're reusing
258 // the access levels from crateanalysis.
259 pub access_levels: Arc<AccessLevels<DefId>>,
261 // Private fields only used when initially crawling a crate to build a cache
264 parent_stack: Vec<DefId>,
265 parent_is_trait_impl: bool,
266 search_index: Vec<IndexItem>,
268 deref_trait_did: Option<DefId>,
269 deref_mut_trait_did: Option<DefId>,
270 owned_box_did: Option<DefId>,
272 // In rare case where a structure is defined in one module but implemented
273 // in another, if the implementing module is parsed before defining module,
274 // then the fully qualified name of the structure isn't presented in `paths`
275 // yet when its implementation methods are being indexed. Caches such methods
276 // and their parent id here and indexes them at the end of crate parsing.
277 orphan_impl_items: Vec<(DefId, clean::Item)>,
280 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
281 /// Later on moved into `CACHE_KEY`.
283 pub struct RenderInfo {
284 pub inlined: FxHashSet<DefId>,
285 pub external_paths: ::core::ExternalPaths,
286 pub external_typarams: FxHashMap<DefId, String>,
287 pub deref_trait_did: Option<DefId>,
288 pub deref_mut_trait_did: Option<DefId>,
289 pub owned_box_did: Option<DefId>,
292 /// Helper struct to render all source code to HTML pages
293 struct SourceCollector<'a> {
294 scx: &'a mut SharedContext,
296 /// Root destination to place all HTML output into
300 /// Wrapper struct to render the source code of a file. This will do things like
301 /// adding line numbers to the left-hand side.
302 struct Source<'a>(&'a str);
304 // Helper structs for rendering items/sidebars and carrying along contextual
307 #[derive(Copy, Clone)]
310 item: &'a clean::Item,
313 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
315 /// Struct representing one entry in the JS search index. These are all emitted
316 /// by hand to a large JS file at the end of cache-creation.
322 parent: Option<DefId>,
323 parent_idx: Option<usize>,
324 search_type: Option<IndexItemFunctionType>,
327 impl ToJson for IndexItem {
328 fn to_json(&self) -> Json {
329 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
331 let mut data = Vec::with_capacity(6);
332 data.push((self.ty as usize).to_json());
333 data.push(self.name.to_json());
334 data.push(self.path.to_json());
335 data.push(self.desc.to_json());
336 data.push(self.parent_idx.to_json());
337 data.push(self.search_type.to_json());
343 /// A type used for the search index.
345 name: Option<String>,
348 impl ToJson for Type {
349 fn to_json(&self) -> Json {
352 let mut data = BTreeMap::new();
353 data.insert("name".to_owned(), name.to_json());
361 /// Full type of functions/methods in the search index.
362 struct IndexItemFunctionType {
367 impl ToJson for IndexItemFunctionType {
368 fn to_json(&self) -> Json {
369 // If we couldn't figure out a type, just write `null`.
370 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
373 let mut data = BTreeMap::new();
374 data.insert("inputs".to_owned(), self.inputs.to_json());
375 data.insert("output".to_owned(), self.output.to_json());
381 // TLS keys used to carry information around during rendering.
383 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
384 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
385 RefCell::new(Vec::new()));
386 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
387 RefCell::new(init_ids()));
389 fn init_ids() -> FxHashMap<String, usize> {
405 ].into_iter().map(|id| (String::from(*id), 1)).collect()
408 /// This method resets the local table of used ID attributes. This is typically
409 /// used at the beginning of rendering an entire HTML page to reset from the
410 /// previous state (if any).
411 pub fn reset_ids(embedded: bool) {
412 USED_ID_MAP.with(|s| {
413 *s.borrow_mut() = if embedded {
421 pub fn derive_id(candidate: String) -> String {
422 USED_ID_MAP.with(|map| {
423 let id = match map.borrow_mut().get_mut(&candidate) {
426 let id = format!("{}-{}", candidate, *a);
432 map.borrow_mut().insert(id.clone(), 1);
437 /// Generates the documentation for `crate` into the directory `dst`
438 pub fn run(mut krate: clean::Crate,
439 external_html: &ExternalHtml,
440 playground_url: Option<String>,
442 passes: FxHashSet<String>,
443 css_file_extension: Option<PathBuf>,
444 renderinfo: RenderInfo,
445 render_type: RenderType) -> Result<(), Error> {
446 let src_root = match krate.src.parent() {
447 Some(p) => p.to_path_buf(),
448 None => PathBuf::new(),
450 let mut scx = SharedContext {
453 include_sources: true,
454 local_sources: FxHashMap(),
455 issue_tracker_base_url: None,
456 layout: layout::Layout {
457 logo: "".to_string(),
458 favicon: "".to_string(),
459 external_html: external_html.clone(),
460 krate: krate.name.clone(),
462 css_file_extension: css_file_extension.clone(),
463 markdown_warnings: RefCell::new(vec![]),
466 // If user passed in `--playground-url` arg, we fill in crate name here
467 if let Some(url) = playground_url {
468 markdown::PLAYGROUND.with(|slot| {
469 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
473 // Crawl the crate attributes looking for attributes which control how we're
474 // going to emit HTML
475 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
476 for attr in attrs.lists("doc") {
477 let name = attr.name().map(|s| s.as_str());
478 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
479 (Some("html_favicon_url"), Some(s)) => {
480 scx.layout.favicon = s.to_string();
482 (Some("html_logo_url"), Some(s)) => {
483 scx.layout.logo = s.to_string();
485 (Some("html_playground_url"), Some(s)) => {
486 markdown::PLAYGROUND.with(|slot| {
487 let name = krate.name.clone();
488 *slot.borrow_mut() = Some((Some(name), s.to_string()));
491 (Some("issue_tracker_base_url"), Some(s)) => {
492 scx.issue_tracker_base_url = Some(s.to_string());
494 (Some("html_no_source"), None) if attr.is_word() => {
495 scx.include_sources = false;
501 try_err!(fs::create_dir_all(&dst), &dst);
502 krate = render_sources(&dst, &mut scx, krate)?;
506 render_redirect_pages: false,
507 shared: Arc::new(scx),
511 // Crawl the crate to build various caches used for the output
521 let external_paths = external_paths.into_iter()
522 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
525 let mut cache = Cache {
529 implementors: FxHashMap(),
531 parent_stack: Vec::new(),
532 search_index: Vec::new(),
533 parent_is_trait_impl: false,
534 extern_locations: FxHashMap(),
535 primitive_locations: FxHashMap(),
537 access_levels: krate.access_levels.clone(),
538 orphan_impl_items: Vec::new(),
539 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
543 typarams: external_typarams,
546 // Cache where all our extern crates are located
547 for &(n, ref e) in &krate.externs {
548 let src_root = match Path::new(&e.src).parent() {
549 Some(p) => p.to_path_buf(),
550 None => PathBuf::new(),
552 cache.extern_locations.insert(n, (e.name.clone(), src_root,
553 extern_location(e, &cx.dst)));
555 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
556 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
559 // Cache where all known primitives have their documentation located.
561 // Favor linking to as local extern as possible, so iterate all crates in
562 // reverse topological order.
563 for &(_, ref e) in krate.externs.iter().rev() {
564 for &(def_id, prim, _) in &e.primitives {
565 cache.primitive_locations.insert(prim, def_id);
568 for &(def_id, prim, _) in &krate.primitives {
569 cache.primitive_locations.insert(prim, def_id);
572 cache.stack.push(krate.name.clone());
573 krate = cache.fold_crate(krate);
575 // Build our search index
576 let index = build_index(&krate, &mut cache);
578 // Freeze the cache now that the index has been built. Put an Arc into TLS
579 // for future parallelization opportunities
580 let cache = Arc::new(cache);
581 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
582 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
584 write_shared(&cx, &krate, &*cache, index)?;
586 let scx = cx.shared.clone();
588 // And finally render the whole crate's documentation
589 let result = cx.krate(krate);
591 let markdown_warnings = scx.markdown_warnings.borrow();
592 if !markdown_warnings.is_empty() {
593 println!("WARNING: documentation for this crate may be rendered \
594 differently using the new Pulldown renderer.");
595 println!(" See https://github.com/rust-lang/rust/issues/44229 for details.");
596 for &(ref span, ref text, ref diffs) in &*markdown_warnings {
597 println!("WARNING: rendering difference in `{}`", concise_str(text));
598 println!(" --> {}:{}:{}", span.filename, span.loline, span.locol);
600 render_difference(d);
608 // A short, single-line view of `s`.
609 fn concise_str(s: &str) -> String {
610 if s.contains('\n') {
611 return format!("{}...", &s[..s.find('\n').unwrap()]);
614 return format!("{} ... {}", &s[..50], &s[s.len()-20..]);
619 // Returns short versions of s1 and s2, starting from where the strings differ.
620 fn concise_compared_strs(s1: &str, s2: &str) -> (String, String) {
623 if !s1.contains('\n') && !s2.contains('\n') && s1.len() <= 70 && s2.len() <= 70 {
624 return (s1.to_owned(), s2.to_owned());
627 let mut start_byte = 0;
628 for (c1, c2) in s1.chars().zip(s2.chars()) {
633 start_byte += c1.len_utf8();
637 return (concise_str(s1), concise_str(s2));
640 let s1 = &s1[start_byte..];
641 let s2 = &s2[start_byte..];
642 (format!("...{}", concise_str(s1)), format!("...{}", concise_str(s2)))
645 fn render_difference(diff: &html_diff::Difference) {
647 html_diff::Difference::NodeType { ref elem, ref opposite_elem } => {
648 println!(" {} Types differ: expected: `{}`, found: `{}`",
649 elem.path, elem.element_name, opposite_elem.element_name);
651 html_diff::Difference::NodeName { ref elem, ref opposite_elem } => {
652 println!(" {} Tags differ: expected: `{}`, found: `{}`",
653 elem.path, elem.element_name, opposite_elem.element_name);
655 html_diff::Difference::NodeAttributes { ref elem,
657 ref opposite_elem_attributes,
659 println!(" {} Attributes differ in `{}`: expected: `{:?}`, found: `{:?}`",
660 elem.path, elem.element_name, elem_attributes, opposite_elem_attributes);
662 html_diff::Difference::NodeText { ref elem, ref elem_text, ref opposite_elem_text, .. } => {
663 let (s1, s2) = concise_compared_strs(elem_text, opposite_elem_text);
664 println!(" {} Text differs:\n expected: `{}`\n found: `{}`",
667 html_diff::Difference::NotPresent { ref elem, ref opposite_elem } => {
668 if let Some(ref elem) = *elem {
669 println!(" {} One element is missing: expected: `{}`",
670 elem.path, elem.element_name);
671 } else if let Some(ref elem) = *opposite_elem {
672 if elem.element_name.is_empty() {
673 println!(" {} Unexpected element: `{}`",
674 elem.path, concise_str(&elem.element_content));
676 println!(" {} Unexpected element `{}`: found: `{}`",
677 elem.path, elem.element_name, concise_str(&elem.element_content));
684 /// Build the search index from the collected metadata
685 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
686 let mut nodeid_to_pathid = FxHashMap();
687 let mut crate_items = Vec::with_capacity(cache.search_index.len());
688 let mut crate_paths = Vec::<Json>::new();
690 let Cache { ref mut search_index,
691 ref orphan_impl_items,
692 ref mut paths, .. } = *cache;
694 // Attach all orphan items to the type's definition if the type
695 // has since been learned.
696 for &(did, ref item) in orphan_impl_items {
697 if let Some(&(ref fqp, _)) = paths.get(&did) {
698 search_index.push(IndexItem {
700 name: item.name.clone().unwrap(),
701 path: fqp[..fqp.len() - 1].join("::"),
702 desc: plain_summary_line(item.doc_value()),
705 search_type: get_index_search_type(&item),
710 // Reduce `NodeId` in paths into smaller sequential numbers,
711 // and prune the paths that do not appear in the index.
712 let mut lastpath = String::new();
713 let mut lastpathid = 0usize;
715 for item in search_index {
716 item.parent_idx = item.parent.map(|nodeid| {
717 if nodeid_to_pathid.contains_key(&nodeid) {
718 *nodeid_to_pathid.get(&nodeid).unwrap()
720 let pathid = lastpathid;
721 nodeid_to_pathid.insert(nodeid, pathid);
724 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
725 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
730 // Omit the parent path if it is same to that of the prior item.
731 if lastpath == item.path {
734 lastpath = item.path.clone();
736 crate_items.push(item.to_json());
739 let crate_doc = krate.module.as_ref().map(|module| {
740 plain_summary_line(module.doc_value())
741 }).unwrap_or(String::new());
743 let mut crate_data = BTreeMap::new();
744 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
745 crate_data.insert("items".to_owned(), Json::Array(crate_items));
746 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
748 // Collect the index into a string
749 format!("searchIndex[{}] = {};",
750 as_json(&krate.name),
751 Json::Object(crate_data))
754 fn write_shared(cx: &Context,
755 krate: &clean::Crate,
757 search_index: String) -> Result<(), Error> {
758 // Write out the shared files. Note that these are shared among all rustdoc
759 // docs placed in the output directory, so this needs to be a synchronized
760 // operation with respect to all other rustdocs running around.
761 try_err!(fs::create_dir_all(&cx.dst), &cx.dst);
762 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
764 // Add all the static files. These may already exist, but we just
765 // overwrite them anyway to make sure that they're fresh and up-to-date.
767 write(cx.dst.join("main.js"),
768 include_bytes!("static/main.js"))?;
769 write(cx.dst.join("rustdoc.css"),
770 include_bytes!("static/rustdoc.css"))?;
771 write(cx.dst.join("main.css"),
772 include_bytes!("static/styles/main.css"))?;
773 if let Some(ref css) = cx.shared.css_file_extension {
774 let mut content = String::new();
775 let css = css.as_path();
776 let mut f = try_err!(File::open(css), css);
778 try_err!(f.read_to_string(&mut content), css);
779 let css = cx.dst.join("theme.css");
780 let css = css.as_path();
781 let mut f = try_err!(File::create(css), css);
782 try_err!(write!(f, "{}", &content), css);
784 write(cx.dst.join("normalize.css"),
785 include_bytes!("static/normalize.css"))?;
786 write(cx.dst.join("FiraSans-Regular.woff"),
787 include_bytes!("static/FiraSans-Regular.woff"))?;
788 write(cx.dst.join("FiraSans-Medium.woff"),
789 include_bytes!("static/FiraSans-Medium.woff"))?;
790 write(cx.dst.join("FiraSans-LICENSE.txt"),
791 include_bytes!("static/FiraSans-LICENSE.txt"))?;
792 write(cx.dst.join("Heuristica-Italic.woff"),
793 include_bytes!("static/Heuristica-Italic.woff"))?;
794 write(cx.dst.join("Heuristica-LICENSE.txt"),
795 include_bytes!("static/Heuristica-LICENSE.txt"))?;
796 write(cx.dst.join("SourceSerifPro-Regular.woff"),
797 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
798 write(cx.dst.join("SourceSerifPro-Bold.woff"),
799 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
800 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
801 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
802 write(cx.dst.join("SourceCodePro-Regular.woff"),
803 include_bytes!("static/SourceCodePro-Regular.woff"))?;
804 write(cx.dst.join("SourceCodePro-Semibold.woff"),
805 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
806 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
807 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
808 write(cx.dst.join("LICENSE-MIT.txt"),
809 include_bytes!("static/LICENSE-MIT.txt"))?;
810 write(cx.dst.join("LICENSE-APACHE.txt"),
811 include_bytes!("static/LICENSE-APACHE.txt"))?;
812 write(cx.dst.join("COPYRIGHT.txt"),
813 include_bytes!("static/COPYRIGHT.txt"))?;
815 fn collect(path: &Path, krate: &str,
816 key: &str) -> io::Result<Vec<String>> {
817 let mut ret = Vec::new();
819 for line in BufReader::new(File::open(path)?).lines() {
821 if !line.starts_with(key) {
824 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
827 ret.push(line.to_string());
833 // Update the search index
834 let dst = cx.dst.join("search-index.js");
835 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
836 all_indexes.push(search_index);
837 // Sort the indexes by crate so the file will be generated identically even
838 // with rustdoc running in parallel.
840 let mut w = try_err!(File::create(&dst), &dst);
841 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
842 for index in &all_indexes {
843 try_err!(writeln!(&mut w, "{}", *index), &dst);
845 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
847 // Update the list of all implementors for traits
848 let dst = cx.dst.join("implementors");
849 for (&did, imps) in &cache.implementors {
850 // Private modules can leak through to this phase of rustdoc, which
851 // could contain implementations for otherwise private types. In some
852 // rare cases we could find an implementation for an item which wasn't
853 // indexed, so we just skip this step in that case.
855 // FIXME: this is a vague explanation for why this can't be a `get`, in
856 // theory it should be...
857 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
859 None => match cache.external_paths.get(&did) {
865 let mut have_impls = false;
866 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
868 // If the trait and implementation are in the same crate, then
869 // there's no need to emit information about it (there's inlining
870 // going on). If they're in different crates then the crate defining
871 // the trait will be interested in our implementation.
872 if imp.def_id.krate == did.krate { continue }
873 // If the implementation is from another crate then that crate
875 if !imp.def_id.is_local() { continue }
877 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
879 implementors.push_str("];");
881 // Only create a js file if we have impls to add to it. If the trait is
882 // documented locally though we always create the file to avoid dead
884 if !have_impls && !cache.paths.contains_key(&did) {
888 let mut mydst = dst.clone();
889 for part in &remote_path[..remote_path.len() - 1] {
892 try_err!(fs::create_dir_all(&mydst), &mydst);
893 mydst.push(&format!("{}.{}.js",
894 remote_item_type.css_class(),
895 remote_path[remote_path.len() - 1]));
897 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
898 all_implementors.push(implementors);
899 // Sort the implementors by crate so the file will be generated
900 // identically even with rustdoc running in parallel.
901 all_implementors.sort();
903 let mut f = try_err!(File::create(&mydst), &mydst);
904 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
905 for implementor in &all_implementors {
906 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
908 try_err!(writeln!(&mut f, "{}", r"
909 if (window.register_implementors) {
910 window.register_implementors(implementors);
912 window.pending_implementors = implementors;
915 try_err!(writeln!(&mut f, r"}})()"), &mydst);
920 fn render_sources(dst: &Path, scx: &mut SharedContext,
921 krate: clean::Crate) -> Result<clean::Crate, Error> {
922 info!("emitting source files");
923 let dst = dst.join("src").join(&krate.name);
924 try_err!(fs::create_dir_all(&dst), &dst);
925 let mut folder = SourceCollector {
929 Ok(folder.fold_crate(krate))
932 /// Writes the entire contents of a string to a destination, not attempting to
933 /// catch any errors.
934 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
935 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
938 /// Takes a path to a source file and cleans the path to it. This canonicalizes
939 /// things like ".." to components which preserve the "top down" hierarchy of a
940 /// static HTML tree. Each component in the cleaned path will be passed as an
941 /// argument to `f`. The very last component of the path (ie the file name) will
942 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
943 // FIXME (#9639): The closure should deal with &[u8] instead of &str
944 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
945 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
948 // make it relative, if possible
949 let p = p.strip_prefix(src_root).unwrap_or(p);
951 let mut iter = p.components().peekable();
953 while let Some(c) = iter.next() {
954 if !keep_filename && iter.peek().is_none() {
959 Component::ParentDir => f("up"),
960 Component::Normal(c) => f(c.to_str().unwrap()),
966 /// Attempts to find where an external crate is located, given that we're
967 /// rendering in to the specified source destination.
968 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
969 // See if there's documentation generated into the local directory
970 let local_location = dst.join(&e.name);
971 if local_location.is_dir() {
975 // Failing that, see if there's an attribute specifying where to find this
978 .filter(|a| a.check_name("html_root_url"))
979 .filter_map(|a| a.value_str())
981 let mut url = url.to_string();
982 if !url.ends_with("/") {
986 }).next().unwrap_or(Unknown) // Well, at least we tried.
989 impl<'a> DocFolder for SourceCollector<'a> {
990 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
991 // If we're including source files, and we haven't seen this file yet,
992 // then we need to render it out to the filesystem.
993 if self.scx.include_sources
994 // skip all invalid spans
995 && item.source.filename != ""
996 // skip non-local items
997 && item.def_id.is_local()
998 // Macros from other libraries get special filenames which we can
1000 && !(item.source.filename.starts_with("<")
1001 && item.source.filename.ends_with("macros>")) {
1003 // If it turns out that we couldn't read this file, then we probably
1004 // can't read any of the files (generating html output from json or
1005 // something like that), so just don't include sources for the
1006 // entire crate. The other option is maintaining this mapping on a
1007 // per-file basis, but that's probably not worth it...
1009 .include_sources = match self.emit_source(&item.source.filename) {
1012 println!("warning: source code was requested to be rendered, \
1013 but processing `{}` had an error: {}",
1014 item.source.filename, e);
1015 println!(" skipping rendering of source code");
1020 self.fold_item_recur(item)
1024 impl<'a> SourceCollector<'a> {
1025 /// Renders the given filename into its corresponding HTML source file.
1026 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
1027 let p = PathBuf::from(filename);
1028 if self.scx.local_sources.contains_key(&p) {
1029 // We've already emitted this source
1033 let mut contents = Vec::new();
1034 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
1036 let contents = str::from_utf8(&contents).unwrap();
1038 // Remove the utf-8 BOM if any
1039 let contents = if contents.starts_with("\u{feff}") {
1045 // Create the intermediate directories
1046 let mut cur = self.dst.clone();
1047 let mut root_path = String::from("../../");
1048 let mut href = String::new();
1049 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1050 cur.push(component);
1051 fs::create_dir_all(&cur).unwrap();
1052 root_path.push_str("../");
1053 href.push_str(component);
1056 let mut fname = p.file_name().expect("source has no filename")
1058 fname.push(".html");
1060 href.push_str(&fname.to_string_lossy());
1062 let mut w = BufWriter::new(File::create(&cur)?);
1063 let title = format!("{} -- source", cur.file_name().unwrap()
1064 .to_string_lossy());
1065 let desc = format!("Source to the Rust file `{}`.", filename);
1066 let page = layout::Page {
1068 css_class: "source",
1069 root_path: &root_path,
1071 keywords: BASIC_KEYWORDS,
1073 layout::render(&mut w, &self.scx.layout,
1074 &page, &(""), &Source(contents),
1075 self.scx.css_file_extension.is_some())?;
1077 self.scx.local_sources.insert(p, href);
1082 impl DocFolder for Cache {
1083 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1084 // If this is a stripped module,
1085 // we don't want it or its children in the search index.
1086 let orig_stripped_mod = match item.inner {
1087 clean::StrippedItem(box clean::ModuleItem(..)) => {
1088 mem::replace(&mut self.stripped_mod, true)
1090 _ => self.stripped_mod,
1093 // Register any generics to their corresponding string. This is used
1094 // when pretty-printing types.
1095 if let Some(generics) = item.inner.generics() {
1096 self.generics(generics);
1099 // Propagate a trait method's documentation to all implementors of the
1101 if let clean::TraitItem(ref t) = item.inner {
1102 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1105 // Collect all the implementors of traits.
1106 if let clean::ImplItem(ref i) = item.inner {
1107 if let Some(did) = i.trait_.def_id() {
1108 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1109 def_id: item.def_id,
1110 stability: item.stability.clone(),
1116 // Index this method for searching later on.
1117 if let Some(ref s) = item.name {
1118 let (parent, is_inherent_impl_item) = match item.inner {
1119 clean::StrippedItem(..) => ((None, None), false),
1120 clean::AssociatedConstItem(..) |
1121 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1122 // skip associated items in trait impls
1123 ((None, None), false)
1125 clean::AssociatedTypeItem(..) |
1126 clean::TyMethodItem(..) |
1127 clean::StructFieldItem(..) |
1128 clean::VariantItem(..) => {
1129 ((Some(*self.parent_stack.last().unwrap()),
1130 Some(&self.stack[..self.stack.len() - 1])),
1133 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1134 if self.parent_stack.is_empty() {
1135 ((None, None), false)
1137 let last = self.parent_stack.last().unwrap();
1139 let path = match self.paths.get(&did) {
1140 // The current stack not necessarily has correlation
1141 // for where the type was defined. On the other
1142 // hand, `paths` always has the right
1143 // information if present.
1144 Some(&(ref fqp, ItemType::Trait)) |
1145 Some(&(ref fqp, ItemType::Struct)) |
1146 Some(&(ref fqp, ItemType::Union)) |
1147 Some(&(ref fqp, ItemType::Enum)) =>
1148 Some(&fqp[..fqp.len() - 1]),
1149 Some(..) => Some(&*self.stack),
1152 ((Some(*last), path), true)
1155 _ => ((None, Some(&*self.stack)), false)
1159 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1160 debug_assert!(!item.is_stripped());
1162 // A crate has a module at its root, containing all items,
1163 // which should not be indexed. The crate-item itself is
1164 // inserted later on when serializing the search-index.
1165 if item.def_id.index != CRATE_DEF_INDEX {
1166 self.search_index.push(IndexItem {
1168 name: s.to_string(),
1169 path: path.join("::").to_string(),
1170 desc: plain_summary_line(item.doc_value()),
1173 search_type: get_index_search_type(&item),
1177 (Some(parent), None) if is_inherent_impl_item => {
1178 // We have a parent, but we don't know where they're
1179 // defined yet. Wait for later to index this item.
1180 self.orphan_impl_items.push((parent, item.clone()));
1186 // Keep track of the fully qualified path for this item.
1187 let pushed = match item.name {
1188 Some(ref n) if !n.is_empty() => {
1189 self.stack.push(n.to_string());
1196 clean::StructItem(..) | clean::EnumItem(..) |
1197 clean::TypedefItem(..) | clean::TraitItem(..) |
1198 clean::FunctionItem(..) | clean::ModuleItem(..) |
1199 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1200 clean::ConstantItem(..) | clean::StaticItem(..) |
1201 clean::UnionItem(..)
1202 if !self.stripped_mod => {
1203 // Reexported items mean that the same id can show up twice
1204 // in the rustdoc ast that we're looking at. We know,
1205 // however, that a reexported item doesn't show up in the
1206 // `public_items` map, so we can skip inserting into the
1207 // paths map if there was already an entry present and we're
1208 // not a public item.
1210 !self.paths.contains_key(&item.def_id) ||
1211 self.access_levels.is_public(item.def_id)
1213 self.paths.insert(item.def_id,
1214 (self.stack.clone(), item.type_()));
1217 // Link variants to their parent enum because pages aren't emitted
1218 // for each variant.
1219 clean::VariantItem(..) if !self.stripped_mod => {
1220 let mut stack = self.stack.clone();
1222 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1225 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1226 self.paths.insert(item.def_id, (self.stack.clone(),
1233 // Maintain the parent stack
1234 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1235 let parent_pushed = match item.inner {
1236 clean::TraitItem(..) | clean::EnumItem(..) |
1237 clean::StructItem(..) | clean::UnionItem(..) => {
1238 self.parent_stack.push(item.def_id);
1239 self.parent_is_trait_impl = false;
1242 clean::ImplItem(ref i) => {
1243 self.parent_is_trait_impl = i.trait_.is_some();
1245 clean::ResolvedPath{ did, .. } => {
1246 self.parent_stack.push(did);
1250 let prim_did = t.primitive_type().and_then(|t| {
1251 self.primitive_locations.get(&t).cloned()
1255 self.parent_stack.push(did);
1266 // Once we've recursively found all the generics, hoard off all the
1267 // implementations elsewhere.
1268 let ret = self.fold_item_recur(item).and_then(|item| {
1269 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1270 // Figure out the id of this impl. This may map to a
1271 // primitive rather than always to a struct/enum.
1272 // Note: matching twice to restrict the lifetime of the `i` borrow.
1273 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1275 clean::ResolvedPath { did, .. } |
1276 clean::BorrowedRef {
1277 type_: box clean::ResolvedPath { did, .. }, ..
1282 t.primitive_type().and_then(|t| {
1283 self.primitive_locations.get(&t).cloned()
1290 if let Some(did) = did {
1291 self.impls.entry(did).or_insert(vec![]).push(Impl {
1301 if pushed { self.stack.pop().unwrap(); }
1302 if parent_pushed { self.parent_stack.pop().unwrap(); }
1303 self.stripped_mod = orig_stripped_mod;
1304 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1310 fn generics(&mut self, generics: &clean::Generics) {
1311 for typ in &generics.type_params {
1312 self.typarams.insert(typ.did, typ.name.clone());
1318 /// String representation of how to get back to the root path of the 'doc/'
1319 /// folder in terms of a relative URL.
1320 fn root_path(&self) -> String {
1321 repeat("../").take(self.current.len()).collect::<String>()
1324 /// Recurse in the directory structure and change the "root path" to make
1325 /// sure it always points to the top (relatively).
1326 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1327 F: FnOnce(&mut Context) -> T,
1330 panic!("Unexpected empty destination: {:?}", self.current);
1332 let prev = self.dst.clone();
1334 self.current.push(s);
1336 info!("Recursing into {}", self.dst.display());
1340 info!("Recursed; leaving {}", self.dst.display());
1342 // Go back to where we were at
1344 self.current.pop().unwrap();
1349 /// Main method for rendering a crate.
1351 /// This currently isn't parallelized, but it'd be pretty easy to add
1352 /// parallelization to this function.
1353 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1354 let mut item = match krate.module.take() {
1356 None => return Ok(()),
1358 item.name = Some(krate.name);
1360 // Render the crate documentation
1361 let mut work = vec![(self, item)];
1363 while let Some((mut cx, item)) = work.pop() {
1364 cx.item(item, |cx, item| {
1365 work.push((cx.clone(), item))
1371 fn render_item(&self,
1372 writer: &mut io::Write,
1376 // A little unfortunate that this is done like this, but it sure
1377 // does make formatting *a lot* nicer.
1378 CURRENT_LOCATION_KEY.with(|slot| {
1379 *slot.borrow_mut() = self.current.clone();
1382 let mut title = if it.is_primitive() {
1383 // No need to include the namespace for primitive types
1386 self.current.join("::")
1389 if !title.is_empty() {
1390 title.push_str("::");
1392 title.push_str(it.name.as_ref().unwrap());
1394 title.push_str(" - Rust");
1395 let tyname = it.type_().css_class();
1396 let desc = if it.is_crate() {
1397 format!("API documentation for the Rust `{}` crate.",
1398 self.shared.layout.krate)
1400 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1401 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1403 let keywords = make_item_keywords(it);
1404 let page = layout::Page {
1406 root_path: &self.root_path(),
1409 keywords: &keywords,
1414 if !self.render_redirect_pages {
1415 layout::render(writer, &self.shared.layout, &page,
1416 &Sidebar{ cx: self, item: it },
1417 &Item{ cx: self, item: it },
1418 self.shared.css_file_extension.is_some())?;
1420 let mut url = self.root_path();
1421 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1422 for name in &names[..names.len() - 1] {
1426 url.push_str(&item_path(ty, names.last().unwrap()));
1427 layout::redirect(writer, &url)?;
1433 /// Non-parallelized version of rendering an item. This will take the input
1434 /// item, render its contents, and then invoke the specified closure with
1435 /// all sub-items which need to be rendered.
1437 /// The rendering driver uses this closure to queue up more work.
1438 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1439 F: FnMut(&mut Context, clean::Item),
1441 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1442 // if they contain impls for public types. These modules can also
1443 // contain items such as publicly reexported structures.
1445 // External crates will provide links to these structures, so
1446 // these modules are recursed into, but not rendered normally
1447 // (a flag on the context).
1448 if !self.render_redirect_pages {
1449 self.render_redirect_pages = item.is_stripped();
1453 // modules are special because they add a namespace. We also need to
1454 // recurse into the items of the module as well.
1455 let name = item.name.as_ref().unwrap().to_string();
1456 let mut item = Some(item);
1457 self.recurse(name, |this| {
1458 let item = item.take().unwrap();
1460 let mut buf = Vec::new();
1461 this.render_item(&mut buf, &item, false).unwrap();
1462 // buf will be empty if the module is stripped and there is no redirect for it
1463 if !buf.is_empty() {
1464 let joint_dst = this.dst.join("index.html");
1465 try_err!(fs::create_dir_all(&this.dst), &this.dst);
1466 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1467 try_err!(dst.write_all(&buf), &joint_dst);
1470 let m = match item.inner {
1471 clean::StrippedItem(box clean::ModuleItem(m)) |
1472 clean::ModuleItem(m) => m,
1476 // Render sidebar-items.js used throughout this module.
1477 if !this.render_redirect_pages {
1478 let items = this.build_sidebar_items(&m);
1479 let js_dst = this.dst.join("sidebar-items.js");
1480 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1481 try_err!(write!(&mut js_out, "initSidebarItems({});",
1482 as_json(&items)), &js_dst);
1485 for item in m.items {
1491 } else if item.name.is_some() {
1492 let mut buf = Vec::new();
1493 self.render_item(&mut buf, &item, true).unwrap();
1494 // buf will be empty if the item is stripped and there is no redirect for it
1495 if !buf.is_empty() {
1496 let name = item.name.as_ref().unwrap();
1497 let item_type = item.type_();
1498 let file_name = &item_path(item_type, name);
1499 let joint_dst = self.dst.join(file_name);
1500 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1501 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1502 try_err!(dst.write_all(&buf), &joint_dst);
1504 // Redirect from a sane URL using the namespace to Rustdoc's
1505 // URL for the page.
1506 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1507 let redir_dst = self.dst.join(redir_name);
1508 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1511 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1514 // If the item is a macro, redirect from the old macro URL (with !)
1515 // to the new one (without).
1516 // FIXME(#35705) remove this redirect.
1517 if item_type == ItemType::Macro {
1518 let redir_name = format!("{}.{}!.html", item_type, name);
1519 let redir_dst = self.dst.join(redir_name);
1520 let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1521 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1528 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1529 // BTreeMap instead of HashMap to get a sorted output
1530 let mut map = BTreeMap::new();
1531 for item in &m.items {
1532 if item.is_stripped() { continue }
1534 let short = item.type_().css_class();
1535 let myname = match item.name {
1537 Some(ref s) => s.to_string(),
1539 let short = short.to_string();
1540 map.entry(short).or_insert(vec![])
1541 .push((myname, Some(plain_summary_line(item.doc_value()))));
1544 for (_, items) in &mut map {
1552 /// Generate a url appropriate for an `href` attribute back to the source of
1555 /// The url generated, when clicked, will redirect the browser back to the
1556 /// original source code.
1558 /// If `None` is returned, then a source link couldn't be generated. This
1559 /// may happen, for example, with externally inlined items where the source
1560 /// of their crate documentation isn't known.
1561 fn src_href(&self) -> Option<String> {
1562 let mut root = self.cx.root_path();
1564 let cache = cache();
1565 let mut path = String::new();
1566 let (krate, path) = if self.item.def_id.is_local() {
1567 let path = PathBuf::from(&self.item.source.filename);
1568 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1569 (&self.cx.shared.layout.krate, path)
1574 // Macros from other libraries get special filenames which we can
1576 if self.item.source.filename.starts_with("<") &&
1577 self.item.source.filename.ends_with("macros>") {
1581 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1582 Some(&(ref name, ref src, Local)) => (name, src),
1583 Some(&(ref name, ref src, Remote(ref s))) => {
1584 root = s.to_string();
1587 Some(&(_, _, Unknown)) | None => return None,
1590 let file = Path::new(&self.item.source.filename);
1591 clean_srcpath(&src_root, file, false, |component| {
1592 path.push_str(component);
1595 let mut fname = file.file_name().expect("source has no filename")
1597 fname.push(".html");
1598 path.push_str(&fname.to_string_lossy());
1602 let lines = if self.item.source.loline == self.item.source.hiline {
1603 format!("{}", self.item.source.loline)
1605 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1607 Some(format!("{root}src/{krate}/{path}#{lines}",
1615 impl<'a> fmt::Display for Item<'a> {
1616 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1617 debug_assert!(!self.item.is_stripped());
1618 // Write the breadcrumb trail header for the top
1619 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1620 match self.item.inner {
1621 clean::ModuleItem(ref m) => if m.is_crate {
1622 write!(fmt, "Crate ")?;
1624 write!(fmt, "Module ")?;
1626 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1627 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1628 clean::StructItem(..) => write!(fmt, "Struct ")?,
1629 clean::UnionItem(..) => write!(fmt, "Union ")?,
1630 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1631 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1632 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1633 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1634 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1635 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1637 // We don't generate pages for any other type.
1641 if !self.item.is_primitive() {
1642 let cur = &self.cx.current;
1643 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1644 for (i, component) in cur.iter().enumerate().take(amt) {
1645 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1646 repeat("../").take(cur.len() - i - 1)
1647 .collect::<String>(),
1651 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1652 self.item.type_(), self.item.name.as_ref().unwrap())?;
1654 write!(fmt, "</span>")?; // in-band
1655 write!(fmt, "<span class='out-of-band'>")?;
1656 if let Some(version) = self.item.stable_since() {
1657 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1661 r##"<span id='render-detail'>
1662 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1663 [<span class='inner'>−</span>]
1669 // When this item is part of a `pub use` in a downstream crate, the
1670 // [src] link in the downstream documentation will actually come back to
1671 // this page, and this link will be auto-clicked. The `id` attribute is
1672 // used to find the link to auto-click.
1673 if self.cx.shared.include_sources && !self.item.is_primitive() {
1674 if let Some(l) = self.src_href() {
1675 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1676 l, "goto source code")?;
1680 write!(fmt, "</span>")?; // out-of-band
1682 write!(fmt, "</h1>\n")?;
1684 match self.item.inner {
1685 clean::ModuleItem(ref m) => {
1686 item_module(fmt, self.cx, self.item, &m.items)
1688 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1689 item_function(fmt, self.cx, self.item, f),
1690 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1691 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1692 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1693 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1694 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1695 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1696 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1697 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1698 item_static(fmt, self.cx, self.item, i),
1699 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1701 // We don't generate pages for any other type.
1708 fn item_path(ty: ItemType, name: &str) -> String {
1710 ItemType::Module => format!("{}/index.html", name),
1711 _ => format!("{}.{}.html", ty.css_class(), name),
1715 fn full_path(cx: &Context, item: &clean::Item) -> String {
1716 let mut s = cx.current.join("::");
1718 s.push_str(item.name.as_ref().unwrap());
1722 fn shorter<'a>(s: Option<&'a str>) -> String {
1724 Some(s) => s.lines().take_while(|line|{
1725 (*line).chars().any(|chr|{
1726 !chr.is_whitespace()
1728 }).collect::<Vec<_>>().join("\n"),
1729 None => "".to_string()
1734 fn plain_summary_line(s: Option<&str>) -> String {
1735 let line = shorter(s).replace("\n", " ");
1736 markdown::plain_summary_line(&line[..])
1739 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1740 document_stability(w, cx, item)?;
1741 let prefix = render_assoc_const_value(item);
1742 document_full(w, item, cx, &prefix)?;
1746 /// Render md_text as markdown. Warns the user if there are difference in
1747 /// rendering between Pulldown and Hoedown.
1748 fn render_markdown(w: &mut fmt::Formatter,
1751 render_type: RenderType,
1753 scx: &SharedContext)
1755 let hoedown_output = format!("{}", Markdown(md_text, RenderType::Hoedown));
1756 // We only emit warnings if the user has opted-in to Pulldown rendering.
1757 let output = if render_type == RenderType::Pulldown {
1758 let pulldown_output = format!("{}", Markdown(md_text, RenderType::Pulldown));
1759 let differences = html_diff::get_differences(&pulldown_output, &hoedown_output);
1760 let differences = differences.into_iter()
1763 html_diff::Difference::NodeText { ref elem_text,
1764 ref opposite_elem_text,
1766 if elem_text.trim() == opposite_elem_text.trim() => false,
1770 .collect::<Vec<_>>();
1772 if !differences.is_empty() {
1773 scx.markdown_warnings.borrow_mut().push((span, md_text.to_owned(), differences));
1781 write!(w, "<div class='docblock'>{}{}</div>", prefix, output)
1784 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1785 cx: &Context, prefix: &str) -> fmt::Result {
1786 if let Some(s) = item.doc_value() {
1787 let markdown = if s.contains('\n') {
1788 format!("{} [Read more]({})",
1789 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1791 format!("{}", &plain_summary_line(Some(s)))
1793 render_markdown(w, &markdown, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1794 } else if !prefix.is_empty() {
1795 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1800 fn render_assoc_const_value(item: &clean::Item) -> String {
1802 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1803 highlight::render_with_highlighting(
1804 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1814 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1815 cx: &Context, prefix: &str) -> fmt::Result {
1816 if let Some(s) = item.doc_value() {
1817 render_markdown(w, s, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1818 } else if !prefix.is_empty() {
1819 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1824 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1825 let stabilities = short_stability(item, cx, true);
1826 if !stabilities.is_empty() {
1827 write!(w, "<div class='stability'>")?;
1828 for stability in stabilities {
1829 write!(w, "{}", stability)?;
1831 write!(w, "</div>")?;
1836 fn name_key(name: &str) -> (&str, u64, usize) {
1837 // find number at end
1838 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1840 // count leading zeroes
1842 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1844 // sort leading zeroes last
1845 let num_zeroes = after_zeroes - split;
1847 match name[split..].parse() {
1848 Ok(n) => (&name[..split], n, num_zeroes),
1849 Err(_) => (name, 0, num_zeroes),
1853 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1854 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1855 document(w, cx, item)?;
1857 let mut indices = (0..items.len()).filter(|i| {
1858 if let clean::DefaultImplItem(..) = items[*i].inner {
1861 !items[*i].is_stripped()
1862 }).collect::<Vec<usize>>();
1864 // the order of item types in the listing
1865 fn reorder(ty: ItemType) -> u8 {
1867 ItemType::ExternCrate => 0,
1868 ItemType::Import => 1,
1869 ItemType::Primitive => 2,
1870 ItemType::Module => 3,
1871 ItemType::Macro => 4,
1872 ItemType::Struct => 5,
1873 ItemType::Enum => 6,
1874 ItemType::Constant => 7,
1875 ItemType::Static => 8,
1876 ItemType::Trait => 9,
1877 ItemType::Function => 10,
1878 ItemType::Typedef => 12,
1879 ItemType::Union => 13,
1884 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1885 let ty1 = i1.type_();
1886 let ty2 = i2.type_();
1888 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1890 let s1 = i1.stability.as_ref().map(|s| s.level);
1891 let s2 = i2.stability.as_ref().map(|s| s.level);
1893 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1894 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1897 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1898 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1899 name_key(lhs).cmp(&name_key(rhs))
1902 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1903 // This call is to remove reexport duplicates in cases such as:
1908 // pub trait Double { fn foo(); }
1912 // pub use foo::bar::*;
1916 // `Double` will appear twice in the generated docs.
1918 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1919 // can be identical even if the elements are different (mostly in imports).
1920 // So in case this is an import, we keep everything by adding a "unique id"
1921 // (which is the position in the vector).
1922 indices.dedup_by_key(|i| (items[*i].def_id,
1923 if items[*i].name.as_ref().is_some() {
1924 Some(full_path(cx, &items[*i]).clone())
1929 if items[*i].is_import() {
1935 debug!("{:?}", indices);
1936 let mut curty = None;
1937 for &idx in &indices {
1938 let myitem = &items[idx];
1939 if myitem.is_stripped() {
1943 let myty = Some(myitem.type_());
1944 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1945 // Put `extern crate` and `use` re-exports in the same section.
1947 } else if myty != curty {
1948 if curty.is_some() {
1949 write!(w, "</table>")?;
1952 let (short, name) = match myty.unwrap() {
1953 ItemType::ExternCrate |
1954 ItemType::Import => ("reexports", "Reexports"),
1955 ItemType::Module => ("modules", "Modules"),
1956 ItemType::Struct => ("structs", "Structs"),
1957 ItemType::Union => ("unions", "Unions"),
1958 ItemType::Enum => ("enums", "Enums"),
1959 ItemType::Function => ("functions", "Functions"),
1960 ItemType::Typedef => ("types", "Type Definitions"),
1961 ItemType::Static => ("statics", "Statics"),
1962 ItemType::Constant => ("constants", "Constants"),
1963 ItemType::Trait => ("traits", "Traits"),
1964 ItemType::Impl => ("impls", "Implementations"),
1965 ItemType::TyMethod => ("tymethods", "Type Methods"),
1966 ItemType::Method => ("methods", "Methods"),
1967 ItemType::StructField => ("fields", "Struct Fields"),
1968 ItemType::Variant => ("variants", "Variants"),
1969 ItemType::Macro => ("macros", "Macros"),
1970 ItemType::Primitive => ("primitives", "Primitive Types"),
1971 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1972 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1974 write!(w, "<h2 id='{id}' class='section-header'>\
1975 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1976 id = derive_id(short.to_owned()), name = name)?;
1979 match myitem.inner {
1980 clean::ExternCrateItem(ref name, ref src) => {
1981 use html::format::HRef;
1985 write!(w, "<tr><td><code>{}extern crate {} as {};",
1986 VisSpace(&myitem.visibility),
1987 HRef::new(myitem.def_id, src),
1991 write!(w, "<tr><td><code>{}extern crate {};",
1992 VisSpace(&myitem.visibility),
1993 HRef::new(myitem.def_id, name))?
1996 write!(w, "</code></td></tr>")?;
1999 clean::ImportItem(ref import) => {
2000 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2001 VisSpace(&myitem.visibility), *import)?;
2005 if myitem.name.is_none() { continue }
2007 let stabilities = short_stability(myitem, cx, false);
2009 let stab_docs = if !stabilities.is_empty() {
2011 .map(|s| format!("[{}]", s))
2012 .collect::<Vec<_>>()
2019 let unsafety_flag = match myitem.inner {
2020 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2021 if func.unsafety == hir::Unsafety::Unsafe => {
2022 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2027 let doc_value = myitem.doc_value().unwrap_or("");
2029 <tr class='{stab} module-item'>
2030 <td><a class=\"{class}\" href=\"{href}\"
2031 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2032 <td class='docblock-short'>
2036 name = *myitem.name.as_ref().unwrap(),
2037 stab_docs = stab_docs,
2038 docs = if cx.render_type == RenderType::Hoedown {
2040 shorter(Some(&Markdown(doc_value,
2041 RenderType::Hoedown).to_string())))
2043 format!("{}", MarkdownSummaryLine(doc_value))
2045 class = myitem.type_(),
2046 stab = myitem.stability_class().unwrap_or("".to_string()),
2047 unsafety_flag = unsafety_flag,
2048 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2049 title_type = myitem.type_(),
2050 title = full_path(cx, myitem))?;
2055 if curty.is_some() {
2056 write!(w, "</table>")?;
2061 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2062 let mut stability = vec![];
2064 if let Some(stab) = item.stability.as_ref() {
2065 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2066 format!(": {}", stab.deprecated_reason)
2070 if !stab.deprecated_since.is_empty() {
2071 let since = if show_reason {
2072 format!(" since {}", Escape(&stab.deprecated_since))
2076 let text = format!("Deprecated{}{}",
2078 MarkdownHtml(&deprecated_reason, cx.render_type));
2079 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2082 if stab.level == stability::Unstable {
2084 let unstable_extra = match (!stab.feature.is_empty(),
2085 &cx.shared.issue_tracker_base_url,
2087 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2088 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2089 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2090 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2091 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2094 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2097 if stab.unstable_reason.is_empty() {
2098 stability.push(format!("<div class='stab unstable'>\
2099 <span class=microscope>🔬</span> \
2100 This is a nightly-only experimental API. {}\
2104 let text = format!("<summary><span class=microscope>🔬</span> \
2105 This is a nightly-only experimental API. {}\
2108 MarkdownHtml(&stab.unstable_reason, cx.render_type));
2109 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2113 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2116 } else if let Some(depr) = item.deprecation.as_ref() {
2117 let note = if show_reason && !depr.note.is_empty() {
2118 format!(": {}", depr.note)
2122 let since = if show_reason && !depr.since.is_empty() {
2123 format!(" since {}", Escape(&depr.since))
2128 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
2129 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2132 if let Some(ref cfg) = item.attrs.cfg {
2133 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2134 cfg.render_long_html()
2136 cfg.render_short_html()
2143 struct Initializer<'a>(&'a str);
2145 impl<'a> fmt::Display for Initializer<'a> {
2146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2147 let Initializer(s) = *self;
2148 if s.is_empty() { return Ok(()); }
2149 write!(f, "<code> = </code>")?;
2150 write!(f, "<code>{}</code>", Escape(s))
2154 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2155 c: &clean::Constant) -> fmt::Result {
2156 write!(w, "<pre class='rust const'>")?;
2157 render_attributes(w, it)?;
2158 write!(w, "{vis}const \
2159 {name}: {typ}{init}</pre>",
2160 vis = VisSpace(&it.visibility),
2161 name = it.name.as_ref().unwrap(),
2163 init = Initializer(&c.expr))?;
2167 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2168 s: &clean::Static) -> fmt::Result {
2169 write!(w, "<pre class='rust static'>")?;
2170 render_attributes(w, it)?;
2171 write!(w, "{vis}static {mutability}\
2172 {name}: {typ}{init}</pre>",
2173 vis = VisSpace(&it.visibility),
2174 mutability = MutableSpace(s.mutability),
2175 name = it.name.as_ref().unwrap(),
2177 init = Initializer(&s.expr))?;
2181 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2182 f: &clean::Function) -> fmt::Result {
2183 // FIXME(#24111): remove when `const_fn` is stabilized
2184 let vis_constness = match UnstableFeatures::from_environment() {
2185 UnstableFeatures::Allow => f.constness,
2186 _ => hir::Constness::NotConst
2188 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2189 VisSpace(&it.visibility),
2190 ConstnessSpace(vis_constness),
2191 UnsafetySpace(f.unsafety),
2193 it.name.as_ref().unwrap(),
2195 write!(w, "<pre class='rust fn'>")?;
2196 render_attributes(w, it)?;
2197 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2198 {name}{generics}{decl}{where_clause}</pre>",
2199 vis = VisSpace(&it.visibility),
2200 constness = ConstnessSpace(vis_constness),
2201 unsafety = UnsafetySpace(f.unsafety),
2202 abi = AbiSpace(f.abi),
2203 name = it.name.as_ref().unwrap(),
2204 generics = f.generics,
2205 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2214 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2215 t: &clean::Trait) -> fmt::Result {
2216 let mut bounds = String::new();
2217 let mut bounds_plain = String::new();
2218 if !t.bounds.is_empty() {
2219 if !bounds.is_empty() {
2221 bounds_plain.push(' ');
2223 bounds.push_str(": ");
2224 bounds_plain.push_str(": ");
2225 for (i, p) in t.bounds.iter().enumerate() {
2227 bounds.push_str(" + ");
2228 bounds_plain.push_str(" + ");
2230 bounds.push_str(&format!("{}", *p));
2231 bounds_plain.push_str(&format!("{:#}", *p));
2235 // Output the trait definition
2236 write!(w, "<pre class='rust trait'>")?;
2237 render_attributes(w, it)?;
2238 write!(w, "{}{}trait {}{}{}",
2239 VisSpace(&it.visibility),
2240 UnsafetySpace(t.unsafety),
2241 it.name.as_ref().unwrap(),
2245 if !t.generics.where_predicates.is_empty() {
2246 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2251 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2252 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2253 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2254 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2256 if t.items.is_empty() {
2257 write!(w, "{{ }}")?;
2259 // FIXME: we should be using a derived_id for the Anchors here
2263 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2266 if !types.is_empty() && !consts.is_empty() {
2271 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2274 if !consts.is_empty() && !required.is_empty() {
2277 for (pos, m) in required.iter().enumerate() {
2279 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2282 if pos < required.len() - 1 {
2283 write!(w, "<div class='item-spacer'></div>")?;
2286 if !required.is_empty() && !provided.is_empty() {
2289 for (pos, m) in provided.iter().enumerate() {
2291 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2293 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2294 write!(w, ",\n {{ ... }}\n")?;
2297 write!(w, " {{ ... }}\n")?;
2300 if pos < provided.len() - 1 {
2301 write!(w, "<div class='item-spacer'></div>")?;
2306 write!(w, "</pre>")?;
2308 // Trait documentation
2309 document(w, cx, it)?;
2311 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2313 let name = m.name.as_ref().unwrap();
2314 let item_type = m.type_();
2315 let id = derive_id(format!("{}.{}", item_type, name));
2316 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2317 write!(w, "<h3 id='{id}' class='method'>\
2318 <span id='{ns_id}' class='invisible'><code>",
2321 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2322 write!(w, "</code>")?;
2323 render_stability_since(w, m, t)?;
2324 write!(w, "</span></h3>")?;
2325 document(w, cx, m)?;
2329 if !types.is_empty() {
2331 <h2 id='associated-types' class='small-section-header'>
2332 Associated Types<a href='#associated-types' class='anchor'></a>
2334 <div class='methods'>
2337 trait_item(w, cx, *t, it)?;
2339 write!(w, "</div>")?;
2342 if !consts.is_empty() {
2344 <h2 id='associated-const' class='small-section-header'>
2345 Associated Constants<a href='#associated-const' class='anchor'></a>
2347 <div class='methods'>
2350 trait_item(w, cx, *t, it)?;
2352 write!(w, "</div>")?;
2355 // Output the documentation for each function individually
2356 if !required.is_empty() {
2358 <h2 id='required-methods' class='small-section-header'>
2359 Required Methods<a href='#required-methods' class='anchor'></a>
2361 <div class='methods'>
2363 for m in &required {
2364 trait_item(w, cx, *m, it)?;
2366 write!(w, "</div>")?;
2368 if !provided.is_empty() {
2370 <h2 id='provided-methods' class='small-section-header'>
2371 Provided Methods<a href='#provided-methods' class='anchor'></a>
2373 <div class='methods'>
2375 for m in &provided {
2376 trait_item(w, cx, *m, it)?;
2378 write!(w, "</div>")?;
2381 // If there are methods directly on this trait object, render them here.
2382 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2384 let cache = cache();
2386 <h2 id='implementors' class='small-section-header'>
2387 Implementors<a href='#implementors' class='anchor'></a>
2389 <ul class='item-list' id='implementors-list'>
2391 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2392 // The DefId is for the first Type found with that name. The bool is
2393 // if any Types with the same name but different DefId have been found.
2394 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2395 for implementor in implementors {
2396 match implementor.impl_.for_ {
2397 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2398 clean::BorrowedRef {
2399 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2402 let &mut (prev_did, ref mut has_duplicates) =
2403 implementor_dups.entry(path.last_name()).or_insert((did, false));
2404 if prev_did != did {
2405 *has_duplicates = true;
2412 for implementor in implementors {
2413 write!(w, "<li><code>")?;
2414 // If there's already another implementor that has the same abbridged name, use the
2415 // full path, for example in `std::iter::ExactSizeIterator`
2416 let use_absolute = match implementor.impl_.for_ {
2417 clean::ResolvedPath { ref path, is_generic: false, .. } |
2418 clean::BorrowedRef {
2419 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2421 } => implementor_dups[path.last_name()].1,
2424 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2425 for it in &implementor.impl_.items {
2426 if let clean::TypedefItem(ref tydef, _) = it.inner {
2427 write!(w, "<span class=\"where fmt-newline\"> ")?;
2428 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2429 write!(w, ";</span>")?;
2432 writeln!(w, "</code></li>")?;
2435 write!(w, "</ul>")?;
2436 write!(w, r#"<script type="text/javascript" async
2437 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2439 root_path = vec![".."; cx.current.len()].join("/"),
2440 path = if it.def_id.is_local() {
2441 cx.current.join("/")
2443 let (ref path, _) = cache.external_paths[&it.def_id];
2444 path[..path.len() - 1].join("/")
2446 ty = it.type_().css_class(),
2447 name = *it.name.as_ref().unwrap())?;
2451 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2452 use html::item_type::ItemType::*;
2454 let name = it.name.as_ref().unwrap();
2455 let ty = match it.type_() {
2456 Typedef | AssociatedType => AssociatedType,
2460 let anchor = format!("#{}.{}", ty, name);
2462 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2463 AssocItemLink::Anchor(None) => anchor,
2464 AssocItemLink::GotoSource(did, _) => {
2465 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2470 fn assoc_const(w: &mut fmt::Formatter,
2473 _default: Option<&String>,
2474 link: AssocItemLink) -> fmt::Result {
2475 write!(w, "const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2476 naive_assoc_href(it, link),
2477 it.name.as_ref().unwrap(),
2482 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2483 bounds: &Vec<clean::TyParamBound>,
2484 default: Option<&clean::Type>,
2485 link: AssocItemLink) -> fmt::Result {
2486 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2487 naive_assoc_href(it, link),
2488 it.name.as_ref().unwrap())?;
2489 if !bounds.is_empty() {
2490 write!(w, ": {}", TyParamBounds(bounds))?
2492 if let Some(default) = default {
2493 write!(w, " = {}", default)?;
2498 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2499 ver: Option<&'a str>,
2500 containing_ver: Option<&'a str>) -> fmt::Result {
2501 if let Some(v) = ver {
2502 if containing_ver != ver && v.len() > 0 {
2503 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2510 fn render_stability_since(w: &mut fmt::Formatter,
2512 containing_item: &clean::Item) -> fmt::Result {
2513 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2516 fn render_assoc_item(w: &mut fmt::Formatter,
2518 link: AssocItemLink,
2519 parent: ItemType) -> fmt::Result {
2520 fn method(w: &mut fmt::Formatter,
2522 unsafety: hir::Unsafety,
2523 constness: hir::Constness,
2525 g: &clean::Generics,
2527 link: AssocItemLink,
2530 let name = meth.name.as_ref().unwrap();
2531 let anchor = format!("#{}.{}", meth.type_(), name);
2532 let href = match link {
2533 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2534 AssocItemLink::Anchor(None) => anchor,
2535 AssocItemLink::GotoSource(did, provided_methods) => {
2536 // We're creating a link from an impl-item to the corresponding
2537 // trait-item and need to map the anchored type accordingly.
2538 let ty = if provided_methods.contains(name) {
2544 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2547 // FIXME(#24111): remove when `const_fn` is stabilized
2548 let vis_constness = if is_nightly_build() {
2551 hir::Constness::NotConst
2553 let mut head_len = format!("{}{}{:#}fn {}{:#}",
2554 ConstnessSpace(vis_constness),
2555 UnsafetySpace(unsafety),
2559 let (indent, end_newline) = if parent == ItemType::Trait {
2565 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2566 {generics}{decl}{where_clause}",
2567 ConstnessSpace(vis_constness),
2568 UnsafetySpace(unsafety),
2578 where_clause = WhereClause {
2585 clean::StrippedItem(..) => Ok(()),
2586 clean::TyMethodItem(ref m) => {
2587 method(w, item, m.unsafety, hir::Constness::NotConst,
2588 m.abi, &m.generics, &m.decl, link, parent)
2590 clean::MethodItem(ref m) => {
2591 method(w, item, m.unsafety, m.constness,
2592 m.abi, &m.generics, &m.decl, link, parent)
2594 clean::AssociatedConstItem(ref ty, ref default) => {
2595 assoc_const(w, item, ty, default.as_ref(), link)
2597 clean::AssociatedTypeItem(ref bounds, ref default) => {
2598 assoc_type(w, item, bounds, default.as_ref(), link)
2600 _ => panic!("render_assoc_item called on non-associated-item")
2604 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2605 s: &clean::Struct) -> fmt::Result {
2606 write!(w, "<pre class='rust struct'>")?;
2607 render_attributes(w, it)?;
2615 write!(w, "</pre>")?;
2617 document(w, cx, it)?;
2618 let mut fields = s.fields.iter().filter_map(|f| {
2620 clean::StructFieldItem(ref ty) => Some((f, ty)),
2624 if let doctree::Plain = s.struct_type {
2625 if fields.peek().is_some() {
2626 write!(w, "<h2 id='fields' class='fields small-section-header'>
2627 Fields<a href='#fields' class='anchor'></a></h2>")?;
2628 for (field, ty) in fields {
2629 let id = derive_id(format!("{}.{}",
2630 ItemType::StructField,
2631 field.name.as_ref().unwrap()));
2632 let ns_id = derive_id(format!("{}.{}",
2633 field.name.as_ref().unwrap(),
2634 ItemType::StructField.name_space()));
2635 write!(w, "<span id='{id}' class=\"{item_type}\">
2636 <span id='{ns_id}' class='invisible'>
2637 <code>{name}: {ty}</code>
2639 item_type = ItemType::StructField,
2642 name = field.name.as_ref().unwrap(),
2644 if let Some(stability_class) = field.stability_class() {
2645 write!(w, "<span class='stab {stab}'></span>",
2646 stab = stability_class)?;
2648 document(w, cx, field)?;
2652 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2655 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2656 s: &clean::Union) -> fmt::Result {
2657 write!(w, "<pre class='rust union'>")?;
2658 render_attributes(w, it)?;
2665 write!(w, "</pre>")?;
2667 document(w, cx, it)?;
2668 let mut fields = s.fields.iter().filter_map(|f| {
2670 clean::StructFieldItem(ref ty) => Some((f, ty)),
2674 if fields.peek().is_some() {
2675 write!(w, "<h2 id='fields' class='fields small-section-header'>
2676 Fields<a href='#fields' class='anchor'></a></h2>")?;
2677 for (field, ty) in fields {
2678 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2680 shortty = ItemType::StructField,
2681 name = field.name.as_ref().unwrap(),
2683 if let Some(stability_class) = field.stability_class() {
2684 write!(w, "<span class='stab {stab}'></span>",
2685 stab = stability_class)?;
2687 document(w, cx, field)?;
2690 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2693 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2694 e: &clean::Enum) -> fmt::Result {
2695 write!(w, "<pre class='rust enum'>")?;
2696 render_attributes(w, it)?;
2697 write!(w, "{}enum {}{}{}",
2698 VisSpace(&it.visibility),
2699 it.name.as_ref().unwrap(),
2701 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2702 if e.variants.is_empty() && !e.variants_stripped {
2703 write!(w, " {{}}")?;
2705 write!(w, " {{\n")?;
2706 for v in &e.variants {
2708 let name = v.name.as_ref().unwrap();
2710 clean::VariantItem(ref var) => {
2712 clean::VariantKind::CLike => write!(w, "{}", name)?,
2713 clean::VariantKind::Tuple(ref tys) => {
2714 write!(w, "{}(", name)?;
2715 for (i, ty) in tys.iter().enumerate() {
2717 write!(w, ", ")?
2719 write!(w, "{}", *ty)?;
2723 clean::VariantKind::Struct(ref s) => {
2739 if e.variants_stripped {
2740 write!(w, " // some variants omitted\n")?;
2744 write!(w, "</pre>")?;
2746 document(w, cx, it)?;
2747 if !e.variants.is_empty() {
2748 write!(w, "<h2 id='variants' class='variants small-section-header'>
2749 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2750 for variant in &e.variants {
2751 let id = derive_id(format!("{}.{}",
2753 variant.name.as_ref().unwrap()));
2754 let ns_id = derive_id(format!("{}.{}",
2755 variant.name.as_ref().unwrap(),
2756 ItemType::Variant.name_space()));
2757 write!(w, "<span id='{id}' class='variant'>\
2758 <span id='{ns_id}' class='invisible'><code>{name}",
2761 name = variant.name.as_ref().unwrap())?;
2762 if let clean::VariantItem(ref var) = variant.inner {
2763 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2765 for (i, ty) in tys.iter().enumerate() {
2767 write!(w, ", ")?;
2769 write!(w, "{}", *ty)?;
2774 write!(w, "</code></span></span>")?;
2775 document(w, cx, variant)?;
2777 use clean::{Variant, VariantKind};
2778 if let clean::VariantItem(Variant {
2779 kind: VariantKind::Struct(ref s)
2780 }) = variant.inner {
2781 let variant_id = derive_id(format!("{}.{}.fields",
2783 variant.name.as_ref().unwrap()));
2784 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2786 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2787 <table>", name = variant.name.as_ref().unwrap())?;
2788 for field in &s.fields {
2789 use clean::StructFieldItem;
2790 if let StructFieldItem(ref ty) = field.inner {
2791 let id = derive_id(format!("variant.{}.field.{}",
2792 variant.name.as_ref().unwrap(),
2793 field.name.as_ref().unwrap()));
2794 let ns_id = derive_id(format!("{}.{}.{}.{}",
2795 variant.name.as_ref().unwrap(),
2796 ItemType::Variant.name_space(),
2797 field.name.as_ref().unwrap(),
2798 ItemType::StructField.name_space()));
2799 write!(w, "<tr><td \
2801 <span id='{ns_id}' class='invisible'>\
2802 <code>{f}: {t}</code></span></td><td>",
2805 f = field.name.as_ref().unwrap(),
2807 document(w, cx, field)?;
2808 write!(w, "</td></tr>")?;
2811 write!(w, "</table></span>")?;
2813 render_stability_since(w, variant, it)?;
2816 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2820 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2821 let name = attr.name();
2824 Some(format!("{}", name))
2825 } else if let Some(v) = attr.value_str() {
2826 Some(format!("{} = {:?}", name, v.as_str()))
2827 } else if let Some(values) = attr.meta_item_list() {
2828 let display: Vec<_> = values.iter().filter_map(|attr| {
2829 attr.meta_item().and_then(|mi| render_attribute(mi))
2832 if display.len() > 0 {
2833 Some(format!("{}({})", name, display.join(", ")))
2842 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2849 "unsafe_destructor_blind_to_params"
2852 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2853 let mut attrs = String::new();
2855 for attr in &it.attrs.other_attrs {
2856 let name = attr.name().unwrap();
2857 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2860 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2861 attrs.push_str(&format!("#[{}]\n", s));
2864 if attrs.len() > 0 {
2865 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2870 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2871 g: Option<&clean::Generics>,
2872 ty: doctree::StructType,
2873 fields: &[clean::Item],
2875 structhead: bool) -> fmt::Result {
2877 VisSpace(&it.visibility),
2878 if structhead {"struct "} else {""},
2879 it.name.as_ref().unwrap())?;
2880 if let Some(g) = g {
2885 if let Some(g) = g {
2886 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2888 let mut has_visible_fields = false;
2890 for field in fields {
2891 if let clean::StructFieldItem(ref ty) = field.inner {
2892 write!(w, "\n{} {}{}: {},",
2894 VisSpace(&field.visibility),
2895 field.name.as_ref().unwrap(),
2897 has_visible_fields = true;
2901 if has_visible_fields {
2902 if it.has_stripped_fields().unwrap() {
2903 write!(w, "\n{} // some fields omitted", tab)?;
2905 write!(w, "\n{}", tab)?;
2906 } else if it.has_stripped_fields().unwrap() {
2907 // If there are no visible fields we can just display
2908 // `{ /* fields omitted */ }` to save space.
2909 write!(w, " /* fields omitted */ ")?;
2915 for (i, field) in fields.iter().enumerate() {
2920 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2923 clean::StructFieldItem(ref ty) => {
2924 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2930 if let Some(g) = g {
2931 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2936 // Needed for PhantomData.
2937 if let Some(g) = g {
2938 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2946 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2947 g: Option<&clean::Generics>,
2948 fields: &[clean::Item],
2950 structhead: bool) -> fmt::Result {
2952 VisSpace(&it.visibility),
2953 if structhead {"union "} else {""},
2954 it.name.as_ref().unwrap())?;
2955 if let Some(g) = g {
2956 write!(w, "{}", g)?;
2957 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
2960 write!(w, " {{\n{}", tab)?;
2961 for field in fields {
2962 if let clean::StructFieldItem(ref ty) = field.inner {
2963 write!(w, " {}{}: {},\n{}",
2964 VisSpace(&field.visibility),
2965 field.name.as_ref().unwrap(),
2971 if it.has_stripped_fields().unwrap() {
2972 write!(w, " // some fields omitted\n{}", tab)?;
2978 #[derive(Copy, Clone)]
2979 enum AssocItemLink<'a> {
2980 Anchor(Option<&'a str>),
2981 GotoSource(DefId, &'a FxHashSet<String>),
2984 impl<'a> AssocItemLink<'a> {
2985 fn anchor(&self, id: &'a String) -> Self {
2987 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2988 ref other => *other,
2993 enum AssocItemRender<'a> {
2995 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2998 #[derive(Copy, Clone, PartialEq)]
3001 ForDeref { mut_: bool },
3004 fn render_assoc_items(w: &mut fmt::Formatter,
3006 containing_item: &clean::Item,
3008 what: AssocItemRender) -> fmt::Result {
3010 let v = match c.impls.get(&it) {
3012 None => return Ok(()),
3014 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3015 i.inner_impl().trait_.is_none()
3017 if !non_trait.is_empty() {
3018 let render_mode = match what {
3019 AssocItemRender::All => {
3021 <h2 id='methods' class='small-section-header'>
3022 Methods<a href='#methods' class='anchor'></a>
3027 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3029 <h2 id='deref-methods' class='small-section-header'>
3030 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3033 RenderMode::ForDeref { mut_: deref_mut_ }
3036 for i in &non_trait {
3037 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3038 containing_item.stable_since())?;
3041 if let AssocItemRender::DerefFor { .. } = what {
3044 if !traits.is_empty() {
3045 let deref_impl = traits.iter().find(|t| {
3046 t.inner_impl().trait_.def_id() == c.deref_trait_did
3048 if let Some(impl_) = deref_impl {
3049 let has_deref_mut = traits.iter().find(|t| {
3050 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3052 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3055 <h2 id='implementations' class='small-section-header'>
3056 Trait Implementations<a href='#implementations' class='anchor'></a>
3060 let did = i.trait_did().unwrap();
3061 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3062 render_impl(w, cx, i, assoc_link,
3063 RenderMode::Normal, containing_item.stable_since())?;
3069 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3070 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3071 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3072 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3074 clean::TypedefItem(ref t, true) => Some(&t.type_),
3077 }).next().expect("Expected associated type binding");
3078 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3079 deref_mut_: deref_mut };
3080 if let Some(did) = target.def_id() {
3081 render_assoc_items(w, cx, container_item, did, what)
3083 if let Some(prim) = target.primitive_type() {
3084 if let Some(&did) = cache().primitive_locations.get(&prim) {
3085 render_assoc_items(w, cx, container_item, did, what)?;
3092 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3093 render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
3094 if render_mode == RenderMode::Normal {
3095 let id = derive_id(match i.inner_impl().trait_ {
3096 Some(ref t) => format!("impl-{}", Escape(&format!("{:#}", t))),
3097 None => "impl".to_string(),
3099 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3100 id, i.inner_impl())?;
3101 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3102 write!(w, "</span><span class='out-of-band'>")?;
3103 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3104 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3105 write!(w, "<div class='ghost'></div>")?;
3106 render_stability_since_raw(w, since, outer_version)?;
3107 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3108 l, "goto source code")?;
3110 render_stability_since_raw(w, since, outer_version)?;
3112 write!(w, "</span>")?;
3113 write!(w, "</h3>\n")?;
3114 if let Some(ref dox) = i.impl_item.doc_value() {
3115 write!(w, "<div class='docblock'>{}</div>", Markdown(dox, cx.render_type))?;
3119 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3120 link: AssocItemLink, render_mode: RenderMode,
3121 is_default_item: bool, outer_version: Option<&str>,
3122 trait_: Option<&clean::Trait>) -> fmt::Result {
3123 let item_type = item.type_();
3124 let name = item.name.as_ref().unwrap();
3126 let render_method_item: bool = match render_mode {
3127 RenderMode::Normal => true,
3128 RenderMode::ForDeref { mut_: deref_mut_ } => {
3129 let self_type_opt = match item.inner {
3130 clean::MethodItem(ref method) => method.decl.self_type(),
3131 clean::TyMethodItem(ref method) => method.decl.self_type(),
3135 if let Some(self_ty) = self_type_opt {
3136 let (by_mut_ref, by_box) = match self_ty {
3137 SelfTy::SelfBorrowed(_, mutability) |
3138 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3139 (mutability == Mutability::Mutable, false)
3141 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3142 (false, Some(did) == cache().owned_box_did)
3144 _ => (false, false),
3147 (deref_mut_ || !by_mut_ref) && !by_box
3155 clean::MethodItem(..) | clean::TyMethodItem(..) => {
3156 // Only render when the method is not static or we allow static methods
3157 if render_method_item {
3158 let id = derive_id(format!("{}.{}", item_type, name));
3159 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3160 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3161 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3162 write!(w, "<code>")?;
3163 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3164 write!(w, "</code>")?;
3165 if let Some(l) = (Item { cx, item }).src_href() {
3166 write!(w, "</span><span class='out-of-band'>")?;
3167 write!(w, "<div class='ghost'></div>")?;
3168 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3169 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3170 l, "goto source code")?;
3172 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3174 write!(w, "</span></h4>\n")?;
3177 clean::TypedefItem(ref tydef, _) => {
3178 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3179 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3180 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3181 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3182 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3183 write!(w, "</code></span></h4>\n")?;
3185 clean::AssociatedConstItem(ref ty, ref default) => {
3186 let id = derive_id(format!("{}.{}", item_type, name));
3187 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3188 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3189 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3190 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3191 write!(w, "</code></span></h4>\n")?;
3193 clean::AssociatedTypeItem(ref bounds, ref default) => {
3194 let id = derive_id(format!("{}.{}", item_type, name));
3195 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3196 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3197 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3198 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3199 write!(w, "</code></span></h4>\n")?;
3201 clean::StrippedItem(..) => return Ok(()),
3202 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3205 if render_method_item || render_mode == RenderMode::Normal {
3206 let prefix = render_assoc_const_value(item);
3207 if !is_default_item {
3208 if let Some(t) = trait_ {
3209 // The trait item may have been stripped so we might not
3210 // find any documentation or stability for it.
3211 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3212 // We need the stability of the item from the trait
3213 // because impls can't have a stability.
3214 document_stability(w, cx, it)?;
3215 if item.doc_value().is_some() {
3216 document_full(w, item, cx, &prefix)?;
3218 // In case the item isn't documented,
3219 // provide short documentation from the trait.
3220 document_short(w, it, link, cx, &prefix)?;
3224 document_stability(w, cx, item)?;
3225 document_full(w, item, cx, &prefix)?;
3228 document_stability(w, cx, item)?;
3229 document_short(w, item, link, cx, &prefix)?;
3235 let traits = &cache().traits;
3236 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3238 write!(w, "<div class='impl-items'>")?;
3239 for trait_item in &i.inner_impl().items {
3240 doc_impl_item(w, cx, trait_item, link, render_mode,
3241 false, outer_version, trait_)?;
3244 fn render_default_items(w: &mut fmt::Formatter,
3248 render_mode: RenderMode,
3249 outer_version: Option<&str>) -> fmt::Result {
3250 for trait_item in &t.items {
3251 let n = trait_item.name.clone();
3252 if i.items.iter().find(|m| m.name == n).is_some() {
3255 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3256 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3258 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3259 outer_version, None)?;
3264 // If we've implemented a trait, then also emit documentation for all
3265 // default items which weren't overridden in the implementation block.
3266 if let Some(t) = trait_ {
3267 render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
3269 write!(w, "</div>")?;
3273 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3274 t: &clean::Typedef) -> fmt::Result {
3275 write!(w, "<pre class='rust typedef'>")?;
3276 render_attributes(w, it)?;
3277 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3278 it.name.as_ref().unwrap(),
3280 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3283 document(w, cx, it)?;
3285 // Render any items associated directly to this alias, as otherwise they
3286 // won't be visible anywhere in the docs. It would be nice to also show
3287 // associated items from the aliased type (see discussion in #32077), but
3288 // we need #14072 to make sense of the generics.
3289 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3292 impl<'a> fmt::Display for Sidebar<'a> {
3293 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3296 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3298 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3299 || it.is_enum() || it.is_mod() || it.is_typedef()
3301 write!(fmt, "<p class='location'>")?;
3303 clean::StructItem(..) => write!(fmt, "Struct ")?,
3304 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3305 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3306 clean::UnionItem(..) => write!(fmt, "Union ")?,
3307 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3308 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3309 clean::ModuleItem(..) => if it.is_crate() {
3310 write!(fmt, "Crate ")?;
3312 write!(fmt, "Module ")?;
3316 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3317 write!(fmt, "</p>")?;
3320 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3321 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3322 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3323 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3324 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3325 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3326 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3331 // The sidebar is designed to display sibling functions, modules and
3332 // other miscellaneous information. since there are lots of sibling
3333 // items (and that causes quadratic growth in large modules),
3334 // we refactor common parts into a shared JavaScript file per module.
3335 // still, we don't move everything into JS because we want to preserve
3336 // as much HTML as possible in order to allow non-JS-enabled browsers
3337 // to navigate the documentation (though slightly inefficiently).
3339 write!(fmt, "<p class='location'>")?;
3340 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3342 write!(fmt, "::<wbr>")?;
3344 write!(fmt, "<a href='{}index.html'>{}</a>",
3345 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3348 write!(fmt, "</p>")?;
3350 // Sidebar refers to the enclosing module, not this module.
3351 let relpath = if it.is_mod() { "../" } else { "" };
3353 "<script>window.sidebarCurrent = {{\
3358 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3359 ty = it.type_().css_class(),
3362 // There is no sidebar-items.js beyond the crate root path
3363 // FIXME maybe dynamic crate loading can be merged here
3365 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3373 fn sidebar_assoc_items(it: &clean::Item) -> String {
3374 let mut out = String::new();
3376 if let Some(v) = c.impls.get(&it.def_id) {
3377 if v.iter().any(|i| i.inner_impl().trait_.is_none()) {
3378 out.push_str("<li><a href=\"#methods\">Methods</a></li>");
3381 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3382 if let Some(impl_) = v.iter()
3383 .filter(|i| i.inner_impl().trait_.is_some())
3384 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3385 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3387 clean::TypedefItem(ref t, true) => Some(&t.type_),
3391 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3392 c.primitive_locations.get(&prim).cloned()
3393 })).and_then(|did| c.impls.get(&did));
3394 if inner_impl.is_some() {
3395 out.push_str("<li><a href=\"#deref-methods\">");
3396 out.push_str(&format!("Methods from {:#}<Target={:#}>",
3397 impl_.inner_impl().trait_.as_ref().unwrap(),
3399 out.push_str("</a></li>");
3403 out.push_str("<li><a href=\"#implementations\">Trait Implementations</a></li>");
3410 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3411 s: &clean::Struct) -> fmt::Result {
3412 let mut sidebar = String::new();
3415 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3416 if let doctree::Plain = s.struct_type {
3417 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3421 sidebar.push_str(&sidebar_assoc_items(it));
3423 if !sidebar.is_empty() {
3424 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3429 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3430 t: &clean::Trait) -> fmt::Result {
3431 let mut sidebar = String::new();
3433 let has_types = t.items.iter().any(|m| m.is_associated_type());
3434 let has_consts = t.items.iter().any(|m| m.is_associated_const());
3435 let has_required = t.items.iter().any(|m| m.is_ty_method());
3436 let has_provided = t.items.iter().any(|m| m.is_method());
3439 sidebar.push_str("<li><a href=\"#associated-types\">Associated Types</a></li>");
3442 sidebar.push_str("<li><a href=\"#associated-const\">Associated Constants</a></li>");
3445 sidebar.push_str("<li><a href=\"#required-methods\">Required Methods</a></li>");
3448 sidebar.push_str("<li><a href=\"#provided-methods\">Provided Methods</a></li>");
3451 sidebar.push_str(&sidebar_assoc_items(it));
3453 sidebar.push_str("<li><a href=\"#implementors\">Implementors</a></li>");
3455 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)
3458 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3459 _p: &clean::PrimitiveType) -> fmt::Result {
3460 let sidebar = sidebar_assoc_items(it);
3462 if !sidebar.is_empty() {
3463 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3468 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3469 _t: &clean::Typedef) -> fmt::Result {
3470 let sidebar = sidebar_assoc_items(it);
3472 if !sidebar.is_empty() {
3473 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3478 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3479 u: &clean::Union) -> fmt::Result {
3480 let mut sidebar = String::new();
3483 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3484 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3487 sidebar.push_str(&sidebar_assoc_items(it));
3489 if !sidebar.is_empty() {
3490 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3495 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3496 e: &clean::Enum) -> fmt::Result {
3497 let mut sidebar = String::new();
3499 if !e.variants.is_empty() {
3500 sidebar.push_str("<li><a href=\"#variants\">Variants</a></li>");
3503 sidebar.push_str(&sidebar_assoc_items(it));
3505 if !sidebar.is_empty() {
3506 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3511 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3512 items: &[clean::Item]) -> fmt::Result {
3513 let mut sidebar = String::new();
3515 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3516 it.type_() == ItemType::Import) {
3517 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3519 name = "Reexports"));
3522 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3523 // to print its headings
3524 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3525 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3526 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3527 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3528 ItemType::AssociatedType, ItemType::AssociatedConst] {
3529 if items.iter().any(|it| {
3530 if let clean::DefaultImplItem(..) = it.inner {
3533 !it.is_stripped() && it.type_() == myty
3536 let (short, name) = match myty {
3537 ItemType::ExternCrate |
3538 ItemType::Import => ("reexports", "Reexports"),
3539 ItemType::Module => ("modules", "Modules"),
3540 ItemType::Struct => ("structs", "Structs"),
3541 ItemType::Union => ("unions", "Unions"),
3542 ItemType::Enum => ("enums", "Enums"),
3543 ItemType::Function => ("functions", "Functions"),
3544 ItemType::Typedef => ("types", "Type Definitions"),
3545 ItemType::Static => ("statics", "Statics"),
3546 ItemType::Constant => ("constants", "Constants"),
3547 ItemType::Trait => ("traits", "Traits"),
3548 ItemType::Impl => ("impls", "Implementations"),
3549 ItemType::TyMethod => ("tymethods", "Type Methods"),
3550 ItemType::Method => ("methods", "Methods"),
3551 ItemType::StructField => ("fields", "Struct Fields"),
3552 ItemType::Variant => ("variants", "Variants"),
3553 ItemType::Macro => ("macros", "Macros"),
3554 ItemType::Primitive => ("primitives", "Primitive Types"),
3555 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3556 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3558 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3564 if !sidebar.is_empty() {
3565 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3570 impl<'a> fmt::Display for Source<'a> {
3571 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3572 let Source(s) = *self;
3573 let lines = s.lines().count();
3575 let mut tmp = lines;
3580 write!(fmt, "<pre class=\"line-numbers\">")?;
3581 for i in 1..lines + 1 {
3582 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3584 write!(fmt, "</pre>")?;
3585 write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3590 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3591 t: &clean::Macro) -> fmt::Result {
3592 w.write_str(&highlight::render_with_highlighting(&t.source,
3599 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3601 _p: &clean::PrimitiveType) -> fmt::Result {
3602 document(w, cx, it)?;
3603 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3606 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3608 fn make_item_keywords(it: &clean::Item) -> String {
3609 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3612 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3613 let decl = match item.inner {
3614 clean::FunctionItem(ref f) => &f.decl,
3615 clean::MethodItem(ref m) => &m.decl,
3616 clean::TyMethodItem(ref m) => &m.decl,
3620 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3621 let output = match decl.output {
3622 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3626 Some(IndexItemFunctionType { inputs: inputs, output: output })
3629 fn get_index_type(clean_type: &clean::Type) -> Type {
3630 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3633 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3635 clean::ResolvedPath { ref path, .. } => {
3636 let segments = &path.segments;
3637 Some(segments[segments.len() - 1].name.clone())
3639 clean::Generic(ref s) => Some(s.clone()),
3640 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3641 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3642 // FIXME: add all from clean::Type.
3647 pub fn cache() -> Arc<Cache> {
3648 CACHE_KEY.with(|c| c.borrow().clone())
3653 fn test_unique_id() {
3654 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3655 "method.into_iter", "foo", "main", "search", "methods",
3656 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3657 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3658 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3659 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3662 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3663 assert_eq!(&actual[..], expected);
3672 fn test_name_key() {
3673 assert_eq!(name_key("0"), ("", 0, 1));
3674 assert_eq!(name_key("123"), ("", 123, 0));
3675 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
3676 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
3677 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
3678 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
3679 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
3680 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
3685 fn test_name_sorting() {
3686 let names = ["Apple",
3688 "Fruit", "Fruit0", "Fruit00",
3689 "Fruit1", "Fruit01",
3690 "Fruit2", "Fruit02",
3694 let mut sorted = names.to_owned();
3695 sorted.sort_by_key(|&s| name_key(s));
3696 assert_eq!(names, sorted);