1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
35 pub use self::ExternalLocation::*;
38 use std::ascii::AsciiExt;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, HashSet};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
45 use std::fs::{self, File, OpenOptions};
46 use std::io::prelude::*;
47 use std::io::{self, BufWriter, BufReader};
48 use std::iter::repeat;
50 use std::path::{PathBuf, Path, Component};
54 use externalfiles::ExternalHtml;
56 use serialize::json::{ToJson, Json, as_json};
57 use syntax::{abi, ast};
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability, Span};
68 use html::escape::Escape;
69 use html::format::{ConstnessSpace};
70 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
71 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
72 use html::format::fmt_impl_for_trait_page;
73 use html::item_type::ItemType;
74 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, RenderType};
75 use html::{highlight, layout};
79 /// A pair of name and its optional document.
80 pub type NameDoc = (String, Option<String>);
82 /// Major driving force in all rustdoc rendering. This contains information
83 /// about where in the tree-like hierarchy rendering is occurring and controls
84 /// how the current page is being rendered.
86 /// It is intended that this context is a lightweight object which can be fairly
87 /// easily cloned because it is cloned per work-job (about once per item in the
91 /// Current hierarchy of components leading down to what's currently being
93 pub current: Vec<String>,
94 /// The current destination folder of where HTML artifacts should be placed.
95 /// This changes as the context descends into the module hierarchy.
97 /// A flag, which when `true`, will render pages which redirect to the
98 /// real location of an item. This is used to allow external links to
99 /// publicly reused items to redirect to the right location.
100 pub render_redirect_pages: bool,
101 pub shared: Arc<SharedContext>,
102 pub render_type: RenderType,
105 pub struct SharedContext {
106 /// The path to the crate root source minus the file name.
107 /// Used for simplifying paths to the highlighted source code files.
108 pub src_root: PathBuf,
109 /// This describes the layout of each page, and is not modified after
110 /// creation of the context (contains info like the favicon and added html).
111 pub layout: layout::Layout,
112 /// This flag indicates whether [src] links should be generated or not. If
113 /// the source files are present in the html rendering, then this will be
115 pub include_sources: bool,
116 /// The local file sources we've emitted and their respective url-paths.
117 pub local_sources: FxHashMap<PathBuf, String>,
118 /// All the passes that were run on this crate.
119 pub passes: FxHashSet<String>,
120 /// The base-URL of the issue tracker for when an item has been tagged with
122 pub issue_tracker_base_url: Option<String>,
123 /// The given user css file which allow to customize the generated
124 /// documentation theme.
125 pub css_file_extension: Option<PathBuf>,
126 /// Warnings for the user if rendering would differ using different markdown
128 pub markdown_warnings: RefCell<Vec<(Span, String, Vec<html_diff::Difference>)>>,
129 /// The directories that have already been created in this doc run. Used to reduce the number
130 /// of spurious `create_dir_all` calls.
131 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
135 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
136 let mut dirs = self.created_dirs.borrow_mut();
137 if !dirs.contains(dst) {
138 fs::create_dir_all(dst)?;
139 dirs.insert(dst.to_path_buf());
146 /// Indicates where an external crate can be found.
147 pub enum ExternalLocation {
148 /// Remote URL root of the external crate
150 /// This external crate can be found in the local doc/ folder
152 /// The external crate could not be found.
156 /// Metadata about an implementor of a trait.
157 pub struct Implementor {
159 pub stability: Option<clean::Stability>,
160 pub impl_: clean::Impl,
163 /// Metadata about implementations for a type.
166 pub impl_item: clean::Item,
170 fn inner_impl(&self) -> &clean::Impl {
171 match self.impl_item.inner {
172 clean::ImplItem(ref impl_) => impl_,
173 _ => panic!("non-impl item found in impl")
177 fn trait_did(&self) -> Option<DefId> {
178 self.inner_impl().trait_.def_id()
188 impl error::Error for Error {
189 fn description(&self) -> &str {
190 self.error.description()
194 impl Display for Error {
195 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
196 write!(f, "\"{}\": {}", self.file.display(), self.error)
201 pub fn new(e: io::Error, file: &Path) -> Error {
203 file: file.to_path_buf(),
209 macro_rules! try_err {
210 ($e:expr, $file:expr) => ({
213 Err(e) => return Err(Error::new(e, $file)),
218 /// This cache is used to store information about the `clean::Crate` being
219 /// rendered in order to provide more useful documentation. This contains
220 /// information like all implementors of a trait, all traits a type implements,
221 /// documentation for all known traits, etc.
223 /// This structure purposefully does not implement `Clone` because it's intended
224 /// to be a fairly large and expensive structure to clone. Instead this adheres
225 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
226 /// rendering threads.
229 /// Mapping of typaram ids to the name of the type parameter. This is used
230 /// when pretty-printing a type (so pretty printing doesn't have to
231 /// painfully maintain a context like this)
232 pub typarams: FxHashMap<DefId, String>,
234 /// Maps a type id to all known implementations for that type. This is only
235 /// recognized for intra-crate `ResolvedPath` types, and is used to print
236 /// out extra documentation on the page of an enum/struct.
238 /// The values of the map are a list of implementations and documentation
239 /// found on that implementation.
240 pub impls: FxHashMap<DefId, Vec<Impl>>,
242 /// Maintains a mapping of local crate node ids to the fully qualified name
243 /// and "short type description" of that node. This is used when generating
244 /// URLs when a type is being linked to. External paths are not located in
245 /// this map because the `External` type itself has all the information
247 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
249 /// Similar to `paths`, but only holds external paths. This is only used for
250 /// generating explicit hyperlinks to other crates.
251 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
253 /// This map contains information about all known traits of this crate.
254 /// Implementations of a crate should inherit the documentation of the
255 /// parent trait if no extra documentation is specified, and default methods
256 /// should show up in documentation about trait implementations.
257 pub traits: FxHashMap<DefId, clean::Trait>,
259 /// When rendering traits, it's often useful to be able to list all
260 /// implementors of the trait, and this mapping is exactly, that: a mapping
261 /// of trait ids to the list of known implementors of the trait
262 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
264 /// Cache of where external crate documentation can be found.
265 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
267 /// Cache of where documentation for primitives can be found.
268 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
270 // Note that external items for which `doc(hidden)` applies to are shown as
271 // non-reachable while local items aren't. This is because we're reusing
272 // the access levels from crateanalysis.
273 pub access_levels: Arc<AccessLevels<DefId>>,
275 /// The version of the crate being documented, if given fron the `--crate-version` flag.
276 pub crate_version: Option<String>,
278 // Private fields only used when initially crawling a crate to build a cache
281 parent_stack: Vec<DefId>,
282 parent_is_trait_impl: bool,
283 search_index: Vec<IndexItem>,
285 deref_trait_did: Option<DefId>,
286 deref_mut_trait_did: Option<DefId>,
287 owned_box_did: Option<DefId>,
288 masked_crates: FxHashSet<CrateNum>,
290 // In rare case where a structure is defined in one module but implemented
291 // in another, if the implementing module is parsed before defining module,
292 // then the fully qualified name of the structure isn't presented in `paths`
293 // yet when its implementation methods are being indexed. Caches such methods
294 // and their parent id here and indexes them at the end of crate parsing.
295 orphan_impl_items: Vec<(DefId, clean::Item)>,
298 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
299 /// Later on moved into `CACHE_KEY`.
301 pub struct RenderInfo {
302 pub inlined: FxHashSet<DefId>,
303 pub external_paths: ::core::ExternalPaths,
304 pub external_typarams: FxHashMap<DefId, String>,
305 pub deref_trait_did: Option<DefId>,
306 pub deref_mut_trait_did: Option<DefId>,
307 pub owned_box_did: Option<DefId>,
310 /// Helper struct to render all source code to HTML pages
311 struct SourceCollector<'a> {
312 scx: &'a mut SharedContext,
314 /// Root destination to place all HTML output into
318 /// Wrapper struct to render the source code of a file. This will do things like
319 /// adding line numbers to the left-hand side.
320 struct Source<'a>(&'a str);
322 // Helper structs for rendering items/sidebars and carrying along contextual
325 #[derive(Copy, Clone)]
328 item: &'a clean::Item,
331 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
333 /// Struct representing one entry in the JS search index. These are all emitted
334 /// by hand to a large JS file at the end of cache-creation.
340 parent: Option<DefId>,
341 parent_idx: Option<usize>,
342 search_type: Option<IndexItemFunctionType>,
345 impl ToJson for IndexItem {
346 fn to_json(&self) -> Json {
347 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
349 let mut data = Vec::with_capacity(6);
350 data.push((self.ty as usize).to_json());
351 data.push(self.name.to_json());
352 data.push(self.path.to_json());
353 data.push(self.desc.to_json());
354 data.push(self.parent_idx.to_json());
355 data.push(self.search_type.to_json());
361 /// A type used for the search index.
363 name: Option<String>,
366 impl ToJson for Type {
367 fn to_json(&self) -> Json {
370 let mut data = BTreeMap::new();
371 data.insert("name".to_owned(), name.to_json());
379 /// Full type of functions/methods in the search index.
380 struct IndexItemFunctionType {
385 impl ToJson for IndexItemFunctionType {
386 fn to_json(&self) -> Json {
387 // If we couldn't figure out a type, just write `null`.
388 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
391 let mut data = BTreeMap::new();
392 data.insert("inputs".to_owned(), self.inputs.to_json());
393 data.insert("output".to_owned(), self.output.to_json());
399 // TLS keys used to carry information around during rendering.
401 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
402 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
403 RefCell::new(Vec::new()));
404 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
405 RefCell::new(init_ids()));
407 fn init_ids() -> FxHashMap<String, usize> {
423 ].into_iter().map(|id| (String::from(*id), 1)).collect()
426 /// This method resets the local table of used ID attributes. This is typically
427 /// used at the beginning of rendering an entire HTML page to reset from the
428 /// previous state (if any).
429 pub fn reset_ids(embedded: bool) {
430 USED_ID_MAP.with(|s| {
431 *s.borrow_mut() = if embedded {
439 pub fn derive_id(candidate: String) -> String {
440 USED_ID_MAP.with(|map| {
441 let id = match map.borrow_mut().get_mut(&candidate) {
444 let id = format!("{}-{}", candidate, *a);
450 map.borrow_mut().insert(id.clone(), 1);
455 /// Generates the documentation for `crate` into the directory `dst`
456 pub fn run(mut krate: clean::Crate,
457 external_html: &ExternalHtml,
458 playground_url: Option<String>,
460 passes: FxHashSet<String>,
461 css_file_extension: Option<PathBuf>,
462 renderinfo: RenderInfo,
463 render_type: RenderType) -> Result<(), Error> {
464 let src_root = match krate.src.parent() {
465 Some(p) => p.to_path_buf(),
466 None => PathBuf::new(),
468 let mut scx = SharedContext {
471 include_sources: true,
472 local_sources: FxHashMap(),
473 issue_tracker_base_url: None,
474 layout: layout::Layout {
475 logo: "".to_string(),
476 favicon: "".to_string(),
477 external_html: external_html.clone(),
478 krate: krate.name.clone(),
480 css_file_extension: css_file_extension.clone(),
481 markdown_warnings: RefCell::new(vec![]),
482 created_dirs: RefCell::new(FxHashSet()),
485 // If user passed in `--playground-url` arg, we fill in crate name here
486 if let Some(url) = playground_url {
487 markdown::PLAYGROUND.with(|slot| {
488 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
492 // Crawl the crate attributes looking for attributes which control how we're
493 // going to emit HTML
494 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
495 for attr in attrs.lists("doc") {
496 let name = attr.name().map(|s| s.as_str());
497 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
498 (Some("html_favicon_url"), Some(s)) => {
499 scx.layout.favicon = s.to_string();
501 (Some("html_logo_url"), Some(s)) => {
502 scx.layout.logo = s.to_string();
504 (Some("html_playground_url"), Some(s)) => {
505 markdown::PLAYGROUND.with(|slot| {
506 let name = krate.name.clone();
507 *slot.borrow_mut() = Some((Some(name), s.to_string()));
510 (Some("issue_tracker_base_url"), Some(s)) => {
511 scx.issue_tracker_base_url = Some(s.to_string());
513 (Some("html_no_source"), None) if attr.is_word() => {
514 scx.include_sources = false;
520 try_err!(fs::create_dir_all(&dst), &dst);
521 krate = render_sources(&dst, &mut scx, krate)?;
525 render_redirect_pages: false,
526 shared: Arc::new(scx),
530 // Crawl the crate to build various caches used for the output
540 let external_paths = external_paths.into_iter()
541 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
544 let mut cache = Cache {
548 implementors: FxHashMap(),
550 parent_stack: Vec::new(),
551 search_index: Vec::new(),
552 parent_is_trait_impl: false,
553 extern_locations: FxHashMap(),
554 primitive_locations: FxHashMap(),
556 access_levels: krate.access_levels.clone(),
557 crate_version: krate.version.take(),
558 orphan_impl_items: Vec::new(),
559 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
563 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
564 typarams: external_typarams,
567 // Cache where all our extern crates are located
568 for &(n, ref e) in &krate.externs {
569 let src_root = match Path::new(&e.src).parent() {
570 Some(p) => p.to_path_buf(),
571 None => PathBuf::new(),
573 cache.extern_locations.insert(n, (e.name.clone(), src_root,
574 extern_location(e, &cx.dst)));
576 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
577 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
580 // Cache where all known primitives have their documentation located.
582 // Favor linking to as local extern as possible, so iterate all crates in
583 // reverse topological order.
584 for &(_, ref e) in krate.externs.iter().rev() {
585 for &(def_id, prim, _) in &e.primitives {
586 cache.primitive_locations.insert(prim, def_id);
589 for &(def_id, prim, _) in &krate.primitives {
590 cache.primitive_locations.insert(prim, def_id);
593 cache.stack.push(krate.name.clone());
594 krate = cache.fold_crate(krate);
596 // Build our search index
597 let index = build_index(&krate, &mut cache);
599 // Freeze the cache now that the index has been built. Put an Arc into TLS
600 // for future parallelization opportunities
601 let cache = Arc::new(cache);
602 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
603 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
605 write_shared(&cx, &krate, &*cache, index)?;
607 let scx = cx.shared.clone();
609 // And finally render the whole crate's documentation
610 let result = cx.krate(krate);
612 let markdown_warnings = scx.markdown_warnings.borrow();
613 if !markdown_warnings.is_empty() {
614 let mut intro_msg = false;
615 for &(ref span, ref text, ref diffs) in &*markdown_warnings {
617 render_difference(d, &mut intro_msg, span, text);
625 // A short, single-line view of `s`.
626 fn concise_str(mut s: &str) -> String {
627 if s.contains('\n') {
628 s = s.lines().next().expect("Impossible! We just found a newline");
632 let mut hi = s.len() - 20;
633 while !s.is_char_boundary(lo) {
636 while !s.is_char_boundary(hi) {
639 return format!("{} ... {}", &s[..lo], &s[hi..]);
644 // Returns short versions of s1 and s2, starting from where the strings differ.
645 fn concise_compared_strs(s1: &str, s2: &str) -> (String, String) {
648 if !s1.contains('\n') && !s2.contains('\n') && s1.len() <= 70 && s2.len() <= 70 {
649 return (s1.to_owned(), s2.to_owned());
652 let mut start_byte = 0;
653 for (c1, c2) in s1.chars().zip(s2.chars()) {
658 start_byte += c1.len_utf8();
662 return (concise_str(s1), concise_str(s2));
665 let s1 = &s1[start_byte..];
666 let s2 = &s2[start_byte..];
667 (format!("...{}", concise_str(s1)), format!("...{}", concise_str(s2)))
671 fn print_message(msg: &str, intro_msg: &mut bool, span: &Span, text: &str) {
673 println!("WARNING: documentation for this crate may be rendered \
674 differently using the new Pulldown renderer.");
675 println!(" See https://github.com/rust-lang/rust/issues/44229 for details.");
678 println!("WARNING: rendering difference in `{}`", concise_str(text));
679 println!(" --> {}:{}:{}", span.filename, span.loline, span.locol);
683 fn render_difference(diff: &html_diff::Difference, intro_msg: &mut bool, span: &Span, text: &str) {
685 html_diff::Difference::NodeType { ref elem, ref opposite_elem } => {
686 print_message(&format!(" {} Types differ: expected: `{}`, found: `{}`",
687 elem.path, elem.element_name, opposite_elem.element_name),
688 intro_msg, span, text);
690 html_diff::Difference::NodeName { ref elem, ref opposite_elem } => {
691 print_message(&format!(" {} Tags differ: expected: `{}`, found: `{}`",
692 elem.path, elem.element_name, opposite_elem.element_name),
693 intro_msg, span, text);
695 html_diff::Difference::NodeAttributes { ref elem,
697 ref opposite_elem_attributes,
699 print_message(&format!(" {} Attributes differ in `{}`: expected: `{:?}`, \
701 elem.path, elem.element_name, elem_attributes,
702 opposite_elem_attributes),
703 intro_msg, span, text);
705 html_diff::Difference::NodeText { ref elem, ref elem_text, ref opposite_elem_text, .. } => {
706 if elem_text.split("\n")
707 .zip(opposite_elem_text.split("\n"))
708 .any(|(a, b)| a.trim() != b.trim()) {
709 let (s1, s2) = concise_compared_strs(elem_text, opposite_elem_text);
710 print_message(&format!(" {} Text differs:\n expected: `{}`\n \
713 intro_msg, span, text);
716 html_diff::Difference::NotPresent { ref elem, ref opposite_elem } => {
717 if let Some(ref elem) = *elem {
718 print_message(&format!(" {} One element is missing: expected: `{}`",
719 elem.path, elem.element_name),
720 intro_msg, span, text);
721 } else if let Some(ref elem) = *opposite_elem {
722 if elem.element_name.is_empty() {
723 print_message(&format!(" {} One element is missing: expected: `{}`",
724 elem.path, concise_str(&elem.element_content)),
725 intro_msg, span, text);
727 print_message(&format!(" {} Unexpected element `{}`: found: `{}`",
728 elem.path, elem.element_name,
729 concise_str(&elem.element_content)),
730 intro_msg, span, text);
737 /// Build the search index from the collected metadata
738 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
739 let mut nodeid_to_pathid = FxHashMap();
740 let mut crate_items = Vec::with_capacity(cache.search_index.len());
741 let mut crate_paths = Vec::<Json>::new();
743 let Cache { ref mut search_index,
744 ref orphan_impl_items,
745 ref mut paths, .. } = *cache;
747 // Attach all orphan items to the type's definition if the type
748 // has since been learned.
749 for &(did, ref item) in orphan_impl_items {
750 if let Some(&(ref fqp, _)) = paths.get(&did) {
751 search_index.push(IndexItem {
753 name: item.name.clone().unwrap(),
754 path: fqp[..fqp.len() - 1].join("::"),
755 desc: plain_summary_line(item.doc_value()),
758 search_type: get_index_search_type(&item),
763 // Reduce `NodeId` in paths into smaller sequential numbers,
764 // and prune the paths that do not appear in the index.
765 let mut lastpath = String::new();
766 let mut lastpathid = 0usize;
768 for item in search_index {
769 item.parent_idx = item.parent.map(|nodeid| {
770 if nodeid_to_pathid.contains_key(&nodeid) {
771 *nodeid_to_pathid.get(&nodeid).unwrap()
773 let pathid = lastpathid;
774 nodeid_to_pathid.insert(nodeid, pathid);
777 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
778 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
783 // Omit the parent path if it is same to that of the prior item.
784 if lastpath == item.path {
787 lastpath = item.path.clone();
789 crate_items.push(item.to_json());
792 let crate_doc = krate.module.as_ref().map(|module| {
793 plain_summary_line(module.doc_value())
794 }).unwrap_or(String::new());
796 let mut crate_data = BTreeMap::new();
797 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
798 crate_data.insert("items".to_owned(), Json::Array(crate_items));
799 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
801 // Collect the index into a string
802 format!("searchIndex[{}] = {};",
803 as_json(&krate.name),
804 Json::Object(crate_data))
807 fn write_shared(cx: &Context,
808 krate: &clean::Crate,
810 search_index: String) -> Result<(), Error> {
811 // Write out the shared files. Note that these are shared among all rustdoc
812 // docs placed in the output directory, so this needs to be a synchronized
813 // operation with respect to all other rustdocs running around.
814 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
816 // Add all the static files. These may already exist, but we just
817 // overwrite them anyway to make sure that they're fresh and up-to-date.
819 write(cx.dst.join("main.js"),
820 include_bytes!("static/main.js"))?;
821 write(cx.dst.join("rustdoc.css"),
822 include_bytes!("static/rustdoc.css"))?;
823 write(cx.dst.join("main.css"),
824 include_bytes!("static/styles/main.css"))?;
825 if let Some(ref css) = cx.shared.css_file_extension {
826 let mut content = String::new();
827 let css = css.as_path();
828 let mut f = try_err!(File::open(css), css);
830 try_err!(f.read_to_string(&mut content), css);
831 let css = cx.dst.join("theme.css");
832 let css = css.as_path();
833 let mut f = try_err!(File::create(css), css);
834 try_err!(write!(f, "{}", &content), css);
836 write(cx.dst.join("normalize.css"),
837 include_bytes!("static/normalize.css"))?;
838 write(cx.dst.join("FiraSans-Regular.woff"),
839 include_bytes!("static/FiraSans-Regular.woff"))?;
840 write(cx.dst.join("FiraSans-Medium.woff"),
841 include_bytes!("static/FiraSans-Medium.woff"))?;
842 write(cx.dst.join("FiraSans-LICENSE.txt"),
843 include_bytes!("static/FiraSans-LICENSE.txt"))?;
844 write(cx.dst.join("Heuristica-Italic.woff"),
845 include_bytes!("static/Heuristica-Italic.woff"))?;
846 write(cx.dst.join("Heuristica-LICENSE.txt"),
847 include_bytes!("static/Heuristica-LICENSE.txt"))?;
848 write(cx.dst.join("SourceSerifPro-Regular.woff"),
849 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
850 write(cx.dst.join("SourceSerifPro-Bold.woff"),
851 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
852 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
853 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
854 write(cx.dst.join("SourceCodePro-Regular.woff"),
855 include_bytes!("static/SourceCodePro-Regular.woff"))?;
856 write(cx.dst.join("SourceCodePro-Semibold.woff"),
857 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
858 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
859 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
860 write(cx.dst.join("LICENSE-MIT.txt"),
861 include_bytes!("static/LICENSE-MIT.txt"))?;
862 write(cx.dst.join("LICENSE-APACHE.txt"),
863 include_bytes!("static/LICENSE-APACHE.txt"))?;
864 write(cx.dst.join("COPYRIGHT.txt"),
865 include_bytes!("static/COPYRIGHT.txt"))?;
867 fn collect(path: &Path, krate: &str,
868 key: &str) -> io::Result<Vec<String>> {
869 let mut ret = Vec::new();
871 for line in BufReader::new(File::open(path)?).lines() {
873 if !line.starts_with(key) {
876 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
879 ret.push(line.to_string());
885 // Update the search index
886 let dst = cx.dst.join("search-index.js");
887 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
888 all_indexes.push(search_index);
889 // Sort the indexes by crate so the file will be generated identically even
890 // with rustdoc running in parallel.
892 let mut w = try_err!(File::create(&dst), &dst);
893 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
894 for index in &all_indexes {
895 try_err!(writeln!(&mut w, "{}", *index), &dst);
897 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
899 // Update the list of all implementors for traits
900 let dst = cx.dst.join("implementors");
901 for (&did, imps) in &cache.implementors {
902 // Private modules can leak through to this phase of rustdoc, which
903 // could contain implementations for otherwise private types. In some
904 // rare cases we could find an implementation for an item which wasn't
905 // indexed, so we just skip this step in that case.
907 // FIXME: this is a vague explanation for why this can't be a `get`, in
908 // theory it should be...
909 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
911 None => match cache.external_paths.get(&did) {
917 let mut have_impls = false;
918 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
920 // If the trait and implementation are in the same crate, then
921 // there's no need to emit information about it (there's inlining
922 // going on). If they're in different crates then the crate defining
923 // the trait will be interested in our implementation.
924 if imp.def_id.krate == did.krate { continue }
925 // If the implementation is from another crate then that crate
927 if !imp.def_id.is_local() { continue }
929 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
931 implementors.push_str("];");
933 // Only create a js file if we have impls to add to it. If the trait is
934 // documented locally though we always create the file to avoid dead
936 if !have_impls && !cache.paths.contains_key(&did) {
940 let mut mydst = dst.clone();
941 for part in &remote_path[..remote_path.len() - 1] {
944 try_err!(fs::create_dir_all(&mydst), &mydst);
945 mydst.push(&format!("{}.{}.js",
946 remote_item_type.css_class(),
947 remote_path[remote_path.len() - 1]));
949 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
950 all_implementors.push(implementors);
951 // Sort the implementors by crate so the file will be generated
952 // identically even with rustdoc running in parallel.
953 all_implementors.sort();
955 let mut f = try_err!(File::create(&mydst), &mydst);
956 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
957 for implementor in &all_implementors {
958 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
960 try_err!(writeln!(&mut f, "{}", r"
961 if (window.register_implementors) {
962 window.register_implementors(implementors);
964 window.pending_implementors = implementors;
967 try_err!(writeln!(&mut f, r"}})()"), &mydst);
972 fn render_sources(dst: &Path, scx: &mut SharedContext,
973 krate: clean::Crate) -> Result<clean::Crate, Error> {
974 info!("emitting source files");
975 let dst = dst.join("src").join(&krate.name);
976 try_err!(fs::create_dir_all(&dst), &dst);
977 let mut folder = SourceCollector {
981 Ok(folder.fold_crate(krate))
984 /// Writes the entire contents of a string to a destination, not attempting to
985 /// catch any errors.
986 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
987 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
990 /// Takes a path to a source file and cleans the path to it. This canonicalizes
991 /// things like ".." to components which preserve the "top down" hierarchy of a
992 /// static HTML tree. Each component in the cleaned path will be passed as an
993 /// argument to `f`. The very last component of the path (ie the file name) will
994 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
995 // FIXME (#9639): The closure should deal with &[u8] instead of &str
996 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
997 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1000 // make it relative, if possible
1001 let p = p.strip_prefix(src_root).unwrap_or(p);
1003 let mut iter = p.components().peekable();
1005 while let Some(c) = iter.next() {
1006 if !keep_filename && iter.peek().is_none() {
1011 Component::ParentDir => f("up"),
1012 Component::Normal(c) => f(c.to_str().unwrap()),
1018 /// Attempts to find where an external crate is located, given that we're
1019 /// rendering in to the specified source destination.
1020 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1021 // See if there's documentation generated into the local directory
1022 let local_location = dst.join(&e.name);
1023 if local_location.is_dir() {
1027 // Failing that, see if there's an attribute specifying where to find this
1029 e.attrs.lists("doc")
1030 .filter(|a| a.check_name("html_root_url"))
1031 .filter_map(|a| a.value_str())
1033 let mut url = url.to_string();
1034 if !url.ends_with("/") {
1038 }).next().unwrap_or(Unknown) // Well, at least we tried.
1041 impl<'a> DocFolder for SourceCollector<'a> {
1042 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1043 // If we're including source files, and we haven't seen this file yet,
1044 // then we need to render it out to the filesystem.
1045 if self.scx.include_sources
1046 // skip all invalid spans
1047 && item.source.filename != ""
1048 // skip non-local items
1049 && item.def_id.is_local()
1050 // Macros from other libraries get special filenames which we can
1052 && !(item.source.filename.starts_with("<")
1053 && item.source.filename.ends_with("macros>")) {
1055 // If it turns out that we couldn't read this file, then we probably
1056 // can't read any of the files (generating html output from json or
1057 // something like that), so just don't include sources for the
1058 // entire crate. The other option is maintaining this mapping on a
1059 // per-file basis, but that's probably not worth it...
1061 .include_sources = match self.emit_source(&item.source.filename) {
1064 println!("warning: source code was requested to be rendered, \
1065 but processing `{}` had an error: {}",
1066 item.source.filename, e);
1067 println!(" skipping rendering of source code");
1072 self.fold_item_recur(item)
1076 impl<'a> SourceCollector<'a> {
1077 /// Renders the given filename into its corresponding HTML source file.
1078 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
1079 let p = PathBuf::from(filename);
1080 if self.scx.local_sources.contains_key(&p) {
1081 // We've already emitted this source
1085 let mut contents = Vec::new();
1086 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
1088 let contents = str::from_utf8(&contents).unwrap();
1090 // Remove the utf-8 BOM if any
1091 let contents = if contents.starts_with("\u{feff}") {
1097 // Create the intermediate directories
1098 let mut cur = self.dst.clone();
1099 let mut root_path = String::from("../../");
1100 let mut href = String::new();
1101 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1102 cur.push(component);
1103 fs::create_dir_all(&cur).unwrap();
1104 root_path.push_str("../");
1105 href.push_str(component);
1108 let mut fname = p.file_name().expect("source has no filename")
1110 fname.push(".html");
1112 href.push_str(&fname.to_string_lossy());
1114 let mut w = BufWriter::new(File::create(&cur)?);
1115 let title = format!("{} -- source", cur.file_name().unwrap()
1116 .to_string_lossy());
1117 let desc = format!("Source to the Rust file `{}`.", filename);
1118 let page = layout::Page {
1120 css_class: "source",
1121 root_path: &root_path,
1123 keywords: BASIC_KEYWORDS,
1125 layout::render(&mut w, &self.scx.layout,
1126 &page, &(""), &Source(contents),
1127 self.scx.css_file_extension.is_some())?;
1129 self.scx.local_sources.insert(p, href);
1134 impl DocFolder for Cache {
1135 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1136 // If this is a stripped module,
1137 // we don't want it or its children in the search index.
1138 let orig_stripped_mod = match item.inner {
1139 clean::StrippedItem(box clean::ModuleItem(..)) => {
1140 mem::replace(&mut self.stripped_mod, true)
1142 _ => self.stripped_mod,
1145 // Register any generics to their corresponding string. This is used
1146 // when pretty-printing types.
1147 if let Some(generics) = item.inner.generics() {
1148 self.generics(generics);
1151 // Propagate a trait method's documentation to all implementors of the
1153 if let clean::TraitItem(ref t) = item.inner {
1154 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1157 // Collect all the implementors of traits.
1158 if let clean::ImplItem(ref i) = item.inner {
1159 if !self.masked_crates.contains(&item.def_id.krate) {
1160 if let Some(did) = i.trait_.def_id() {
1161 if i.for_.def_id().map_or(true, |d| !self.masked_crates.contains(&d.krate)) {
1162 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1163 def_id: item.def_id,
1164 stability: item.stability.clone(),
1172 // Index this method for searching later on.
1173 if let Some(ref s) = item.name {
1174 let (parent, is_inherent_impl_item) = match item.inner {
1175 clean::StrippedItem(..) => ((None, None), false),
1176 clean::AssociatedConstItem(..) |
1177 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1178 // skip associated items in trait impls
1179 ((None, None), false)
1181 clean::AssociatedTypeItem(..) |
1182 clean::TyMethodItem(..) |
1183 clean::StructFieldItem(..) |
1184 clean::VariantItem(..) => {
1185 ((Some(*self.parent_stack.last().unwrap()),
1186 Some(&self.stack[..self.stack.len() - 1])),
1189 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1190 if self.parent_stack.is_empty() {
1191 ((None, None), false)
1193 let last = self.parent_stack.last().unwrap();
1195 let path = match self.paths.get(&did) {
1196 // The current stack not necessarily has correlation
1197 // for where the type was defined. On the other
1198 // hand, `paths` always has the right
1199 // information if present.
1200 Some(&(ref fqp, ItemType::Trait)) |
1201 Some(&(ref fqp, ItemType::Struct)) |
1202 Some(&(ref fqp, ItemType::Union)) |
1203 Some(&(ref fqp, ItemType::Enum)) =>
1204 Some(&fqp[..fqp.len() - 1]),
1205 Some(..) => Some(&*self.stack),
1208 ((Some(*last), path), true)
1211 _ => ((None, Some(&*self.stack)), false)
1215 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1216 debug_assert!(!item.is_stripped());
1218 // A crate has a module at its root, containing all items,
1219 // which should not be indexed. The crate-item itself is
1220 // inserted later on when serializing the search-index.
1221 if item.def_id.index != CRATE_DEF_INDEX {
1222 self.search_index.push(IndexItem {
1224 name: s.to_string(),
1225 path: path.join("::").to_string(),
1226 desc: plain_summary_line(item.doc_value()),
1229 search_type: get_index_search_type(&item),
1233 (Some(parent), None) if is_inherent_impl_item => {
1234 // We have a parent, but we don't know where they're
1235 // defined yet. Wait for later to index this item.
1236 self.orphan_impl_items.push((parent, item.clone()));
1242 // Keep track of the fully qualified path for this item.
1243 let pushed = match item.name {
1244 Some(ref n) if !n.is_empty() => {
1245 self.stack.push(n.to_string());
1252 clean::StructItem(..) | clean::EnumItem(..) |
1253 clean::TypedefItem(..) | clean::TraitItem(..) |
1254 clean::FunctionItem(..) | clean::ModuleItem(..) |
1255 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1256 clean::ConstantItem(..) | clean::StaticItem(..) |
1257 clean::UnionItem(..)
1258 if !self.stripped_mod => {
1259 // Reexported items mean that the same id can show up twice
1260 // in the rustdoc ast that we're looking at. We know,
1261 // however, that a reexported item doesn't show up in the
1262 // `public_items` map, so we can skip inserting into the
1263 // paths map if there was already an entry present and we're
1264 // not a public item.
1266 !self.paths.contains_key(&item.def_id) ||
1267 self.access_levels.is_public(item.def_id)
1269 self.paths.insert(item.def_id,
1270 (self.stack.clone(), item.type_()));
1273 // Link variants to their parent enum because pages aren't emitted
1274 // for each variant.
1275 clean::VariantItem(..) if !self.stripped_mod => {
1276 let mut stack = self.stack.clone();
1278 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1281 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1282 self.paths.insert(item.def_id, (self.stack.clone(),
1289 // Maintain the parent stack
1290 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1291 let parent_pushed = match item.inner {
1292 clean::TraitItem(..) | clean::EnumItem(..) |
1293 clean::StructItem(..) | clean::UnionItem(..) => {
1294 self.parent_stack.push(item.def_id);
1295 self.parent_is_trait_impl = false;
1298 clean::ImplItem(ref i) => {
1299 self.parent_is_trait_impl = i.trait_.is_some();
1301 clean::ResolvedPath{ did, .. } => {
1302 self.parent_stack.push(did);
1306 let prim_did = t.primitive_type().and_then(|t| {
1307 self.primitive_locations.get(&t).cloned()
1311 self.parent_stack.push(did);
1322 // Once we've recursively found all the generics, hoard off all the
1323 // implementations elsewhere.
1324 let ret = self.fold_item_recur(item).and_then(|item| {
1325 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1326 // Figure out the id of this impl. This may map to a
1327 // primitive rather than always to a struct/enum.
1328 // Note: matching twice to restrict the lifetime of the `i` borrow.
1329 let mut dids = FxHashSet();
1330 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1331 let masked_trait = i.trait_.def_id().map_or(false,
1332 |d| self.masked_crates.contains(&d.krate));
1335 clean::ResolvedPath { did, .. } |
1336 clean::BorrowedRef {
1337 type_: box clean::ResolvedPath { did, .. }, ..
1342 let did = t.primitive_type().and_then(|t| {
1343 self.primitive_locations.get(&t).cloned()
1346 if let Some(did) = did {
1353 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1354 for bound in generics {
1355 if let Some(did) = bound.def_id() {
1364 self.impls.entry(did).or_insert(vec![]).push(Impl {
1365 impl_item: item.clone(),
1374 if pushed { self.stack.pop().unwrap(); }
1375 if parent_pushed { self.parent_stack.pop().unwrap(); }
1376 self.stripped_mod = orig_stripped_mod;
1377 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1383 fn generics(&mut self, generics: &clean::Generics) {
1384 for typ in &generics.type_params {
1385 self.typarams.insert(typ.did, typ.name.clone());
1391 /// String representation of how to get back to the root path of the 'doc/'
1392 /// folder in terms of a relative URL.
1393 fn root_path(&self) -> String {
1394 repeat("../").take(self.current.len()).collect::<String>()
1397 /// Recurse in the directory structure and change the "root path" to make
1398 /// sure it always points to the top (relatively).
1399 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1400 F: FnOnce(&mut Context) -> T,
1403 panic!("Unexpected empty destination: {:?}", self.current);
1405 let prev = self.dst.clone();
1407 self.current.push(s);
1409 info!("Recursing into {}", self.dst.display());
1413 info!("Recursed; leaving {}", self.dst.display());
1415 // Go back to where we were at
1417 self.current.pop().unwrap();
1422 /// Main method for rendering a crate.
1424 /// This currently isn't parallelized, but it'd be pretty easy to add
1425 /// parallelization to this function.
1426 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1427 let mut item = match krate.module.take() {
1429 None => return Ok(()),
1431 item.name = Some(krate.name);
1433 // Render the crate documentation
1434 let mut work = vec![(self, item)];
1436 while let Some((mut cx, item)) = work.pop() {
1437 cx.item(item, |cx, item| {
1438 work.push((cx.clone(), item))
1444 fn render_item(&self,
1445 writer: &mut io::Write,
1449 // A little unfortunate that this is done like this, but it sure
1450 // does make formatting *a lot* nicer.
1451 CURRENT_LOCATION_KEY.with(|slot| {
1452 *slot.borrow_mut() = self.current.clone();
1455 let mut title = if it.is_primitive() {
1456 // No need to include the namespace for primitive types
1459 self.current.join("::")
1462 if !title.is_empty() {
1463 title.push_str("::");
1465 title.push_str(it.name.as_ref().unwrap());
1467 title.push_str(" - Rust");
1468 let tyname = it.type_().css_class();
1469 let desc = if it.is_crate() {
1470 format!("API documentation for the Rust `{}` crate.",
1471 self.shared.layout.krate)
1473 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1474 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1476 let keywords = make_item_keywords(it);
1477 let page = layout::Page {
1479 root_path: &self.root_path(),
1482 keywords: &keywords,
1487 if !self.render_redirect_pages {
1488 layout::render(writer, &self.shared.layout, &page,
1489 &Sidebar{ cx: self, item: it },
1490 &Item{ cx: self, item: it },
1491 self.shared.css_file_extension.is_some())?;
1493 let mut url = self.root_path();
1494 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1495 for name in &names[..names.len() - 1] {
1499 url.push_str(&item_path(ty, names.last().unwrap()));
1500 layout::redirect(writer, &url)?;
1506 /// Non-parallelized version of rendering an item. This will take the input
1507 /// item, render its contents, and then invoke the specified closure with
1508 /// all sub-items which need to be rendered.
1510 /// The rendering driver uses this closure to queue up more work.
1511 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1512 F: FnMut(&mut Context, clean::Item),
1514 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1515 // if they contain impls for public types. These modules can also
1516 // contain items such as publicly reexported structures.
1518 // External crates will provide links to these structures, so
1519 // these modules are recursed into, but not rendered normally
1520 // (a flag on the context).
1521 if !self.render_redirect_pages {
1522 self.render_redirect_pages = item.is_stripped();
1526 // modules are special because they add a namespace. We also need to
1527 // recurse into the items of the module as well.
1528 let name = item.name.as_ref().unwrap().to_string();
1529 let mut item = Some(item);
1530 self.recurse(name, |this| {
1531 let item = item.take().unwrap();
1533 let mut buf = Vec::new();
1534 this.render_item(&mut buf, &item, false).unwrap();
1535 // buf will be empty if the module is stripped and there is no redirect for it
1536 if !buf.is_empty() {
1537 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1538 let joint_dst = this.dst.join("index.html");
1539 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1540 try_err!(dst.write_all(&buf), &joint_dst);
1543 let m = match item.inner {
1544 clean::StrippedItem(box clean::ModuleItem(m)) |
1545 clean::ModuleItem(m) => m,
1549 // Render sidebar-items.js used throughout this module.
1550 if !this.render_redirect_pages {
1551 let items = this.build_sidebar_items(&m);
1552 let js_dst = this.dst.join("sidebar-items.js");
1553 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1554 try_err!(write!(&mut js_out, "initSidebarItems({});",
1555 as_json(&items)), &js_dst);
1558 for item in m.items {
1564 } else if item.name.is_some() {
1565 let mut buf = Vec::new();
1566 self.render_item(&mut buf, &item, true).unwrap();
1567 // buf will be empty if the item is stripped and there is no redirect for it
1568 if !buf.is_empty() {
1569 let name = item.name.as_ref().unwrap();
1570 let item_type = item.type_();
1571 let file_name = &item_path(item_type, name);
1572 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1573 let joint_dst = self.dst.join(file_name);
1574 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1575 try_err!(dst.write_all(&buf), &joint_dst);
1577 // Redirect from a sane URL using the namespace to Rustdoc's
1578 // URL for the page.
1579 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1580 let redir_dst = self.dst.join(redir_name);
1581 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1584 let mut redirect_out = BufWriter::new(redirect_out);
1585 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1588 // If the item is a macro, redirect from the old macro URL (with !)
1589 // to the new one (without).
1590 // FIXME(#35705) remove this redirect.
1591 if item_type == ItemType::Macro {
1592 let redir_name = format!("{}.{}!.html", item_type, name);
1593 let redir_dst = self.dst.join(redir_name);
1594 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1595 let mut redirect_out = BufWriter::new(redirect_out);
1596 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1603 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1604 // BTreeMap instead of HashMap to get a sorted output
1605 let mut map = BTreeMap::new();
1606 for item in &m.items {
1607 if item.is_stripped() { continue }
1609 let short = item.type_().css_class();
1610 let myname = match item.name {
1612 Some(ref s) => s.to_string(),
1614 let short = short.to_string();
1615 map.entry(short).or_insert(vec![])
1616 .push((myname, Some(plain_summary_line(item.doc_value()))));
1619 for (_, items) in &mut map {
1627 /// Generate a url appropriate for an `href` attribute back to the source of
1630 /// The url generated, when clicked, will redirect the browser back to the
1631 /// original source code.
1633 /// If `None` is returned, then a source link couldn't be generated. This
1634 /// may happen, for example, with externally inlined items where the source
1635 /// of their crate documentation isn't known.
1636 fn src_href(&self) -> Option<String> {
1637 let mut root = self.cx.root_path();
1639 let cache = cache();
1640 let mut path = String::new();
1641 let (krate, path) = if self.item.def_id.is_local() {
1642 let path = PathBuf::from(&self.item.source.filename);
1643 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1644 (&self.cx.shared.layout.krate, path)
1649 // Macros from other libraries get special filenames which we can
1651 if self.item.source.filename.starts_with("<") &&
1652 self.item.source.filename.ends_with("macros>") {
1656 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1657 Some(&(ref name, ref src, Local)) => (name, src),
1658 Some(&(ref name, ref src, Remote(ref s))) => {
1659 root = s.to_string();
1662 Some(&(_, _, Unknown)) | None => return None,
1665 let file = Path::new(&self.item.source.filename);
1666 clean_srcpath(&src_root, file, false, |component| {
1667 path.push_str(component);
1670 let mut fname = file.file_name().expect("source has no filename")
1672 fname.push(".html");
1673 path.push_str(&fname.to_string_lossy());
1677 let lines = if self.item.source.loline == self.item.source.hiline {
1678 format!("{}", self.item.source.loline)
1680 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1682 Some(format!("{root}src/{krate}/{path}#{lines}",
1690 impl<'a> fmt::Display for Item<'a> {
1691 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1692 debug_assert!(!self.item.is_stripped());
1693 // Write the breadcrumb trail header for the top
1694 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1695 match self.item.inner {
1696 clean::ModuleItem(ref m) => if m.is_crate {
1697 write!(fmt, "Crate ")?;
1699 write!(fmt, "Module ")?;
1701 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1702 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1703 clean::StructItem(..) => write!(fmt, "Struct ")?,
1704 clean::UnionItem(..) => write!(fmt, "Union ")?,
1705 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1706 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1707 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1708 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1709 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1710 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1712 // We don't generate pages for any other type.
1716 if !self.item.is_primitive() {
1717 let cur = &self.cx.current;
1718 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1719 for (i, component) in cur.iter().enumerate().take(amt) {
1720 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1721 repeat("../").take(cur.len() - i - 1)
1722 .collect::<String>(),
1726 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1727 self.item.type_(), self.item.name.as_ref().unwrap())?;
1729 write!(fmt, "</span>")?; // in-band
1730 write!(fmt, "<span class='out-of-band'>")?;
1731 if let Some(version) = self.item.stable_since() {
1732 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1736 r##"<span id='render-detail'>
1737 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1738 [<span class='inner'>−</span>]
1744 // When this item is part of a `pub use` in a downstream crate, the
1745 // [src] link in the downstream documentation will actually come back to
1746 // this page, and this link will be auto-clicked. The `id` attribute is
1747 // used to find the link to auto-click.
1748 if self.cx.shared.include_sources && !self.item.is_primitive() {
1749 if let Some(l) = self.src_href() {
1750 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1751 l, "goto source code")?;
1755 write!(fmt, "</span>")?; // out-of-band
1757 write!(fmt, "</h1>\n")?;
1759 match self.item.inner {
1760 clean::ModuleItem(ref m) => {
1761 item_module(fmt, self.cx, self.item, &m.items)
1763 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1764 item_function(fmt, self.cx, self.item, f),
1765 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1766 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1767 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1768 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1769 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1770 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1771 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1772 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1773 item_static(fmt, self.cx, self.item, i),
1774 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1776 // We don't generate pages for any other type.
1783 fn item_path(ty: ItemType, name: &str) -> String {
1785 ItemType::Module => format!("{}/index.html", name),
1786 _ => format!("{}.{}.html", ty.css_class(), name),
1790 fn full_path(cx: &Context, item: &clean::Item) -> String {
1791 let mut s = cx.current.join("::");
1793 s.push_str(item.name.as_ref().unwrap());
1797 fn shorter<'a>(s: Option<&'a str>) -> String {
1799 Some(s) => s.lines().take_while(|line|{
1800 (*line).chars().any(|chr|{
1801 !chr.is_whitespace()
1803 }).collect::<Vec<_>>().join("\n"),
1804 None => "".to_string()
1809 fn plain_summary_line(s: Option<&str>) -> String {
1810 let line = shorter(s).replace("\n", " ");
1811 markdown::plain_summary_line(&line[..])
1814 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1815 document_stability(w, cx, item)?;
1816 let prefix = render_assoc_const_value(item);
1817 document_full(w, item, cx, &prefix)?;
1821 /// Render md_text as markdown. Warns the user if there are difference in
1822 /// rendering between Pulldown and Hoedown.
1823 fn render_markdown(w: &mut fmt::Formatter,
1826 render_type: RenderType,
1828 scx: &SharedContext)
1830 // Save the state of USED_ID_MAP so it only gets updated once even
1831 // though we're rendering twice.
1832 let orig_used_id_map = USED_ID_MAP.with(|map| map.borrow().clone());
1833 let hoedown_output = format!("{}", Markdown(md_text, RenderType::Hoedown));
1834 USED_ID_MAP.with(|map| *map.borrow_mut() = orig_used_id_map);
1835 let pulldown_output = format!("{}", Markdown(md_text, RenderType::Pulldown));
1836 let mut differences = html_diff::get_differences(&pulldown_output, &hoedown_output);
1837 differences.retain(|s| {
1839 html_diff::Difference::NodeText { ref elem_text,
1840 ref opposite_elem_text,
1842 if elem_text.split_whitespace().eq(opposite_elem_text.split_whitespace()) => {
1849 if !differences.is_empty() {
1850 scx.markdown_warnings.borrow_mut().push((span, md_text.to_owned(), differences));
1853 write!(w, "<div class='docblock'>{}{}</div>",
1855 if render_type == RenderType::Pulldown { pulldown_output } else { hoedown_output })
1858 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1859 cx: &Context, prefix: &str) -> fmt::Result {
1860 if let Some(s) = item.doc_value() {
1861 let markdown = if s.contains('\n') {
1862 format!("{} [Read more]({})",
1863 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1865 format!("{}", &plain_summary_line(Some(s)))
1867 render_markdown(w, &markdown, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1868 } else if !prefix.is_empty() {
1869 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1874 fn render_assoc_const_value(item: &clean::Item) -> String {
1876 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1877 highlight::render_with_highlighting(
1878 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1889 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1890 cx: &Context, prefix: &str) -> fmt::Result {
1891 if let Some(s) = item.doc_value() {
1892 render_markdown(w, s, item.source.clone(), cx.render_type, prefix, &cx.shared)?;
1893 } else if !prefix.is_empty() {
1894 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1899 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1900 let stabilities = short_stability(item, cx, true);
1901 if !stabilities.is_empty() {
1902 write!(w, "<div class='stability'>")?;
1903 for stability in stabilities {
1904 write!(w, "{}", stability)?;
1906 write!(w, "</div>")?;
1911 fn name_key(name: &str) -> (&str, u64, usize) {
1912 // find number at end
1913 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1915 // count leading zeroes
1917 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1919 // sort leading zeroes last
1920 let num_zeroes = after_zeroes - split;
1922 match name[split..].parse() {
1923 Ok(n) => (&name[..split], n, num_zeroes),
1924 Err(_) => (name, 0, num_zeroes),
1928 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1929 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1930 document(w, cx, item)?;
1932 let mut indices = (0..items.len()).filter(|i| {
1933 if let clean::AutoImplItem(..) = items[*i].inner {
1936 !items[*i].is_stripped()
1937 }).collect::<Vec<usize>>();
1939 // the order of item types in the listing
1940 fn reorder(ty: ItemType) -> u8 {
1942 ItemType::ExternCrate => 0,
1943 ItemType::Import => 1,
1944 ItemType::Primitive => 2,
1945 ItemType::Module => 3,
1946 ItemType::Macro => 4,
1947 ItemType::Struct => 5,
1948 ItemType::Enum => 6,
1949 ItemType::Constant => 7,
1950 ItemType::Static => 8,
1951 ItemType::Trait => 9,
1952 ItemType::Function => 10,
1953 ItemType::Typedef => 12,
1954 ItemType::Union => 13,
1959 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1960 let ty1 = i1.type_();
1961 let ty2 = i2.type_();
1963 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1965 let s1 = i1.stability.as_ref().map(|s| s.level);
1966 let s2 = i2.stability.as_ref().map(|s| s.level);
1968 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1969 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1972 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1973 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1974 name_key(lhs).cmp(&name_key(rhs))
1977 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1978 // This call is to remove reexport duplicates in cases such as:
1983 // pub trait Double { fn foo(); }
1987 // pub use foo::bar::*;
1991 // `Double` will appear twice in the generated docs.
1993 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1994 // can be identical even if the elements are different (mostly in imports).
1995 // So in case this is an import, we keep everything by adding a "unique id"
1996 // (which is the position in the vector).
1997 indices.dedup_by_key(|i| (items[*i].def_id,
1998 if items[*i].name.as_ref().is_some() {
1999 Some(full_path(cx, &items[*i]).clone())
2004 if items[*i].is_import() {
2010 debug!("{:?}", indices);
2011 let mut curty = None;
2012 for &idx in &indices {
2013 let myitem = &items[idx];
2014 if myitem.is_stripped() {
2018 let myty = Some(myitem.type_());
2019 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2020 // Put `extern crate` and `use` re-exports in the same section.
2022 } else if myty != curty {
2023 if curty.is_some() {
2024 write!(w, "</table>")?;
2027 let (short, name) = match myty.unwrap() {
2028 ItemType::ExternCrate |
2029 ItemType::Import => ("reexports", "Reexports"),
2030 ItemType::Module => ("modules", "Modules"),
2031 ItemType::Struct => ("structs", "Structs"),
2032 ItemType::Union => ("unions", "Unions"),
2033 ItemType::Enum => ("enums", "Enums"),
2034 ItemType::Function => ("functions", "Functions"),
2035 ItemType::Typedef => ("types", "Type Definitions"),
2036 ItemType::Static => ("statics", "Statics"),
2037 ItemType::Constant => ("constants", "Constants"),
2038 ItemType::Trait => ("traits", "Traits"),
2039 ItemType::Impl => ("impls", "Implementations"),
2040 ItemType::TyMethod => ("tymethods", "Type Methods"),
2041 ItemType::Method => ("methods", "Methods"),
2042 ItemType::StructField => ("fields", "Struct Fields"),
2043 ItemType::Variant => ("variants", "Variants"),
2044 ItemType::Macro => ("macros", "Macros"),
2045 ItemType::Primitive => ("primitives", "Primitive Types"),
2046 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2047 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2048 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2050 write!(w, "<h2 id='{id}' class='section-header'>\
2051 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2052 id = derive_id(short.to_owned()), name = name)?;
2055 match myitem.inner {
2056 clean::ExternCrateItem(ref name, ref src) => {
2057 use html::format::HRef;
2061 write!(w, "<tr><td><code>{}extern crate {} as {};",
2062 VisSpace(&myitem.visibility),
2063 HRef::new(myitem.def_id, src),
2067 write!(w, "<tr><td><code>{}extern crate {};",
2068 VisSpace(&myitem.visibility),
2069 HRef::new(myitem.def_id, name))?
2072 write!(w, "</code></td></tr>")?;
2075 clean::ImportItem(ref import) => {
2076 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2077 VisSpace(&myitem.visibility), *import)?;
2081 if myitem.name.is_none() { continue }
2083 let stabilities = short_stability(myitem, cx, false);
2085 let stab_docs = if !stabilities.is_empty() {
2087 .map(|s| format!("[{}]", s))
2088 .collect::<Vec<_>>()
2095 let unsafety_flag = match myitem.inner {
2096 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2097 if func.unsafety == hir::Unsafety::Unsafe => {
2098 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2103 let doc_value = myitem.doc_value().unwrap_or("");
2105 <tr class='{stab} module-item'>
2106 <td><a class=\"{class}\" href=\"{href}\"
2107 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2108 <td class='docblock-short'>
2112 name = *myitem.name.as_ref().unwrap(),
2113 stab_docs = stab_docs,
2114 docs = if cx.render_type == RenderType::Hoedown {
2116 shorter(Some(&Markdown(doc_value,
2117 RenderType::Hoedown).to_string())))
2119 format!("{}", MarkdownSummaryLine(doc_value))
2121 class = myitem.type_(),
2122 stab = myitem.stability_class().unwrap_or("".to_string()),
2123 unsafety_flag = unsafety_flag,
2124 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2125 title_type = myitem.type_(),
2126 title = full_path(cx, myitem))?;
2131 if curty.is_some() {
2132 write!(w, "</table>")?;
2137 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2138 let mut stability = vec![];
2140 if let Some(stab) = item.stability.as_ref() {
2141 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2142 format!(": {}", stab.deprecated_reason)
2146 if !stab.deprecated_since.is_empty() {
2147 let since = if show_reason {
2148 format!(" since {}", Escape(&stab.deprecated_since))
2152 let text = format!("Deprecated{}{}",
2154 MarkdownHtml(&deprecated_reason, cx.render_type));
2155 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2158 if stab.level == stability::Unstable {
2160 let unstable_extra = match (!stab.feature.is_empty(),
2161 &cx.shared.issue_tracker_base_url,
2163 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2164 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2165 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2166 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2167 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2170 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2173 if stab.unstable_reason.is_empty() {
2174 stability.push(format!("<div class='stab unstable'>\
2175 <span class=microscope>🔬</span> \
2176 This is a nightly-only experimental API. {}\
2180 let text = format!("<summary><span class=microscope>🔬</span> \
2181 This is a nightly-only experimental API. {}\
2184 MarkdownHtml(&stab.unstable_reason, cx.render_type));
2185 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2189 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2192 } else if let Some(depr) = item.deprecation.as_ref() {
2193 let note = if show_reason && !depr.note.is_empty() {
2194 format!(": {}", depr.note)
2198 let since = if show_reason && !depr.since.is_empty() {
2199 format!(" since {}", Escape(&depr.since))
2204 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
2205 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2208 if let Some(ref cfg) = item.attrs.cfg {
2209 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2210 cfg.render_long_html()
2212 cfg.render_short_html()
2219 struct Initializer<'a>(&'a str);
2221 impl<'a> fmt::Display for Initializer<'a> {
2222 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2223 let Initializer(s) = *self;
2224 if s.is_empty() { return Ok(()); }
2225 write!(f, "<code> = </code>")?;
2226 write!(f, "<code>{}</code>", Escape(s))
2230 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2231 c: &clean::Constant) -> fmt::Result {
2232 write!(w, "<pre class='rust const'>")?;
2233 render_attributes(w, it)?;
2234 write!(w, "{vis}const \
2235 {name}: {typ}{init}</pre>",
2236 vis = VisSpace(&it.visibility),
2237 name = it.name.as_ref().unwrap(),
2239 init = Initializer(&c.expr))?;
2243 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2244 s: &clean::Static) -> fmt::Result {
2245 write!(w, "<pre class='rust static'>")?;
2246 render_attributes(w, it)?;
2247 write!(w, "{vis}static {mutability}\
2248 {name}: {typ}{init}</pre>",
2249 vis = VisSpace(&it.visibility),
2250 mutability = MutableSpace(s.mutability),
2251 name = it.name.as_ref().unwrap(),
2253 init = Initializer(&s.expr))?;
2257 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2258 f: &clean::Function) -> fmt::Result {
2259 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2260 VisSpace(&it.visibility),
2261 ConstnessSpace(f.constness),
2262 UnsafetySpace(f.unsafety),
2264 it.name.as_ref().unwrap(),
2266 write!(w, "<pre class='rust fn'>")?;
2267 render_attributes(w, it)?;
2268 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2269 {name}{generics}{decl}{where_clause}</pre>",
2270 vis = VisSpace(&it.visibility),
2271 constness = ConstnessSpace(f.constness),
2272 unsafety = UnsafetySpace(f.unsafety),
2273 abi = AbiSpace(f.abi),
2274 name = it.name.as_ref().unwrap(),
2275 generics = f.generics,
2276 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2285 fn implementor2item<'a>(cache: &'a Cache, imp : &Implementor) -> Option<&'a clean::Item> {
2286 if let Some(t_did) = imp.impl_.for_.def_id() {
2287 if let Some(impl_item) = cache.impls.get(&t_did).and_then(|i| i.iter()
2288 .find(|i| i.impl_item.def_id == imp.def_id))
2290 let i = &impl_item.impl_item;
2297 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2298 t: &clean::Trait) -> fmt::Result {
2299 let mut bounds = String::new();
2300 let mut bounds_plain = String::new();
2301 if !t.bounds.is_empty() {
2302 if !bounds.is_empty() {
2304 bounds_plain.push(' ');
2306 bounds.push_str(": ");
2307 bounds_plain.push_str(": ");
2308 for (i, p) in t.bounds.iter().enumerate() {
2310 bounds.push_str(" + ");
2311 bounds_plain.push_str(" + ");
2313 bounds.push_str(&format!("{}", *p));
2314 bounds_plain.push_str(&format!("{:#}", *p));
2318 // Output the trait definition
2319 write!(w, "<pre class='rust trait'>")?;
2320 render_attributes(w, it)?;
2321 write!(w, "{}{}trait {}{}{}",
2322 VisSpace(&it.visibility),
2323 UnsafetySpace(t.unsafety),
2324 it.name.as_ref().unwrap(),
2328 if !t.generics.where_predicates.is_empty() {
2329 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2334 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2335 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2336 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2337 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2339 if t.items.is_empty() {
2340 write!(w, "{{ }}")?;
2342 // FIXME: we should be using a derived_id for the Anchors here
2346 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2349 if !types.is_empty() && !consts.is_empty() {
2354 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2357 if !consts.is_empty() && !required.is_empty() {
2360 for (pos, m) in required.iter().enumerate() {
2362 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2365 if pos < required.len() - 1 {
2366 write!(w, "<div class='item-spacer'></div>")?;
2369 if !required.is_empty() && !provided.is_empty() {
2372 for (pos, m) in provided.iter().enumerate() {
2374 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2376 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2377 write!(w, ",\n {{ ... }}\n")?;
2380 write!(w, " {{ ... }}\n")?;
2383 if pos < provided.len() - 1 {
2384 write!(w, "<div class='item-spacer'></div>")?;
2389 write!(w, "</pre>")?;
2391 // Trait documentation
2392 document(w, cx, it)?;
2394 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2396 let name = m.name.as_ref().unwrap();
2397 let item_type = m.type_();
2398 let id = derive_id(format!("{}.{}", item_type, name));
2399 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2400 write!(w, "<h3 id='{id}' class='method'>\
2401 <span id='{ns_id}' class='invisible'><code>",
2404 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2405 write!(w, "</code>")?;
2406 render_stability_since(w, m, t)?;
2407 write!(w, "</span></h3>")?;
2408 document(w, cx, m)?;
2412 if !types.is_empty() {
2414 <h2 id='associated-types' class='small-section-header'>
2415 Associated Types<a href='#associated-types' class='anchor'></a>
2417 <div class='methods'>
2420 trait_item(w, cx, *t, it)?;
2422 write!(w, "</div>")?;
2425 if !consts.is_empty() {
2427 <h2 id='associated-const' class='small-section-header'>
2428 Associated Constants<a href='#associated-const' class='anchor'></a>
2430 <div class='methods'>
2433 trait_item(w, cx, *t, it)?;
2435 write!(w, "</div>")?;
2438 // Output the documentation for each function individually
2439 if !required.is_empty() {
2441 <h2 id='required-methods' class='small-section-header'>
2442 Required Methods<a href='#required-methods' class='anchor'></a>
2444 <div class='methods'>
2446 for m in &required {
2447 trait_item(w, cx, *m, it)?;
2449 write!(w, "</div>")?;
2451 if !provided.is_empty() {
2453 <h2 id='provided-methods' class='small-section-header'>
2454 Provided Methods<a href='#provided-methods' class='anchor'></a>
2456 <div class='methods'>
2458 for m in &provided {
2459 trait_item(w, cx, *m, it)?;
2461 write!(w, "</div>")?;
2464 // If there are methods directly on this trait object, render them here.
2465 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2467 let cache = cache();
2469 <h2 id='implementors' class='small-section-header'>
2470 Implementors<a href='#implementors' class='anchor'></a>
2472 <ul class='item-list' id='implementors-list'>
2474 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2475 // The DefId is for the first Type found with that name. The bool is
2476 // if any Types with the same name but different DefId have been found.
2477 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2478 for implementor in implementors {
2479 match implementor.impl_.for_ {
2480 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2481 clean::BorrowedRef {
2482 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2485 let &mut (prev_did, ref mut has_duplicates) =
2486 implementor_dups.entry(path.last_name()).or_insert((did, false));
2487 if prev_did != did {
2488 *has_duplicates = true;
2495 let (local, foreign) = implementors.iter()
2496 .partition::<Vec<_>, _>(|i| i.impl_.for_.def_id()
2497 .map_or(true, |d| cache.paths.contains_key(&d)));
2499 if !foreign.is_empty() {
2501 <h2 id='foreign-impls' class='section-header'>
2502 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2506 for implementor in foreign {
2507 if let Some(i) = implementor2item(&cache, implementor) {
2508 let impl_ = Impl { impl_item: i.clone() };
2509 let assoc_link = AssocItemLink::GotoSource(
2510 i.def_id, &implementor.impl_.provided_trait_methods
2512 render_impl(w, cx, &impl_, assoc_link,
2513 RenderMode::Normal, i.stable_since(), false)?;
2518 write!(w, "{}", impl_header)?;
2520 for implementor in local {
2522 if let Some(item) = implementor2item(&cache, implementor) {
2523 if let Some(l) = (Item { cx, item }).src_href() {
2524 write!(w, "<div class='out-of-band'>")?;
2525 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2526 l, "goto source code")?;
2527 write!(w, "</div>")?;
2530 write!(w, "<code>")?;
2531 // If there's already another implementor that has the same abbridged name, use the
2532 // full path, for example in `std::iter::ExactSizeIterator`
2533 let use_absolute = match implementor.impl_.for_ {
2534 clean::ResolvedPath { ref path, is_generic: false, .. } |
2535 clean::BorrowedRef {
2536 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2538 } => implementor_dups[path.last_name()].1,
2541 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2542 for it in &implementor.impl_.items {
2543 if let clean::TypedefItem(ref tydef, _) = it.inner {
2544 write!(w, "<span class=\"where fmt-newline\"> ")?;
2545 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2546 write!(w, ";</span>")?;
2549 writeln!(w, "</code></li>")?;
2552 // even without any implementations to write in, we still want the heading and list, so the
2553 // implementors javascript file pulled in below has somewhere to write the impls into
2554 write!(w, "{}", impl_header)?;
2556 write!(w, "</ul>")?;
2557 write!(w, r#"<script type="text/javascript" async
2558 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2560 root_path = vec![".."; cx.current.len()].join("/"),
2561 path = if it.def_id.is_local() {
2562 cx.current.join("/")
2564 let (ref path, _) = cache.external_paths[&it.def_id];
2565 path[..path.len() - 1].join("/")
2567 ty = it.type_().css_class(),
2568 name = *it.name.as_ref().unwrap())?;
2572 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2573 use html::item_type::ItemType::*;
2575 let name = it.name.as_ref().unwrap();
2576 let ty = match it.type_() {
2577 Typedef | AssociatedType => AssociatedType,
2581 let anchor = format!("#{}.{}", ty, name);
2583 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2584 AssocItemLink::Anchor(None) => anchor,
2585 AssocItemLink::GotoSource(did, _) => {
2586 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2591 fn assoc_const(w: &mut fmt::Formatter,
2594 _default: Option<&String>,
2595 link: AssocItemLink) -> fmt::Result {
2596 write!(w, "const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2597 naive_assoc_href(it, link),
2598 it.name.as_ref().unwrap(),
2603 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2604 bounds: &Vec<clean::TyParamBound>,
2605 default: Option<&clean::Type>,
2606 link: AssocItemLink) -> fmt::Result {
2607 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2608 naive_assoc_href(it, link),
2609 it.name.as_ref().unwrap())?;
2610 if !bounds.is_empty() {
2611 write!(w, ": {}", TyParamBounds(bounds))?
2613 if let Some(default) = default {
2614 write!(w, " = {}", default)?;
2619 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2620 ver: Option<&'a str>,
2621 containing_ver: Option<&'a str>) -> fmt::Result {
2622 if let Some(v) = ver {
2623 if containing_ver != ver && v.len() > 0 {
2624 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2631 fn render_stability_since(w: &mut fmt::Formatter,
2633 containing_item: &clean::Item) -> fmt::Result {
2634 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2637 fn render_assoc_item(w: &mut fmt::Formatter,
2639 link: AssocItemLink,
2640 parent: ItemType) -> fmt::Result {
2641 fn method(w: &mut fmt::Formatter,
2643 unsafety: hir::Unsafety,
2644 constness: hir::Constness,
2646 g: &clean::Generics,
2648 link: AssocItemLink,
2651 let name = meth.name.as_ref().unwrap();
2652 let anchor = format!("#{}.{}", meth.type_(), name);
2653 let href = match link {
2654 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2655 AssocItemLink::Anchor(None) => anchor,
2656 AssocItemLink::GotoSource(did, provided_methods) => {
2657 // We're creating a link from an impl-item to the corresponding
2658 // trait-item and need to map the anchored type accordingly.
2659 let ty = if provided_methods.contains(name) {
2665 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2668 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2669 VisSpace(&meth.visibility),
2670 ConstnessSpace(constness),
2671 UnsafetySpace(unsafety),
2675 let (indent, end_newline) = if parent == ItemType::Trait {
2681 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2682 {generics}{decl}{where_clause}",
2683 VisSpace(&meth.visibility),
2684 ConstnessSpace(constness),
2685 UnsafetySpace(unsafety),
2695 where_clause = WhereClause {
2702 clean::StrippedItem(..) => Ok(()),
2703 clean::TyMethodItem(ref m) => {
2704 method(w, item, m.unsafety, hir::Constness::NotConst,
2705 m.abi, &m.generics, &m.decl, link, parent)
2707 clean::MethodItem(ref m) => {
2708 method(w, item, m.unsafety, m.constness,
2709 m.abi, &m.generics, &m.decl, link, parent)
2711 clean::AssociatedConstItem(ref ty, ref default) => {
2712 assoc_const(w, item, ty, default.as_ref(), link)
2714 clean::AssociatedTypeItem(ref bounds, ref default) => {
2715 assoc_type(w, item, bounds, default.as_ref(), link)
2717 _ => panic!("render_assoc_item called on non-associated-item")
2721 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2722 s: &clean::Struct) -> fmt::Result {
2723 write!(w, "<pre class='rust struct'>")?;
2724 render_attributes(w, it)?;
2732 write!(w, "</pre>")?;
2734 document(w, cx, it)?;
2735 let mut fields = s.fields.iter().filter_map(|f| {
2737 clean::StructFieldItem(ref ty) => Some((f, ty)),
2741 if let doctree::Plain = s.struct_type {
2742 if fields.peek().is_some() {
2743 write!(w, "<h2 id='fields' class='fields small-section-header'>
2744 Fields<a href='#fields' class='anchor'></a></h2>")?;
2745 for (field, ty) in fields {
2746 let id = derive_id(format!("{}.{}",
2747 ItemType::StructField,
2748 field.name.as_ref().unwrap()));
2749 let ns_id = derive_id(format!("{}.{}",
2750 field.name.as_ref().unwrap(),
2751 ItemType::StructField.name_space()));
2752 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2753 <a href=\"#{id}\" class=\"anchor field\"></a>
2754 <span id=\"{ns_id}\" class='invisible'>
2755 <code>{name}: {ty}</code>
2757 item_type = ItemType::StructField,
2760 name = field.name.as_ref().unwrap(),
2762 if let Some(stability_class) = field.stability_class() {
2763 write!(w, "<span class='stab {stab}'></span>",
2764 stab = stability_class)?;
2766 document(w, cx, field)?;
2770 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2773 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2774 s: &clean::Union) -> fmt::Result {
2775 write!(w, "<pre class='rust union'>")?;
2776 render_attributes(w, it)?;
2783 write!(w, "</pre>")?;
2785 document(w, cx, it)?;
2786 let mut fields = s.fields.iter().filter_map(|f| {
2788 clean::StructFieldItem(ref ty) => Some((f, ty)),
2792 if fields.peek().is_some() {
2793 write!(w, "<h2 id='fields' class='fields small-section-header'>
2794 Fields<a href='#fields' class='anchor'></a></h2>")?;
2795 for (field, ty) in fields {
2796 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2798 shortty = ItemType::StructField,
2799 name = field.name.as_ref().unwrap(),
2801 if let Some(stability_class) = field.stability_class() {
2802 write!(w, "<span class='stab {stab}'></span>",
2803 stab = stability_class)?;
2805 document(w, cx, field)?;
2808 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2811 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2812 e: &clean::Enum) -> fmt::Result {
2813 write!(w, "<pre class='rust enum'>")?;
2814 render_attributes(w, it)?;
2815 write!(w, "{}enum {}{}{}",
2816 VisSpace(&it.visibility),
2817 it.name.as_ref().unwrap(),
2819 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2820 if e.variants.is_empty() && !e.variants_stripped {
2821 write!(w, " {{}}")?;
2823 write!(w, " {{\n")?;
2824 for v in &e.variants {
2826 let name = v.name.as_ref().unwrap();
2828 clean::VariantItem(ref var) => {
2830 clean::VariantKind::CLike => write!(w, "{}", name)?,
2831 clean::VariantKind::Tuple(ref tys) => {
2832 write!(w, "{}(", name)?;
2833 for (i, ty) in tys.iter().enumerate() {
2835 write!(w, ", ")?
2837 write!(w, "{}", *ty)?;
2841 clean::VariantKind::Struct(ref s) => {
2857 if e.variants_stripped {
2858 write!(w, " // some variants omitted\n")?;
2862 write!(w, "</pre>")?;
2864 document(w, cx, it)?;
2865 if !e.variants.is_empty() {
2866 write!(w, "<h2 id='variants' class='variants small-section-header'>
2867 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2868 for variant in &e.variants {
2869 let id = derive_id(format!("{}.{}",
2871 variant.name.as_ref().unwrap()));
2872 let ns_id = derive_id(format!("{}.{}",
2873 variant.name.as_ref().unwrap(),
2874 ItemType::Variant.name_space()));
2875 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2876 <a href=\"#{id}\" class=\"anchor field\"></a>\
2877 <span id='{ns_id}' class='invisible'><code>{name}",
2880 name = variant.name.as_ref().unwrap())?;
2881 if let clean::VariantItem(ref var) = variant.inner {
2882 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2884 for (i, ty) in tys.iter().enumerate() {
2886 write!(w, ", ")?;
2888 write!(w, "{}", *ty)?;
2893 write!(w, "</code></span></span>")?;
2894 document(w, cx, variant)?;
2896 use clean::{Variant, VariantKind};
2897 if let clean::VariantItem(Variant {
2898 kind: VariantKind::Struct(ref s)
2899 }) = variant.inner {
2900 let variant_id = derive_id(format!("{}.{}.fields",
2902 variant.name.as_ref().unwrap()));
2903 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2905 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2906 <table>", name = variant.name.as_ref().unwrap())?;
2907 for field in &s.fields {
2908 use clean::StructFieldItem;
2909 if let StructFieldItem(ref ty) = field.inner {
2910 let id = derive_id(format!("variant.{}.field.{}",
2911 variant.name.as_ref().unwrap(),
2912 field.name.as_ref().unwrap()));
2913 let ns_id = derive_id(format!("{}.{}.{}.{}",
2914 variant.name.as_ref().unwrap(),
2915 ItemType::Variant.name_space(),
2916 field.name.as_ref().unwrap(),
2917 ItemType::StructField.name_space()));
2918 write!(w, "<tr><td \
2920 <span id='{ns_id}' class='invisible'>\
2921 <code>{f}: {t}</code></span></td><td>",
2924 f = field.name.as_ref().unwrap(),
2926 document(w, cx, field)?;
2927 write!(w, "</td></tr>")?;
2930 write!(w, "</table></span>")?;
2932 render_stability_since(w, variant, it)?;
2935 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2939 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2940 let name = attr.name();
2943 Some(format!("{}", name))
2944 } else if let Some(v) = attr.value_str() {
2945 Some(format!("{} = {:?}", name, v.as_str()))
2946 } else if let Some(values) = attr.meta_item_list() {
2947 let display: Vec<_> = values.iter().filter_map(|attr| {
2948 attr.meta_item().and_then(|mi| render_attribute(mi))
2951 if display.len() > 0 {
2952 Some(format!("{}({})", name, display.join(", ")))
2961 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2968 "unsafe_destructor_blind_to_params"
2971 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2972 let mut attrs = String::new();
2974 for attr in &it.attrs.other_attrs {
2975 let name = attr.name().unwrap();
2976 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2979 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2980 attrs.push_str(&format!("#[{}]\n", s));
2983 if attrs.len() > 0 {
2984 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2989 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2990 g: Option<&clean::Generics>,
2991 ty: doctree::StructType,
2992 fields: &[clean::Item],
2994 structhead: bool) -> fmt::Result {
2996 VisSpace(&it.visibility),
2997 if structhead {"struct "} else {""},
2998 it.name.as_ref().unwrap())?;
2999 if let Some(g) = g {
3004 if let Some(g) = g {
3005 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3007 let mut has_visible_fields = false;
3009 for field in fields {
3010 if let clean::StructFieldItem(ref ty) = field.inner {
3011 write!(w, "\n{} {}{}: {},",
3013 VisSpace(&field.visibility),
3014 field.name.as_ref().unwrap(),
3016 has_visible_fields = true;
3020 if has_visible_fields {
3021 if it.has_stripped_fields().unwrap() {
3022 write!(w, "\n{} // some fields omitted", tab)?;
3024 write!(w, "\n{}", tab)?;
3025 } else if it.has_stripped_fields().unwrap() {
3026 // If there are no visible fields we can just display
3027 // `{ /* fields omitted */ }` to save space.
3028 write!(w, " /* fields omitted */ ")?;
3034 for (i, field) in fields.iter().enumerate() {
3039 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3042 clean::StructFieldItem(ref ty) => {
3043 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3049 if let Some(g) = g {
3050 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3055 // Needed for PhantomData.
3056 if let Some(g) = g {
3057 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3065 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3066 g: Option<&clean::Generics>,
3067 fields: &[clean::Item],
3069 structhead: bool) -> fmt::Result {
3071 VisSpace(&it.visibility),
3072 if structhead {"union "} else {""},
3073 it.name.as_ref().unwrap())?;
3074 if let Some(g) = g {
3075 write!(w, "{}", g)?;
3076 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3079 write!(w, " {{\n{}", tab)?;
3080 for field in fields {
3081 if let clean::StructFieldItem(ref ty) = field.inner {
3082 write!(w, " {}{}: {},\n{}",
3083 VisSpace(&field.visibility),
3084 field.name.as_ref().unwrap(),
3090 if it.has_stripped_fields().unwrap() {
3091 write!(w, " // some fields omitted\n{}", tab)?;
3097 #[derive(Copy, Clone)]
3098 enum AssocItemLink<'a> {
3099 Anchor(Option<&'a str>),
3100 GotoSource(DefId, &'a FxHashSet<String>),
3103 impl<'a> AssocItemLink<'a> {
3104 fn anchor(&self, id: &'a String) -> Self {
3106 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3107 ref other => *other,
3112 enum AssocItemRender<'a> {
3114 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3117 #[derive(Copy, Clone, PartialEq)]
3120 ForDeref { mut_: bool },
3123 fn render_assoc_items(w: &mut fmt::Formatter,
3125 containing_item: &clean::Item,
3127 what: AssocItemRender) -> fmt::Result {
3129 let v = match c.impls.get(&it) {
3131 None => return Ok(()),
3133 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3134 i.inner_impl().trait_.is_none()
3136 if !non_trait.is_empty() {
3137 let render_mode = match what {
3138 AssocItemRender::All => {
3140 <h2 id='methods' class='small-section-header'>
3141 Methods<a href='#methods' class='anchor'></a>
3146 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3148 <h2 id='deref-methods' class='small-section-header'>
3149 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3152 RenderMode::ForDeref { mut_: deref_mut_ }
3155 for i in &non_trait {
3156 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3157 containing_item.stable_since(), true)?;
3160 if let AssocItemRender::DerefFor { .. } = what {
3163 if !traits.is_empty() {
3164 let deref_impl = traits.iter().find(|t| {
3165 t.inner_impl().trait_.def_id() == c.deref_trait_did
3167 if let Some(impl_) = deref_impl {
3168 let has_deref_mut = traits.iter().find(|t| {
3169 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3171 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3174 <h2 id='implementations' class='small-section-header'>
3175 Trait Implementations<a href='#implementations' class='anchor'></a>
3179 let did = i.trait_did().unwrap();
3180 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3181 render_impl(w, cx, i, assoc_link,
3182 RenderMode::Normal, containing_item.stable_since(), true)?;
3188 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3189 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3190 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3191 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3193 clean::TypedefItem(ref t, true) => Some(&t.type_),
3196 }).next().expect("Expected associated type binding");
3197 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3198 deref_mut_: deref_mut };
3199 if let Some(did) = target.def_id() {
3200 render_assoc_items(w, cx, container_item, did, what)
3202 if let Some(prim) = target.primitive_type() {
3203 if let Some(&did) = cache().primitive_locations.get(&prim) {
3204 render_assoc_items(w, cx, container_item, did, what)?;
3211 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3212 let self_type_opt = match item.inner {
3213 clean::MethodItem(ref method) => method.decl.self_type(),
3214 clean::TyMethodItem(ref method) => method.decl.self_type(),
3218 if let Some(self_ty) = self_type_opt {
3219 let (by_mut_ref, by_box) = match self_ty {
3220 SelfTy::SelfBorrowed(_, mutability) |
3221 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3222 (mutability == Mutability::Mutable, false)
3224 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3225 (false, Some(did) == cache().owned_box_did)
3227 _ => (false, false),
3230 (deref_mut_ || !by_mut_ref) && !by_box
3236 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3237 render_mode: RenderMode, outer_version: Option<&str>,
3238 show_def_docs: bool) -> fmt::Result {
3239 if render_mode == RenderMode::Normal {
3240 let id = derive_id(match i.inner_impl().trait_ {
3241 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3242 None => "impl".to_string(),
3244 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3245 id, i.inner_impl())?;
3246 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3247 write!(w, "</span><span class='out-of-band'>")?;
3248 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3249 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3250 write!(w, "<div class='ghost'></div>")?;
3251 render_stability_since_raw(w, since, outer_version)?;
3252 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3253 l, "goto source code")?;
3255 render_stability_since_raw(w, since, outer_version)?;
3257 write!(w, "</span>")?;
3258 write!(w, "</h3>\n")?;
3259 if let Some(ref dox) = i.impl_item.doc_value() {
3260 write!(w, "<div class='docblock'>{}</div>", Markdown(dox, cx.render_type))?;
3264 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3265 link: AssocItemLink, render_mode: RenderMode,
3266 is_default_item: bool, outer_version: Option<&str>,
3267 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3268 let item_type = item.type_();
3269 let name = item.name.as_ref().unwrap();
3271 let render_method_item: bool = match render_mode {
3272 RenderMode::Normal => true,
3273 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3277 clean::MethodItem(..) | clean::TyMethodItem(..) => {
3278 // Only render when the method is not static or we allow static methods
3279 if render_method_item {
3280 let id = derive_id(format!("{}.{}", item_type, name));
3281 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3282 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3283 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3284 write!(w, "<code>")?;
3285 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3286 write!(w, "</code>")?;
3287 if let Some(l) = (Item { cx, item }).src_href() {
3288 write!(w, "</span><span class='out-of-band'>")?;
3289 write!(w, "<div class='ghost'></div>")?;
3290 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3291 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3292 l, "goto source code")?;
3294 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3296 write!(w, "</span></h4>\n")?;
3299 clean::TypedefItem(ref tydef, _) => {
3300 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3301 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3302 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3303 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3304 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3305 write!(w, "</code></span></h4>\n")?;
3307 clean::AssociatedConstItem(ref ty, ref default) => {
3308 let id = derive_id(format!("{}.{}", item_type, name));
3309 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3310 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3311 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3312 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3313 write!(w, "</code></span></h4>\n")?;
3315 clean::AssociatedTypeItem(ref bounds, ref default) => {
3316 let id = derive_id(format!("{}.{}", item_type, name));
3317 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3318 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3319 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3320 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3321 write!(w, "</code></span></h4>\n")?;
3323 clean::StrippedItem(..) => return Ok(()),
3324 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3327 if render_method_item || render_mode == RenderMode::Normal {
3328 let prefix = render_assoc_const_value(item);
3329 if !is_default_item {
3330 if let Some(t) = trait_ {
3331 // The trait item may have been stripped so we might not
3332 // find any documentation or stability for it.
3333 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3334 // We need the stability of the item from the trait
3335 // because impls can't have a stability.
3336 document_stability(w, cx, it)?;
3337 if item.doc_value().is_some() {
3338 document_full(w, item, cx, &prefix)?;
3339 } else if show_def_docs {
3340 // In case the item isn't documented,
3341 // provide short documentation from the trait.
3342 document_short(w, it, link, cx, &prefix)?;
3346 document_stability(w, cx, item)?;
3348 document_full(w, item, cx, &prefix)?;
3352 document_stability(w, cx, item)?;
3354 document_short(w, item, link, cx, &prefix)?;
3361 let traits = &cache().traits;
3362 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3365 write!(w, "<span class='docblock autohide'>")?;
3368 write!(w, "<div class='impl-items'>")?;
3369 for trait_item in &i.inner_impl().items {
3370 doc_impl_item(w, cx, trait_item, link, render_mode,
3371 false, outer_version, trait_, show_def_docs)?;
3374 fn render_default_items(w: &mut fmt::Formatter,
3378 render_mode: RenderMode,
3379 outer_version: Option<&str>,
3380 show_def_docs: bool) -> fmt::Result {
3381 for trait_item in &t.items {
3382 let n = trait_item.name.clone();
3383 if i.items.iter().find(|m| m.name == n).is_some() {
3386 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3387 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3389 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3390 outer_version, None, show_def_docs)?;
3395 // If we've implemented a trait, then also emit documentation for all
3396 // default items which weren't overridden in the implementation block.
3397 if let Some(t) = trait_ {
3398 render_default_items(w, cx, t, &i.inner_impl(),
3399 render_mode, outer_version, show_def_docs)?;
3401 write!(w, "</div>")?;
3404 write!(w, "</span>")?;
3410 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3411 t: &clean::Typedef) -> fmt::Result {
3412 write!(w, "<pre class='rust typedef'>")?;
3413 render_attributes(w, it)?;
3414 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3415 it.name.as_ref().unwrap(),
3417 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3420 document(w, cx, it)?;
3422 // Render any items associated directly to this alias, as otherwise they
3423 // won't be visible anywhere in the docs. It would be nice to also show
3424 // associated items from the aliased type (see discussion in #32077), but
3425 // we need #14072 to make sense of the generics.
3426 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3429 impl<'a> fmt::Display for Sidebar<'a> {
3430 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3433 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3435 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3436 || it.is_enum() || it.is_mod() || it.is_typedef()
3438 write!(fmt, "<p class='location'>")?;
3440 clean::StructItem(..) => write!(fmt, "Struct ")?,
3441 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3442 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3443 clean::UnionItem(..) => write!(fmt, "Union ")?,
3444 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3445 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3446 clean::ModuleItem(..) => if it.is_crate() {
3447 write!(fmt, "Crate ")?;
3449 write!(fmt, "Module ")?;
3453 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3454 write!(fmt, "</p>")?;
3457 if let Some(ref version) = cache().crate_version {
3459 "<div class='block version'>\
3467 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3468 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3469 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3470 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3471 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3472 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3473 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3478 // The sidebar is designed to display sibling functions, modules and
3479 // other miscellaneous information. since there are lots of sibling
3480 // items (and that causes quadratic growth in large modules),
3481 // we refactor common parts into a shared JavaScript file per module.
3482 // still, we don't move everything into JS because we want to preserve
3483 // as much HTML as possible in order to allow non-JS-enabled browsers
3484 // to navigate the documentation (though slightly inefficiently).
3486 write!(fmt, "<p class='location'>")?;
3487 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3489 write!(fmt, "::<wbr>")?;
3491 write!(fmt, "<a href='{}index.html'>{}</a>",
3492 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3495 write!(fmt, "</p>")?;
3497 // Sidebar refers to the enclosing module, not this module.
3498 let relpath = if it.is_mod() { "../" } else { "" };
3500 "<script>window.sidebarCurrent = {{\
3505 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3506 ty = it.type_().css_class(),
3509 // There is no sidebar-items.js beyond the crate root path
3510 // FIXME maybe dynamic crate loading can be merged here
3512 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3520 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3521 i.items.iter().filter_map(|item| {
3523 // Maybe check with clean::Visibility::Public as well?
3524 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3525 if !for_deref || should_render_item(item, false) {
3526 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3533 }).collect::<Vec<_>>()
3536 // The point is to url encode any potential character from a type with genericity.
3537 fn small_url_encode(s: &str) -> String {
3538 s.replace("<", "%3C")
3539 .replace(">", "%3E")
3540 .replace(" ", "%20")
3541 .replace("?", "%3F")
3542 .replace("'", "%27")
3543 .replace("&", "%26")
3544 .replace(",", "%2C")
3545 .replace(":", "%3A")
3546 .replace(";", "%3B")
3547 .replace("[", "%5B")
3548 .replace("]", "%5D")
3551 fn sidebar_assoc_items(it: &clean::Item) -> String {
3552 let mut out = String::new();
3554 if let Some(v) = c.impls.get(&it.def_id) {
3556 .filter(|i| i.inner_impl().trait_.is_none())
3557 .flat_map(|i| get_methods(i.inner_impl(), false))
3558 .collect::<String>();
3559 if !ret.is_empty() {
3560 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3561 </a><div class=\"sidebar-links\">{}</div>", ret));
3564 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3565 if let Some(impl_) = v.iter()
3566 .filter(|i| i.inner_impl().trait_.is_some())
3567 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3568 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3570 clean::TypedefItem(ref t, true) => Some(&t.type_),
3574 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3575 c.primitive_locations.get(&prim).cloned()
3576 })).and_then(|did| c.impls.get(&did));
3577 if let Some(impls) = inner_impl {
3578 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3579 out.push_str(&format!("Methods from {:#}<Target={:#}>",
3580 impl_.inner_impl().trait_.as_ref().unwrap(),
3582 out.push_str("</a>");
3583 let ret = impls.iter()
3584 .filter(|i| i.inner_impl().trait_.is_none())
3585 .flat_map(|i| get_methods(i.inner_impl(), true))
3586 .collect::<String>();
3587 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3591 let mut links = HashSet::new();
3593 .filter_map(|i| if let Some(ref i) = i.inner_impl().trait_ {
3594 let out = format!("{:#}", i).replace("<", "<").replace(">", ">");
3595 let encoded = small_url_encode(&format!("{:#}", i));
3596 let generated = format!("<a href=\"#impl-{}\">{}</a>", encoded, out);
3597 if !links.contains(&generated) && links.insert(generated.clone()) {
3605 .collect::<String>();
3606 if !ret.is_empty() {
3607 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3608 Trait Implementations</a>");
3609 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3617 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3618 s: &clean::Struct) -> fmt::Result {
3619 let mut sidebar = String::new();
3622 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3623 if let doctree::Plain = s.struct_type {
3624 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3628 sidebar.push_str(&sidebar_assoc_items(it));
3630 if !sidebar.is_empty() {
3631 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3636 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3637 t: &clean::Trait) -> fmt::Result {
3638 let mut sidebar = String::new();
3640 let has_types = t.items.iter().any(|m| m.is_associated_type());
3641 let has_consts = t.items.iter().any(|m| m.is_associated_const());
3642 let has_required = t.items.iter().any(|m| m.is_ty_method());
3643 let has_provided = t.items.iter().any(|m| m.is_method());
3646 sidebar.push_str("<li><a href=\"#associated-types\">Associated Types</a></li>");
3649 sidebar.push_str("<li><a href=\"#associated-const\">Associated Constants</a></li>");
3652 sidebar.push_str("<li><a href=\"#required-methods\">Required Methods</a></li>");
3655 sidebar.push_str("<li><a href=\"#provided-methods\">Provided Methods</a></li>");
3660 if let Some(implementors) = c.implementors.get(&it.def_id) {
3661 if implementors.iter().any(|i| i.impl_.for_.def_id()
3662 .map_or(false, |d| !c.paths.contains_key(&d)))
3664 sidebar.push_str("<li><a href=\"#foreign-impls\">\
3665 Implementations on Foreign Types</a></li>");
3669 sidebar.push_str("<li><a href=\"#implementors\">Implementors</a></li>");
3671 sidebar.push_str(&sidebar_assoc_items(it));
3673 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3676 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3677 _p: &clean::PrimitiveType) -> fmt::Result {
3678 let sidebar = sidebar_assoc_items(it);
3680 if !sidebar.is_empty() {
3681 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3686 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3687 _t: &clean::Typedef) -> fmt::Result {
3688 let sidebar = sidebar_assoc_items(it);
3690 if !sidebar.is_empty() {
3691 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3696 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3697 u: &clean::Union) -> fmt::Result {
3698 let mut sidebar = String::new();
3701 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3702 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3705 sidebar.push_str(&sidebar_assoc_items(it));
3707 if !sidebar.is_empty() {
3708 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3713 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3714 e: &clean::Enum) -> fmt::Result {
3715 let mut sidebar = String::new();
3717 if !e.variants.is_empty() {
3718 sidebar.push_str("<li><a href=\"#variants\">Variants</a></li>");
3721 sidebar.push_str(&sidebar_assoc_items(it));
3723 if !sidebar.is_empty() {
3724 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3729 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3730 items: &[clean::Item]) -> fmt::Result {
3731 let mut sidebar = String::new();
3733 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3734 it.type_() == ItemType::Import) {
3735 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3737 name = "Reexports"));
3740 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3741 // to print its headings
3742 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3743 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3744 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3745 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3746 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3747 if items.iter().any(|it| {
3748 if let clean::AutoImplItem(..) = it.inner {
3751 !it.is_stripped() && it.type_() == myty
3754 let (short, name) = match myty {
3755 ItemType::ExternCrate |
3756 ItemType::Import => ("reexports", "Reexports"),
3757 ItemType::Module => ("modules", "Modules"),
3758 ItemType::Struct => ("structs", "Structs"),
3759 ItemType::Union => ("unions", "Unions"),
3760 ItemType::Enum => ("enums", "Enums"),
3761 ItemType::Function => ("functions", "Functions"),
3762 ItemType::Typedef => ("types", "Type Definitions"),
3763 ItemType::Static => ("statics", "Statics"),
3764 ItemType::Constant => ("constants", "Constants"),
3765 ItemType::Trait => ("traits", "Traits"),
3766 ItemType::Impl => ("impls", "Implementations"),
3767 ItemType::TyMethod => ("tymethods", "Type Methods"),
3768 ItemType::Method => ("methods", "Methods"),
3769 ItemType::StructField => ("fields", "Struct Fields"),
3770 ItemType::Variant => ("variants", "Variants"),
3771 ItemType::Macro => ("macros", "Macros"),
3772 ItemType::Primitive => ("primitives", "Primitive Types"),
3773 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3774 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3775 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
3777 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3783 if !sidebar.is_empty() {
3784 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3789 impl<'a> fmt::Display for Source<'a> {
3790 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3791 let Source(s) = *self;
3792 let lines = s.lines().count();
3794 let mut tmp = lines;
3799 write!(fmt, "<pre class=\"line-numbers\">")?;
3800 for i in 1..lines + 1 {
3801 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3803 write!(fmt, "</pre>")?;
3805 highlight::render_with_highlighting(s, None, None, None, None))?;
3810 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3811 t: &clean::Macro) -> fmt::Result {
3812 w.write_str(&highlight::render_with_highlighting(&t.source,
3820 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3822 _p: &clean::PrimitiveType) -> fmt::Result {
3823 document(w, cx, it)?;
3824 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3827 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3829 fn make_item_keywords(it: &clean::Item) -> String {
3830 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3833 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3834 let decl = match item.inner {
3835 clean::FunctionItem(ref f) => &f.decl,
3836 clean::MethodItem(ref m) => &m.decl,
3837 clean::TyMethodItem(ref m) => &m.decl,
3841 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3842 let output = match decl.output {
3843 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3847 Some(IndexItemFunctionType { inputs: inputs, output: output })
3850 fn get_index_type(clean_type: &clean::Type) -> Type {
3851 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3854 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3856 clean::ResolvedPath { ref path, .. } => {
3857 let segments = &path.segments;
3858 Some(segments[segments.len() - 1].name.clone())
3860 clean::Generic(ref s) => Some(s.clone()),
3861 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3862 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3863 // FIXME: add all from clean::Type.
3868 pub fn cache() -> Arc<Cache> {
3869 CACHE_KEY.with(|c| c.borrow().clone())
3874 fn test_unique_id() {
3875 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3876 "method.into_iter", "foo", "main", "search", "methods",
3877 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3878 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3879 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3880 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3883 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3884 assert_eq!(&actual[..], expected);
3893 fn test_name_key() {
3894 assert_eq!(name_key("0"), ("", 0, 1));
3895 assert_eq!(name_key("123"), ("", 123, 0));
3896 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
3897 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
3898 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
3899 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
3900 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
3901 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
3906 fn test_name_sorting() {
3907 let names = ["Apple",
3909 "Fruit", "Fruit0", "Fruit00",
3910 "Fruit1", "Fruit01",
3911 "Fruit2", "Fruit02",
3915 let mut sorted = names.to_owned();
3916 sorted.sort_by_key(|&s| name_key(s));
3917 assert_eq!(names, sorted);