1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
35 pub use self::ExternalLocation::*;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::{BTreeMap, HashSet};
41 use std::default::Default;
43 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
44 use std::fs::{self, File, OpenOptions};
45 use std::io::prelude::*;
46 use std::io::{self, BufWriter, BufReader};
47 use std::iter::repeat;
49 use std::path::{PathBuf, Path, Component};
53 use externalfiles::ExternalHtml;
55 use serialize::json::{ToJson, Json, as_json};
56 use syntax::{abi, ast};
57 use syntax::codemap::FileName;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability, 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>>,
132 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
133 /// should be ordered alphabetically or in order of appearance (in the source code).
134 pub sort_modules_alphabetically: bool,
135 /// Additional themes to be added to the generated docs.
136 pub themes: Vec<PathBuf>,
140 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
141 let mut dirs = self.created_dirs.borrow_mut();
142 if !dirs.contains(dst) {
143 fs::create_dir_all(dst)?;
144 dirs.insert(dst.to_path_buf());
152 /// Returns whether the `collapse-docs` pass was run on this crate.
153 pub fn was_collapsed(&self) -> bool {
154 self.passes.contains("collapse-docs")
157 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
158 /// `collapsed_doc_value` of the given item.
159 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
160 if self.was_collapsed() {
161 item.collapsed_doc_value().map(|s| s.into())
163 item.doc_value().map(|s| s.into())
168 /// Indicates where an external crate can be found.
169 pub enum ExternalLocation {
170 /// Remote URL root of the external crate
172 /// This external crate can be found in the local doc/ folder
174 /// The external crate could not be found.
178 /// Metadata about implementations for a type or trait.
181 pub impl_item: clean::Item,
185 fn inner_impl(&self) -> &clean::Impl {
186 match self.impl_item.inner {
187 clean::ImplItem(ref impl_) => impl_,
188 _ => panic!("non-impl item found in impl")
192 fn trait_did(&self) -> Option<DefId> {
193 self.inner_impl().trait_.def_id()
203 impl error::Error for Error {
204 fn description(&self) -> &str {
205 self.error.description()
209 impl Display for Error {
210 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
211 write!(f, "\"{}\": {}", self.file.display(), self.error)
216 pub fn new(e: io::Error, file: &Path) -> Error {
218 file: file.to_path_buf(),
224 macro_rules! try_none {
225 ($e:expr, $file:expr) => ({
229 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
235 macro_rules! try_err {
236 ($e:expr, $file:expr) => ({
239 Err(e) => return Err(Error::new(e, $file)),
244 /// This cache is used to store information about the `clean::Crate` being
245 /// rendered in order to provide more useful documentation. This contains
246 /// information like all implementors of a trait, all traits a type implements,
247 /// documentation for all known traits, etc.
249 /// This structure purposefully does not implement `Clone` because it's intended
250 /// to be a fairly large and expensive structure to clone. Instead this adheres
251 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
252 /// rendering threads.
255 /// Mapping of typaram ids to the name of the type parameter. This is used
256 /// when pretty-printing a type (so pretty printing doesn't have to
257 /// painfully maintain a context like this)
258 pub typarams: FxHashMap<DefId, String>,
260 /// Maps a type id to all known implementations for that type. This is only
261 /// recognized for intra-crate `ResolvedPath` types, and is used to print
262 /// out extra documentation on the page of an enum/struct.
264 /// The values of the map are a list of implementations and documentation
265 /// found on that implementation.
266 pub impls: FxHashMap<DefId, Vec<Impl>>,
268 /// Maintains a mapping of local crate node ids to the fully qualified name
269 /// and "short type description" of that node. This is used when generating
270 /// URLs when a type is being linked to. External paths are not located in
271 /// this map because the `External` type itself has all the information
273 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
275 /// Similar to `paths`, but only holds external paths. This is only used for
276 /// generating explicit hyperlinks to other crates.
277 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
279 /// This map contains information about all known traits of this crate.
280 /// Implementations of a crate should inherit the documentation of the
281 /// parent trait if no extra documentation is specified, and default methods
282 /// should show up in documentation about trait implementations.
283 pub traits: FxHashMap<DefId, clean::Trait>,
285 /// When rendering traits, it's often useful to be able to list all
286 /// implementors of the trait, and this mapping is exactly, that: a mapping
287 /// of trait ids to the list of known implementors of the trait
288 pub implementors: FxHashMap<DefId, Vec<Impl>>,
290 /// Cache of where external crate documentation can be found.
291 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
293 /// Cache of where documentation for primitives can be found.
294 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
296 // Note that external items for which `doc(hidden)` applies to are shown as
297 // non-reachable while local items aren't. This is because we're reusing
298 // the access levels from crateanalysis.
299 pub access_levels: Arc<AccessLevels<DefId>>,
301 /// The version of the crate being documented, if given fron the `--crate-version` flag.
302 pub crate_version: Option<String>,
304 // Private fields only used when initially crawling a crate to build a cache
307 parent_stack: Vec<DefId>,
308 parent_is_trait_impl: bool,
309 search_index: Vec<IndexItem>,
311 deref_trait_did: Option<DefId>,
312 deref_mut_trait_did: Option<DefId>,
313 owned_box_did: Option<DefId>,
314 masked_crates: FxHashSet<CrateNum>,
316 // In rare case where a structure is defined in one module but implemented
317 // in another, if the implementing module is parsed before defining module,
318 // then the fully qualified name of the structure isn't presented in `paths`
319 // yet when its implementation methods are being indexed. Caches such methods
320 // and their parent id here and indexes them at the end of crate parsing.
321 orphan_impl_items: Vec<(DefId, clean::Item)>,
324 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
325 /// Later on moved into `CACHE_KEY`.
327 pub struct RenderInfo {
328 pub inlined: FxHashSet<DefId>,
329 pub external_paths: ::core::ExternalPaths,
330 pub external_typarams: FxHashMap<DefId, String>,
331 pub deref_trait_did: Option<DefId>,
332 pub deref_mut_trait_did: Option<DefId>,
333 pub owned_box_did: Option<DefId>,
336 /// Helper struct to render all source code to HTML pages
337 struct SourceCollector<'a> {
338 scx: &'a mut SharedContext,
340 /// Root destination to place all HTML output into
344 /// Wrapper struct to render the source code of a file. This will do things like
345 /// adding line numbers to the left-hand side.
346 struct Source<'a>(&'a str);
348 // Helper structs for rendering items/sidebars and carrying along contextual
351 #[derive(Copy, Clone)]
354 item: &'a clean::Item,
357 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
359 /// Struct representing one entry in the JS search index. These are all emitted
360 /// by hand to a large JS file at the end of cache-creation.
366 parent: Option<DefId>,
367 parent_idx: Option<usize>,
368 search_type: Option<IndexItemFunctionType>,
371 impl ToJson for IndexItem {
372 fn to_json(&self) -> Json {
373 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
375 let mut data = Vec::with_capacity(6);
376 data.push((self.ty as usize).to_json());
377 data.push(self.name.to_json());
378 data.push(self.path.to_json());
379 data.push(self.desc.to_json());
380 data.push(self.parent_idx.to_json());
381 data.push(self.search_type.to_json());
387 /// A type used for the search index.
389 name: Option<String>,
390 generics: Option<Vec<String>>,
393 impl ToJson for Type {
394 fn to_json(&self) -> Json {
397 let mut data = BTreeMap::new();
398 data.insert("name".to_owned(), name.to_json());
399 if let Some(ref generics) = self.generics {
400 data.insert("generics".to_owned(), generics.to_json());
409 /// Full type of functions/methods in the search index.
410 struct IndexItemFunctionType {
415 impl ToJson for IndexItemFunctionType {
416 fn to_json(&self) -> Json {
417 // If we couldn't figure out a type, just write `null`.
418 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
421 let mut data = BTreeMap::new();
422 data.insert("inputs".to_owned(), self.inputs.to_json());
423 data.insert("output".to_owned(), self.output.to_json());
429 // TLS keys used to carry information around during rendering.
431 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
432 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
433 RefCell::new(Vec::new()));
434 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
435 RefCell::new(init_ids()));
437 pub fn render_text<T, F: FnMut(RenderType) -> T>(mut render: F) -> (T, T) {
438 // Save the state of USED_ID_MAP so it only gets updated once even
439 // though we're rendering twice.
440 let orig_used_id_map = USED_ID_MAP.with(|map| map.borrow().clone());
441 let hoedown_output = render(RenderType::Hoedown);
442 USED_ID_MAP.with(|map| *map.borrow_mut() = orig_used_id_map);
443 let pulldown_output = render(RenderType::Pulldown);
444 (hoedown_output, pulldown_output)
447 fn init_ids() -> FxHashMap<String, usize> {
463 ].into_iter().map(|id| (String::from(*id), 1)).collect()
466 /// This method resets the local table of used ID attributes. This is typically
467 /// used at the beginning of rendering an entire HTML page to reset from the
468 /// previous state (if any).
469 pub fn reset_ids(embedded: bool) {
470 USED_ID_MAP.with(|s| {
471 *s.borrow_mut() = if embedded {
479 pub fn derive_id(candidate: String) -> String {
480 USED_ID_MAP.with(|map| {
481 let id = match map.borrow_mut().get_mut(&candidate) {
484 let id = format!("{}-{}", candidate, *a);
490 map.borrow_mut().insert(id.clone(), 1);
495 /// Generates the documentation for `crate` into the directory `dst`
496 pub fn run(mut krate: clean::Crate,
497 external_html: &ExternalHtml,
498 playground_url: Option<String>,
500 passes: FxHashSet<String>,
501 css_file_extension: Option<PathBuf>,
502 renderinfo: RenderInfo,
503 render_type: RenderType,
504 sort_modules_alphabetically: bool,
505 deny_render_differences: bool,
506 themes: Vec<PathBuf>) -> Result<(), Error> {
507 let src_root = match krate.src {
508 FileName::Real(ref p) => match p.parent() {
509 Some(p) => p.to_path_buf(),
510 None => PathBuf::new(),
514 let mut scx = SharedContext {
517 include_sources: true,
518 local_sources: FxHashMap(),
519 issue_tracker_base_url: None,
520 layout: layout::Layout {
521 logo: "".to_string(),
522 favicon: "".to_string(),
523 external_html: external_html.clone(),
524 krate: krate.name.clone(),
526 css_file_extension: css_file_extension.clone(),
527 markdown_warnings: RefCell::new(vec![]),
528 created_dirs: RefCell::new(FxHashSet()),
529 sort_modules_alphabetically,
533 // If user passed in `--playground-url` arg, we fill in crate name here
534 if let Some(url) = playground_url {
535 markdown::PLAYGROUND.with(|slot| {
536 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
540 // Crawl the crate attributes looking for attributes which control how we're
541 // going to emit HTML
542 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
543 for attr in attrs.lists("doc") {
544 let name = attr.name().map(|s| s.as_str());
545 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
546 (Some("html_favicon_url"), Some(s)) => {
547 scx.layout.favicon = s.to_string();
549 (Some("html_logo_url"), Some(s)) => {
550 scx.layout.logo = s.to_string();
552 (Some("html_playground_url"), Some(s)) => {
553 markdown::PLAYGROUND.with(|slot| {
554 let name = krate.name.clone();
555 *slot.borrow_mut() = Some((Some(name), s.to_string()));
558 (Some("issue_tracker_base_url"), Some(s)) => {
559 scx.issue_tracker_base_url = Some(s.to_string());
561 (Some("html_no_source"), None) if attr.is_word() => {
562 scx.include_sources = false;
568 try_err!(fs::create_dir_all(&dst), &dst);
569 krate = render_sources(&dst, &mut scx, krate)?;
573 render_redirect_pages: false,
574 shared: Arc::new(scx),
578 // Crawl the crate to build various caches used for the output
588 let external_paths = external_paths.into_iter()
589 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
592 let mut cache = Cache {
596 implementors: FxHashMap(),
598 parent_stack: Vec::new(),
599 search_index: Vec::new(),
600 parent_is_trait_impl: false,
601 extern_locations: FxHashMap(),
602 primitive_locations: FxHashMap(),
604 access_levels: krate.access_levels.clone(),
605 crate_version: krate.version.take(),
606 orphan_impl_items: Vec::new(),
607 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
611 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
612 typarams: external_typarams,
615 // Cache where all our extern crates are located
616 for &(n, ref e) in &krate.externs {
617 let src_root = match e.src {
618 FileName::Real(ref p) => match p.parent() {
619 Some(p) => p.to_path_buf(),
620 None => PathBuf::new(),
624 cache.extern_locations.insert(n, (e.name.clone(), src_root,
625 extern_location(e, &cx.dst)));
627 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
628 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
631 // Cache where all known primitives have their documentation located.
633 // Favor linking to as local extern as possible, so iterate all crates in
634 // reverse topological order.
635 for &(_, ref e) in krate.externs.iter().rev() {
636 for &(def_id, prim, _) in &e.primitives {
637 cache.primitive_locations.insert(prim, def_id);
640 for &(def_id, prim, _) in &krate.primitives {
641 cache.primitive_locations.insert(prim, def_id);
644 cache.stack.push(krate.name.clone());
645 krate = cache.fold_crate(krate);
647 // Build our search index
648 let index = build_index(&krate, &mut cache);
650 // Freeze the cache now that the index has been built. Put an Arc into TLS
651 // for future parallelization opportunities
652 let cache = Arc::new(cache);
653 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
654 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
656 write_shared(&cx, &krate, &*cache, index)?;
658 let scx = cx.shared.clone();
660 // And finally render the whole crate's documentation
661 let result = cx.krate(krate);
663 let markdown_warnings = scx.markdown_warnings.borrow();
664 if !markdown_warnings.is_empty() {
665 let mut intro_msg = false;
666 for &(ref span, ref text, ref diffs) in &*markdown_warnings {
668 render_difference(d, &mut intro_msg, span, text);
672 if deny_render_differences {
673 println!("Aborting with {} rendering differences", markdown_warnings.len());
674 ::std::process::exit(1);
681 // A short, single-line view of `s`.
682 fn concise_str(mut s: &str) -> String {
683 if s.contains('\n') {
684 s = s.lines().next().expect("Impossible! We just found a newline");
688 let mut hi = s.len() - 20;
689 while !s.is_char_boundary(lo) {
692 while !s.is_char_boundary(hi) {
695 return format!("{} ... {}", &s[..lo], &s[hi..]);
700 // Returns short versions of s1 and s2, starting from where the strings differ.
701 fn concise_compared_strs(s1: &str, s2: &str) -> (String, String) {
704 if !s1.contains('\n') && !s2.contains('\n') && s1.len() <= 70 && s2.len() <= 70 {
705 return (s1.to_owned(), s2.to_owned());
708 let mut start_byte = 0;
709 for (c1, c2) in s1.chars().zip(s2.chars()) {
714 start_byte += c1.len_utf8();
718 return (concise_str(s1), concise_str(s2));
721 let s1 = &s1[start_byte..];
722 let s2 = &s2[start_byte..];
723 (format!("...{}", concise_str(s1)), format!("...{}", concise_str(s2)))
726 fn print_message(msg: &str, intro_msg: &mut bool, span: &Span, text: &str) {
728 println!("WARNING: documentation for this crate may be rendered \
729 differently using the new Pulldown renderer.");
730 println!(" See https://github.com/rust-lang/rust/issues/44229 for details.");
733 println!("WARNING: rendering difference in `{}`", concise_str(text));
734 println!(" --> {}:{}:{}", span.filename, span.loline, span.locol);
738 pub fn render_difference(diff: &html_diff::Difference,
739 intro_msg: &mut bool,
743 html_diff::Difference::NodeType { ref elem, ref opposite_elem } => {
744 print_message(&format!(" {} Types differ: expected: `{}`, found: `{}`",
745 elem.path, elem.element_name, opposite_elem.element_name),
746 intro_msg, span, text);
748 html_diff::Difference::NodeName { ref elem, ref opposite_elem } => {
749 print_message(&format!(" {} Tags differ: expected: `{}`, found: `{}`",
750 elem.path, elem.element_name, opposite_elem.element_name),
751 intro_msg, span, text);
753 html_diff::Difference::NodeAttributes { ref elem,
755 ref opposite_elem_attributes,
757 print_message(&format!(" {} Attributes differ in `{}`: expected: `{:?}`, \
759 elem.path, elem.element_name, elem_attributes,
760 opposite_elem_attributes),
761 intro_msg, span, text);
763 html_diff::Difference::NodeText { ref elem, ref elem_text, ref opposite_elem_text, .. } => {
764 if elem_text.split("\n")
765 .zip(opposite_elem_text.split("\n"))
766 .any(|(a, b)| a.trim() != b.trim()) {
767 let (s1, s2) = concise_compared_strs(elem_text, opposite_elem_text);
768 print_message(&format!(" {} Text differs:\n expected: `{}`\n \
771 intro_msg, span, text);
774 html_diff::Difference::NotPresent { ref elem, ref opposite_elem } => {
775 if let Some(ref elem) = *elem {
776 print_message(&format!(" {} One element is missing: expected: `{}`",
777 elem.path, elem.element_name),
778 intro_msg, span, text);
779 } else if let Some(ref elem) = *opposite_elem {
780 if elem.element_name.is_empty() {
781 print_message(&format!(" {} One element is missing: expected: `{}`",
782 elem.path, concise_str(&elem.element_content)),
783 intro_msg, span, text);
785 print_message(&format!(" {} Unexpected element `{}`: found: `{}`",
786 elem.path, elem.element_name,
787 concise_str(&elem.element_content)),
788 intro_msg, span, text);
795 /// Build the search index from the collected metadata
796 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
797 let mut nodeid_to_pathid = FxHashMap();
798 let mut crate_items = Vec::with_capacity(cache.search_index.len());
799 let mut crate_paths = Vec::<Json>::new();
801 let Cache { ref mut search_index,
802 ref orphan_impl_items,
803 ref mut paths, .. } = *cache;
805 // Attach all orphan items to the type's definition if the type
806 // has since been learned.
807 for &(did, ref item) in orphan_impl_items {
808 if let Some(&(ref fqp, _)) = paths.get(&did) {
809 search_index.push(IndexItem {
811 name: item.name.clone().unwrap(),
812 path: fqp[..fqp.len() - 1].join("::"),
813 desc: plain_summary_line(item.doc_value()),
816 search_type: get_index_search_type(&item),
821 // Reduce `NodeId` in paths into smaller sequential numbers,
822 // and prune the paths that do not appear in the index.
823 let mut lastpath = String::new();
824 let mut lastpathid = 0usize;
826 for item in search_index {
827 item.parent_idx = item.parent.map(|nodeid| {
828 if nodeid_to_pathid.contains_key(&nodeid) {
829 *nodeid_to_pathid.get(&nodeid).unwrap()
831 let pathid = lastpathid;
832 nodeid_to_pathid.insert(nodeid, pathid);
835 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
836 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
841 // Omit the parent path if it is same to that of the prior item.
842 if lastpath == item.path {
845 lastpath = item.path.clone();
847 crate_items.push(item.to_json());
850 let crate_doc = krate.module.as_ref().map(|module| {
851 plain_summary_line(module.doc_value())
852 }).unwrap_or(String::new());
854 let mut crate_data = BTreeMap::new();
855 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
856 crate_data.insert("items".to_owned(), Json::Array(crate_items));
857 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
859 // Collect the index into a string
860 format!("searchIndex[{}] = {};",
861 as_json(&krate.name),
862 Json::Object(crate_data))
865 fn write_shared(cx: &Context,
866 krate: &clean::Crate,
868 search_index: String) -> Result<(), Error> {
869 // Write out the shared files. Note that these are shared among all rustdoc
870 // docs placed in the output directory, so this needs to be a synchronized
871 // operation with respect to all other rustdocs running around.
872 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
874 // Add all the static files. These may already exist, but we just
875 // overwrite them anyway to make sure that they're fresh and up-to-date.
877 write(cx.dst.join("rustdoc.css"),
878 include_bytes!("static/rustdoc.css"))?;
880 // To avoid "main.css" to be overwritten, we'll first run over the received themes and only
881 // then we'll run over the "official" styles.
882 let mut themes: HashSet<String> = HashSet::new();
884 for entry in &cx.shared.themes {
885 let mut content = Vec::with_capacity(100000);
887 let mut f = try_err!(File::open(&entry), &entry);
888 try_err!(f.read_to_end(&mut content), &entry);
889 write(cx.dst.join(try_none!(entry.file_name(), &entry)), content.as_slice())?;
890 themes.insert(try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry).to_owned());
893 write(cx.dst.join("brush.svg"),
894 include_bytes!("static/brush.svg"))?;
895 write(cx.dst.join("main.css"),
896 include_bytes!("static/themes/main.css"))?;
897 themes.insert("main".to_owned());
898 write(cx.dst.join("dark.css"),
899 include_bytes!("static/themes/dark.css"))?;
900 themes.insert("dark".to_owned());
902 let mut themes: Vec<&String> = themes.iter().collect();
904 // To avoid theme switch latencies as much as possible, we put everything theme related
905 // at the beginning of the html files into another js file.
906 write(cx.dst.join("theme.js"), format!(
907 r#"var themes = document.getElementById("theme-choices");
908 var themePicker = document.getElementById("theme-picker");
909 themePicker.onclick = function() {{
910 if (themes.style.display === "block") {{
911 themes.style.display = "none";
912 themePicker.style.borderBottomRightRadius = "3px";
913 themePicker.style.borderBottomLeftRadius = "3px";
915 themes.style.display = "block";
916 themePicker.style.borderBottomRightRadius = "0";
917 themePicker.style.borderBottomLeftRadius = "0";
920 [{}].forEach(function(item) {{
921 var but = document.createElement('button');
922 but.innerHTML = item;
923 but.onclick = function(el) {{
924 switchTheme(currentTheme, mainTheme, item);
926 themes.appendChild(but);
929 .map(|s| format!("\"{}\"", s))
930 .collect::<Vec<String>>()
931 .join(",")).as_bytes())?;
933 write(cx.dst.join("main.js"), include_bytes!("static/main.js"))?;
934 write(cx.dst.join("storage.js"), include_bytes!("static/storage.js"))?;
936 if let Some(ref css) = cx.shared.css_file_extension {
937 let out = cx.dst.join("theme.css");
938 try_err!(fs::copy(css, out), css);
940 write(cx.dst.join("normalize.css"),
941 include_bytes!("static/normalize.css"))?;
942 write(cx.dst.join("FiraSans-Regular.woff"),
943 include_bytes!("static/FiraSans-Regular.woff"))?;
944 write(cx.dst.join("FiraSans-Medium.woff"),
945 include_bytes!("static/FiraSans-Medium.woff"))?;
946 write(cx.dst.join("FiraSans-LICENSE.txt"),
947 include_bytes!("static/FiraSans-LICENSE.txt"))?;
948 write(cx.dst.join("Heuristica-Italic.woff"),
949 include_bytes!("static/Heuristica-Italic.woff"))?;
950 write(cx.dst.join("Heuristica-LICENSE.txt"),
951 include_bytes!("static/Heuristica-LICENSE.txt"))?;
952 write(cx.dst.join("SourceSerifPro-Regular.woff"),
953 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
954 write(cx.dst.join("SourceSerifPro-Bold.woff"),
955 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
956 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
957 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
958 write(cx.dst.join("SourceCodePro-Regular.woff"),
959 include_bytes!("static/SourceCodePro-Regular.woff"))?;
960 write(cx.dst.join("SourceCodePro-Semibold.woff"),
961 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
962 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
963 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
964 write(cx.dst.join("LICENSE-MIT.txt"),
965 include_bytes!("static/LICENSE-MIT.txt"))?;
966 write(cx.dst.join("LICENSE-APACHE.txt"),
967 include_bytes!("static/LICENSE-APACHE.txt"))?;
968 write(cx.dst.join("COPYRIGHT.txt"),
969 include_bytes!("static/COPYRIGHT.txt"))?;
971 fn collect(path: &Path, krate: &str,
972 key: &str) -> io::Result<Vec<String>> {
973 let mut ret = Vec::new();
975 for line in BufReader::new(File::open(path)?).lines() {
977 if !line.starts_with(key) {
980 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
983 ret.push(line.to_string());
989 // Update the search index
990 let dst = cx.dst.join("search-index.js");
991 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
992 all_indexes.push(search_index);
993 // Sort the indexes by crate so the file will be generated identically even
994 // with rustdoc running in parallel.
996 let mut w = try_err!(File::create(&dst), &dst);
997 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
998 for index in &all_indexes {
999 try_err!(writeln!(&mut w, "{}", *index), &dst);
1001 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
1003 // Update the list of all implementors for traits
1004 let dst = cx.dst.join("implementors");
1005 for (&did, imps) in &cache.implementors {
1006 // Private modules can leak through to this phase of rustdoc, which
1007 // could contain implementations for otherwise private types. In some
1008 // rare cases we could find an implementation for an item which wasn't
1009 // indexed, so we just skip this step in that case.
1011 // FIXME: this is a vague explanation for why this can't be a `get`, in
1012 // theory it should be...
1013 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1015 None => match cache.external_paths.get(&did) {
1021 let mut have_impls = false;
1022 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1024 // If the trait and implementation are in the same crate, then
1025 // there's no need to emit information about it (there's inlining
1026 // going on). If they're in different crates then the crate defining
1027 // the trait will be interested in our implementation.
1028 if imp.impl_item.def_id.krate == did.krate { continue }
1029 // If the implementation is from another crate then that crate
1031 if !imp.impl_item.def_id.is_local() { continue }
1033 write!(implementors, "{},", as_json(&imp.inner_impl().to_string())).unwrap();
1035 implementors.push_str("];");
1037 // Only create a js file if we have impls to add to it. If the trait is
1038 // documented locally though we always create the file to avoid dead
1040 if !have_impls && !cache.paths.contains_key(&did) {
1044 let mut mydst = dst.clone();
1045 for part in &remote_path[..remote_path.len() - 1] {
1048 try_err!(fs::create_dir_all(&mydst), &mydst);
1049 mydst.push(&format!("{}.{}.js",
1050 remote_item_type.css_class(),
1051 remote_path[remote_path.len() - 1]));
1053 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1054 all_implementors.push(implementors);
1055 // Sort the implementors by crate so the file will be generated
1056 // identically even with rustdoc running in parallel.
1057 all_implementors.sort();
1059 let mut f = try_err!(File::create(&mydst), &mydst);
1060 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1061 for implementor in &all_implementors {
1062 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1064 try_err!(writeln!(&mut f, "{}", r"
1065 if (window.register_implementors) {
1066 window.register_implementors(implementors);
1068 window.pending_implementors = implementors;
1071 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1076 fn render_sources(dst: &Path, scx: &mut SharedContext,
1077 krate: clean::Crate) -> Result<clean::Crate, Error> {
1078 info!("emitting source files");
1079 let dst = dst.join("src").join(&krate.name);
1080 try_err!(fs::create_dir_all(&dst), &dst);
1081 let mut folder = SourceCollector {
1085 Ok(folder.fold_crate(krate))
1088 /// Writes the entire contents of a string to a destination, not attempting to
1089 /// catch any errors.
1090 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1091 Ok(try_err!(fs::write(&dst, contents), &dst))
1094 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1095 /// things like ".." to components which preserve the "top down" hierarchy of a
1096 /// static HTML tree. Each component in the cleaned path will be passed as an
1097 /// argument to `f`. The very last component of the path (ie the file name) will
1098 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1099 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1100 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1101 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1104 // make it relative, if possible
1105 let p = p.strip_prefix(src_root).unwrap_or(p);
1107 let mut iter = p.components().peekable();
1109 while let Some(c) = iter.next() {
1110 if !keep_filename && iter.peek().is_none() {
1115 Component::ParentDir => f("up"),
1116 Component::Normal(c) => f(c.to_str().unwrap()),
1122 /// Attempts to find where an external crate is located, given that we're
1123 /// rendering in to the specified source destination.
1124 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1125 // See if there's documentation generated into the local directory
1126 let local_location = dst.join(&e.name);
1127 if local_location.is_dir() {
1131 // Failing that, see if there's an attribute specifying where to find this
1133 e.attrs.lists("doc")
1134 .filter(|a| a.check_name("html_root_url"))
1135 .filter_map(|a| a.value_str())
1137 let mut url = url.to_string();
1138 if !url.ends_with("/") {
1142 }).next().unwrap_or(Unknown) // Well, at least we tried.
1145 impl<'a> DocFolder for SourceCollector<'a> {
1146 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1147 // If we're including source files, and we haven't seen this file yet,
1148 // then we need to render it out to the filesystem.
1149 if self.scx.include_sources
1150 // skip all invalid or macro spans
1151 && item.source.filename.is_real()
1152 // skip non-local items
1153 && item.def_id.is_local() {
1155 // If it turns out that we couldn't read this file, then we probably
1156 // can't read any of the files (generating html output from json or
1157 // something like that), so just don't include sources for the
1158 // entire crate. The other option is maintaining this mapping on a
1159 // per-file basis, but that's probably not worth it...
1161 .include_sources = match self.emit_source(&item.source.filename) {
1164 println!("warning: source code was requested to be rendered, \
1165 but processing `{}` had an error: {}",
1166 item.source.filename, e);
1167 println!(" skipping rendering of source code");
1172 self.fold_item_recur(item)
1176 impl<'a> SourceCollector<'a> {
1177 /// Renders the given filename into its corresponding HTML source file.
1178 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1179 let p = match *filename {
1180 FileName::Real(ref file) => file,
1183 if self.scx.local_sources.contains_key(&**p) {
1184 // We've already emitted this source
1188 let contents = fs::read_string(&p)?;
1190 // Remove the utf-8 BOM if any
1191 let contents = if contents.starts_with("\u{feff}") {
1197 // Create the intermediate directories
1198 let mut cur = self.dst.clone();
1199 let mut root_path = String::from("../../");
1200 let mut href = String::new();
1201 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1202 cur.push(component);
1203 fs::create_dir_all(&cur).unwrap();
1204 root_path.push_str("../");
1205 href.push_str(component);
1208 let mut fname = p.file_name().expect("source has no filename")
1210 fname.push(".html");
1212 href.push_str(&fname.to_string_lossy());
1214 let mut w = BufWriter::new(File::create(&cur)?);
1215 let title = format!("{} -- source", cur.file_name().unwrap()
1216 .to_string_lossy());
1217 let desc = format!("Source to the Rust file `{}`.", filename);
1218 let page = layout::Page {
1220 css_class: "source",
1221 root_path: &root_path,
1223 keywords: BASIC_KEYWORDS,
1225 layout::render(&mut w, &self.scx.layout,
1226 &page, &(""), &Source(contents),
1227 self.scx.css_file_extension.is_some(),
1230 self.scx.local_sources.insert(p.clone(), href);
1235 impl DocFolder for Cache {
1236 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1237 // If this is a stripped module,
1238 // we don't want it or its children in the search index.
1239 let orig_stripped_mod = match item.inner {
1240 clean::StrippedItem(box clean::ModuleItem(..)) => {
1241 mem::replace(&mut self.stripped_mod, true)
1243 _ => self.stripped_mod,
1246 // If the impl is from a masked crate or references something from a
1247 // masked crate then remove it completely.
1248 if let clean::ImplItem(ref i) = item.inner {
1249 if self.masked_crates.contains(&item.def_id.krate) ||
1250 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1251 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1256 // Register any generics to their corresponding string. This is used
1257 // when pretty-printing types.
1258 if let Some(generics) = item.inner.generics() {
1259 self.generics(generics);
1262 // Propagate a trait method's documentation to all implementors of the
1264 if let clean::TraitItem(ref t) = item.inner {
1265 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1268 // Collect all the implementors of traits.
1269 if let clean::ImplItem(ref i) = item.inner {
1270 if let Some(did) = i.trait_.def_id() {
1271 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1272 impl_item: item.clone(),
1277 // Index this method for searching later on.
1278 if let Some(ref s) = item.name {
1279 let (parent, is_inherent_impl_item) = match item.inner {
1280 clean::StrippedItem(..) => ((None, None), false),
1281 clean::AssociatedConstItem(..) |
1282 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1283 // skip associated items in trait impls
1284 ((None, None), false)
1286 clean::AssociatedTypeItem(..) |
1287 clean::TyMethodItem(..) |
1288 clean::StructFieldItem(..) |
1289 clean::VariantItem(..) => {
1290 ((Some(*self.parent_stack.last().unwrap()),
1291 Some(&self.stack[..self.stack.len() - 1])),
1294 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1295 if self.parent_stack.is_empty() {
1296 ((None, None), false)
1298 let last = self.parent_stack.last().unwrap();
1300 let path = match self.paths.get(&did) {
1301 // The current stack not necessarily has correlation
1302 // for where the type was defined. On the other
1303 // hand, `paths` always has the right
1304 // information if present.
1305 Some(&(ref fqp, ItemType::Trait)) |
1306 Some(&(ref fqp, ItemType::Struct)) |
1307 Some(&(ref fqp, ItemType::Union)) |
1308 Some(&(ref fqp, ItemType::Enum)) =>
1309 Some(&fqp[..fqp.len() - 1]),
1310 Some(..) => Some(&*self.stack),
1313 ((Some(*last), path), true)
1316 _ => ((None, Some(&*self.stack)), false)
1320 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1321 debug_assert!(!item.is_stripped());
1323 // A crate has a module at its root, containing all items,
1324 // which should not be indexed. The crate-item itself is
1325 // inserted later on when serializing the search-index.
1326 if item.def_id.index != CRATE_DEF_INDEX {
1327 self.search_index.push(IndexItem {
1329 name: s.to_string(),
1330 path: path.join("::").to_string(),
1331 desc: plain_summary_line(item.doc_value()),
1334 search_type: get_index_search_type(&item),
1338 (Some(parent), None) if is_inherent_impl_item => {
1339 // We have a parent, but we don't know where they're
1340 // defined yet. Wait for later to index this item.
1341 self.orphan_impl_items.push((parent, item.clone()));
1347 // Keep track of the fully qualified path for this item.
1348 let pushed = match item.name {
1349 Some(ref n) if !n.is_empty() => {
1350 self.stack.push(n.to_string());
1357 clean::StructItem(..) | clean::EnumItem(..) |
1358 clean::TypedefItem(..) | clean::TraitItem(..) |
1359 clean::FunctionItem(..) | clean::ModuleItem(..) |
1360 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1361 clean::ConstantItem(..) | clean::StaticItem(..) |
1362 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1363 if !self.stripped_mod => {
1364 // Re-exported items mean that the same id can show up twice
1365 // in the rustdoc ast that we're looking at. We know,
1366 // however, that a re-exported item doesn't show up in the
1367 // `public_items` map, so we can skip inserting into the
1368 // paths map if there was already an entry present and we're
1369 // not a public item.
1371 !self.paths.contains_key(&item.def_id) ||
1372 self.access_levels.is_public(item.def_id)
1374 self.paths.insert(item.def_id,
1375 (self.stack.clone(), item.type_()));
1378 // Link variants to their parent enum because pages aren't emitted
1379 // for each variant.
1380 clean::VariantItem(..) if !self.stripped_mod => {
1381 let mut stack = self.stack.clone();
1383 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1386 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1387 self.paths.insert(item.def_id, (self.stack.clone(),
1394 // Maintain the parent stack
1395 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1396 let parent_pushed = match item.inner {
1397 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1398 clean::StructItem(..) | clean::UnionItem(..) => {
1399 self.parent_stack.push(item.def_id);
1400 self.parent_is_trait_impl = false;
1403 clean::ImplItem(ref i) => {
1404 self.parent_is_trait_impl = i.trait_.is_some();
1406 clean::ResolvedPath{ did, .. } => {
1407 self.parent_stack.push(did);
1411 let prim_did = t.primitive_type().and_then(|t| {
1412 self.primitive_locations.get(&t).cloned()
1416 self.parent_stack.push(did);
1427 // Once we've recursively found all the generics, hoard off all the
1428 // implementations elsewhere.
1429 let ret = self.fold_item_recur(item).and_then(|item| {
1430 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1431 // Figure out the id of this impl. This may map to a
1432 // primitive rather than always to a struct/enum.
1433 // Note: matching twice to restrict the lifetime of the `i` borrow.
1434 let mut dids = FxHashSet();
1435 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1437 clean::ResolvedPath { did, .. } |
1438 clean::BorrowedRef {
1439 type_: box clean::ResolvedPath { did, .. }, ..
1444 let did = t.primitive_type().and_then(|t| {
1445 self.primitive_locations.get(&t).cloned()
1448 if let Some(did) = did {
1454 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1455 for bound in generics {
1456 if let Some(did) = bound.def_id() {
1465 self.impls.entry(did).or_insert(vec![]).push(Impl {
1466 impl_item: item.clone(),
1475 if pushed { self.stack.pop().unwrap(); }
1476 if parent_pushed { self.parent_stack.pop().unwrap(); }
1477 self.stripped_mod = orig_stripped_mod;
1478 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1484 fn generics(&mut self, generics: &clean::Generics) {
1485 for param in &generics.params {
1486 if let clean::GenericParam::Type(ref typ) = *param {
1487 self.typarams.insert(typ.did, typ.name.clone());
1494 /// String representation of how to get back to the root path of the 'doc/'
1495 /// folder in terms of a relative URL.
1496 fn root_path(&self) -> String {
1497 repeat("../").take(self.current.len()).collect::<String>()
1500 /// Recurse in the directory structure and change the "root path" to make
1501 /// sure it always points to the top (relatively).
1502 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1503 F: FnOnce(&mut Context) -> T,
1506 panic!("Unexpected empty destination: {:?}", self.current);
1508 let prev = self.dst.clone();
1510 self.current.push(s);
1512 info!("Recursing into {}", self.dst.display());
1516 info!("Recursed; leaving {}", self.dst.display());
1518 // Go back to where we were at
1520 self.current.pop().unwrap();
1525 /// Main method for rendering a crate.
1527 /// This currently isn't parallelized, but it'd be pretty easy to add
1528 /// parallelization to this function.
1529 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1530 let mut item = match krate.module.take() {
1532 None => return Ok(()),
1534 item.name = Some(krate.name);
1536 // Render the crate documentation
1537 let mut work = vec![(self, item)];
1539 while let Some((mut cx, item)) = work.pop() {
1540 cx.item(item, |cx, item| {
1541 work.push((cx.clone(), item))
1547 fn render_item(&self,
1548 writer: &mut io::Write,
1552 // A little unfortunate that this is done like this, but it sure
1553 // does make formatting *a lot* nicer.
1554 CURRENT_LOCATION_KEY.with(|slot| {
1555 *slot.borrow_mut() = self.current.clone();
1558 let mut title = if it.is_primitive() {
1559 // No need to include the namespace for primitive types
1562 self.current.join("::")
1565 if !title.is_empty() {
1566 title.push_str("::");
1568 title.push_str(it.name.as_ref().unwrap());
1570 title.push_str(" - Rust");
1571 let tyname = it.type_().css_class();
1572 let desc = if it.is_crate() {
1573 format!("API documentation for the Rust `{}` crate.",
1574 self.shared.layout.krate)
1576 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1577 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1579 let keywords = make_item_keywords(it);
1580 let page = layout::Page {
1582 root_path: &self.root_path(),
1585 keywords: &keywords,
1590 if !self.render_redirect_pages {
1591 layout::render(writer, &self.shared.layout, &page,
1592 &Sidebar{ cx: self, item: it },
1593 &Item{ cx: self, item: it },
1594 self.shared.css_file_extension.is_some(),
1595 &self.shared.themes)?;
1597 let mut url = self.root_path();
1598 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1599 for name in &names[..names.len() - 1] {
1603 url.push_str(&item_path(ty, names.last().unwrap()));
1604 layout::redirect(writer, &url)?;
1610 /// Non-parallelized version of rendering an item. This will take the input
1611 /// item, render its contents, and then invoke the specified closure with
1612 /// all sub-items which need to be rendered.
1614 /// The rendering driver uses this closure to queue up more work.
1615 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1616 F: FnMut(&mut Context, clean::Item),
1618 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1619 // if they contain impls for public types. These modules can also
1620 // contain items such as publicly re-exported structures.
1622 // External crates will provide links to these structures, so
1623 // these modules are recursed into, but not rendered normally
1624 // (a flag on the context).
1625 if !self.render_redirect_pages {
1626 self.render_redirect_pages = item.is_stripped();
1630 // modules are special because they add a namespace. We also need to
1631 // recurse into the items of the module as well.
1632 let name = item.name.as_ref().unwrap().to_string();
1633 let mut item = Some(item);
1634 self.recurse(name, |this| {
1635 let item = item.take().unwrap();
1637 let mut buf = Vec::new();
1638 this.render_item(&mut buf, &item, false).unwrap();
1639 // buf will be empty if the module is stripped and there is no redirect for it
1640 if !buf.is_empty() {
1641 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1642 let joint_dst = this.dst.join("index.html");
1643 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1644 try_err!(dst.write_all(&buf), &joint_dst);
1647 let m = match item.inner {
1648 clean::StrippedItem(box clean::ModuleItem(m)) |
1649 clean::ModuleItem(m) => m,
1653 // Render sidebar-items.js used throughout this module.
1654 if !this.render_redirect_pages {
1655 let items = this.build_sidebar_items(&m);
1656 let js_dst = this.dst.join("sidebar-items.js");
1657 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1658 try_err!(write!(&mut js_out, "initSidebarItems({});",
1659 as_json(&items)), &js_dst);
1662 for item in m.items {
1668 } else if item.name.is_some() {
1669 let mut buf = Vec::new();
1670 self.render_item(&mut buf, &item, true).unwrap();
1671 // buf will be empty if the item is stripped and there is no redirect for it
1672 if !buf.is_empty() {
1673 let name = item.name.as_ref().unwrap();
1674 let item_type = item.type_();
1675 let file_name = &item_path(item_type, name);
1676 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1677 let joint_dst = self.dst.join(file_name);
1678 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1679 try_err!(dst.write_all(&buf), &joint_dst);
1681 // Redirect from a sane URL using the namespace to Rustdoc's
1682 // URL for the page.
1683 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1684 let redir_dst = self.dst.join(redir_name);
1685 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1688 let mut redirect_out = BufWriter::new(redirect_out);
1689 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1692 // If the item is a macro, redirect from the old macro URL (with !)
1693 // to the new one (without).
1694 // FIXME(#35705) remove this redirect.
1695 if item_type == ItemType::Macro {
1696 let redir_name = format!("{}.{}!.html", item_type, name);
1697 let redir_dst = self.dst.join(redir_name);
1698 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1699 let mut redirect_out = BufWriter::new(redirect_out);
1700 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1707 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1708 // BTreeMap instead of HashMap to get a sorted output
1709 let mut map = BTreeMap::new();
1710 for item in &m.items {
1711 if item.is_stripped() { continue }
1713 let short = item.type_().css_class();
1714 let myname = match item.name {
1716 Some(ref s) => s.to_string(),
1718 let short = short.to_string();
1719 map.entry(short).or_insert(vec![])
1720 .push((myname, Some(plain_summary_line(item.doc_value()))));
1723 if self.shared.sort_modules_alphabetically {
1724 for (_, items) in &mut map {
1733 /// Generate a url appropriate for an `href` attribute back to the source of
1736 /// The url generated, when clicked, will redirect the browser back to the
1737 /// original source code.
1739 /// If `None` is returned, then a source link couldn't be generated. This
1740 /// may happen, for example, with externally inlined items where the source
1741 /// of their crate documentation isn't known.
1742 fn src_href(&self) -> Option<String> {
1743 let mut root = self.cx.root_path();
1745 let cache = cache();
1746 let mut path = String::new();
1748 // We can safely ignore macros from other libraries
1749 let file = match self.item.source.filename {
1750 FileName::Real(ref path) => path,
1754 let (krate, path) = if self.item.def_id.is_local() {
1755 if let Some(path) = self.cx.shared.local_sources.get(file) {
1756 (&self.cx.shared.layout.krate, path)
1761 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1762 Some(&(ref name, ref src, Local)) => (name, src),
1763 Some(&(ref name, ref src, Remote(ref s))) => {
1764 root = s.to_string();
1767 Some(&(_, _, Unknown)) | None => return None,
1770 clean_srcpath(&src_root, file, false, |component| {
1771 path.push_str(component);
1774 let mut fname = file.file_name().expect("source has no filename")
1776 fname.push(".html");
1777 path.push_str(&fname.to_string_lossy());
1781 let lines = if self.item.source.loline == self.item.source.hiline {
1782 format!("{}", self.item.source.loline)
1784 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1786 Some(format!("{root}src/{krate}/{path}#{lines}",
1787 root = Escape(&root),
1794 impl<'a> fmt::Display for Item<'a> {
1795 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1796 debug_assert!(!self.item.is_stripped());
1797 // Write the breadcrumb trail header for the top
1798 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1799 match self.item.inner {
1800 clean::ModuleItem(ref m) => if m.is_crate {
1801 write!(fmt, "Crate ")?;
1803 write!(fmt, "Module ")?;
1805 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1806 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1807 clean::StructItem(..) => write!(fmt, "Struct ")?,
1808 clean::UnionItem(..) => write!(fmt, "Union ")?,
1809 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1810 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1811 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1812 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1813 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1814 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1815 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1817 // We don't generate pages for any other type.
1821 if !self.item.is_primitive() {
1822 let cur = &self.cx.current;
1823 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1824 for (i, component) in cur.iter().enumerate().take(amt) {
1825 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1826 repeat("../").take(cur.len() - i - 1)
1827 .collect::<String>(),
1831 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1832 self.item.type_(), self.item.name.as_ref().unwrap())?;
1834 write!(fmt, "</span>")?; // in-band
1835 write!(fmt, "<span class='out-of-band'>")?;
1836 if let Some(version) = self.item.stable_since() {
1837 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1841 r##"<span id='render-detail'>
1842 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1843 [<span class='inner'>−</span>]
1849 // When this item is part of a `pub use` in a downstream crate, the
1850 // [src] link in the downstream documentation will actually come back to
1851 // this page, and this link will be auto-clicked. The `id` attribute is
1852 // used to find the link to auto-click.
1853 if self.cx.shared.include_sources && !self.item.is_primitive() {
1854 if let Some(l) = self.src_href() {
1855 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1856 l, "goto source code")?;
1860 write!(fmt, "</span>")?; // out-of-band
1862 write!(fmt, "</h1>\n")?;
1864 match self.item.inner {
1865 clean::ModuleItem(ref m) => {
1866 item_module(fmt, self.cx, self.item, &m.items)
1868 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1869 item_function(fmt, self.cx, self.item, f),
1870 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1871 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1872 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1873 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1874 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1875 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1876 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1877 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1878 item_static(fmt, self.cx, self.item, i),
1879 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1880 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1882 // We don't generate pages for any other type.
1889 fn item_path(ty: ItemType, name: &str) -> String {
1891 ItemType::Module => format!("{}/index.html", name),
1892 _ => format!("{}.{}.html", ty.css_class(), name),
1896 fn full_path(cx: &Context, item: &clean::Item) -> String {
1897 let mut s = cx.current.join("::");
1899 s.push_str(item.name.as_ref().unwrap());
1903 fn shorter<'a>(s: Option<&'a str>) -> String {
1905 Some(s) => s.lines()
1906 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1908 (*line).chars().any(|chr|{
1909 !chr.is_whitespace()
1911 }).collect::<Vec<_>>().join("\n"),
1912 None => "".to_string()
1917 fn plain_summary_line(s: Option<&str>) -> String {
1918 let line = shorter(s).replace("\n", " ");
1919 markdown::plain_summary_line(&line[..])
1922 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1923 if let Some(ref name) = item.name {
1924 info!("Documenting {}", name);
1926 document_stability(w, cx, item)?;
1927 let prefix = render_assoc_const_value(item);
1928 document_full(w, item, cx, &prefix)?;
1932 /// Render md_text as markdown. Warns the user if there are difference in
1933 /// rendering between Pulldown and Hoedown.
1934 fn render_markdown(w: &mut fmt::Formatter,
1936 links: Vec<(String, String)>,
1938 render_type: RenderType,
1940 scx: &SharedContext)
1942 let (hoedown_output, pulldown_output) =
1943 render_text(|ty| format!("{}", Markdown(md_text, &links, ty)));
1944 let mut differences = html_diff::get_differences(&pulldown_output, &hoedown_output);
1945 differences.retain(|s| {
1947 html_diff::Difference::NodeText { ref elem_text,
1948 ref opposite_elem_text,
1950 if elem_text.split_whitespace().eq(opposite_elem_text.split_whitespace()) => {
1957 if !differences.is_empty() {
1958 scx.markdown_warnings.borrow_mut().push((span, md_text.to_owned(), differences));
1961 write!(w, "<div class='docblock'>{}{}</div>",
1963 if render_type == RenderType::Pulldown { pulldown_output } else { hoedown_output })
1966 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1967 cx: &Context, prefix: &str) -> fmt::Result {
1968 if let Some(s) = item.doc_value() {
1969 let markdown = if s.contains('\n') {
1970 format!("{} [Read more]({})",
1971 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1973 format!("{}", &plain_summary_line(Some(s)))
1978 item.source.clone(),
1982 } else if !prefix.is_empty() {
1983 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1988 fn render_assoc_const_value(item: &clean::Item) -> String {
1990 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1991 highlight::render_with_highlighting(
1992 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2003 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2004 cx: &Context, prefix: &str) -> fmt::Result {
2005 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2006 debug!("Doc block: =====\n{}\n=====", s);
2010 item.source.clone(),
2014 } else if !prefix.is_empty() {
2015 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2020 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2021 let stabilities = short_stability(item, cx, true);
2022 if !stabilities.is_empty() {
2023 write!(w, "<div class='stability'>")?;
2024 for stability in stabilities {
2025 write!(w, "{}", stability)?;
2027 write!(w, "</div>")?;
2032 fn name_key(name: &str) -> (&str, u64, usize) {
2033 // find number at end
2034 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2036 // count leading zeroes
2038 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2040 // sort leading zeroes last
2041 let num_zeroes = after_zeroes - split;
2043 match name[split..].parse() {
2044 Ok(n) => (&name[..split], n, num_zeroes),
2045 Err(_) => (name, 0, num_zeroes),
2049 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2050 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2051 document(w, cx, item)?;
2053 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped())
2054 .collect::<Vec<usize>>();
2056 // the order of item types in the listing
2057 fn reorder(ty: ItemType) -> u8 {
2059 ItemType::ExternCrate => 0,
2060 ItemType::Import => 1,
2061 ItemType::Primitive => 2,
2062 ItemType::Module => 3,
2063 ItemType::Macro => 4,
2064 ItemType::Struct => 5,
2065 ItemType::Enum => 6,
2066 ItemType::Constant => 7,
2067 ItemType::Static => 8,
2068 ItemType::Trait => 9,
2069 ItemType::Function => 10,
2070 ItemType::Typedef => 12,
2071 ItemType::Union => 13,
2076 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2077 let ty1 = i1.type_();
2078 let ty2 = i2.type_();
2080 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2082 let s1 = i1.stability.as_ref().map(|s| s.level);
2083 let s2 = i2.stability.as_ref().map(|s| s.level);
2085 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2086 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2089 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2090 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2091 name_key(lhs).cmp(&name_key(rhs))
2094 if cx.shared.sort_modules_alphabetically {
2095 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2097 // This call is to remove re-export duplicates in cases such as:
2102 // pub trait Double { fn foo(); }
2106 // pub use foo::bar::*;
2110 // `Double` will appear twice in the generated docs.
2112 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2113 // can be identical even if the elements are different (mostly in imports).
2114 // So in case this is an import, we keep everything by adding a "unique id"
2115 // (which is the position in the vector).
2116 indices.dedup_by_key(|i| (items[*i].def_id,
2117 if items[*i].name.as_ref().is_some() {
2118 Some(full_path(cx, &items[*i]).clone())
2123 if items[*i].is_import() {
2129 debug!("{:?}", indices);
2130 let mut curty = None;
2131 for &idx in &indices {
2132 let myitem = &items[idx];
2133 if myitem.is_stripped() {
2137 let myty = Some(myitem.type_());
2138 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2139 // Put `extern crate` and `use` re-exports in the same section.
2141 } else if myty != curty {
2142 if curty.is_some() {
2143 write!(w, "</table>")?;
2146 let (short, name) = match myty.unwrap() {
2147 ItemType::ExternCrate |
2148 ItemType::Import => ("reexports", "Re-exports"),
2149 ItemType::Module => ("modules", "Modules"),
2150 ItemType::Struct => ("structs", "Structs"),
2151 ItemType::Union => ("unions", "Unions"),
2152 ItemType::Enum => ("enums", "Enums"),
2153 ItemType::Function => ("functions", "Functions"),
2154 ItemType::Typedef => ("types", "Type Definitions"),
2155 ItemType::Static => ("statics", "Statics"),
2156 ItemType::Constant => ("constants", "Constants"),
2157 ItemType::Trait => ("traits", "Traits"),
2158 ItemType::Impl => ("impls", "Implementations"),
2159 ItemType::TyMethod => ("tymethods", "Type Methods"),
2160 ItemType::Method => ("methods", "Methods"),
2161 ItemType::StructField => ("fields", "Struct Fields"),
2162 ItemType::Variant => ("variants", "Variants"),
2163 ItemType::Macro => ("macros", "Macros"),
2164 ItemType::Primitive => ("primitives", "Primitive Types"),
2165 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2166 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2167 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2169 write!(w, "<h2 id='{id}' class='section-header'>\
2170 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2171 id = derive_id(short.to_owned()), name = name)?;
2174 match myitem.inner {
2175 clean::ExternCrateItem(ref name, ref src) => {
2176 use html::format::HRef;
2180 write!(w, "<tr><td><code>{}extern crate {} as {};",
2181 VisSpace(&myitem.visibility),
2182 HRef::new(myitem.def_id, src),
2186 write!(w, "<tr><td><code>{}extern crate {};",
2187 VisSpace(&myitem.visibility),
2188 HRef::new(myitem.def_id, name))?
2191 write!(w, "</code></td></tr>")?;
2194 clean::ImportItem(ref import) => {
2195 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2196 VisSpace(&myitem.visibility), *import)?;
2200 if myitem.name.is_none() { continue }
2202 let stabilities = short_stability(myitem, cx, false);
2204 let stab_docs = if !stabilities.is_empty() {
2206 .map(|s| format!("[{}]", s))
2207 .collect::<Vec<_>>()
2214 let unsafety_flag = match myitem.inner {
2215 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2216 if func.unsafety == hir::Unsafety::Unsafe => {
2217 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2222 let doc_value = myitem.doc_value().unwrap_or("");
2224 <tr class='{stab} module-item'>
2225 <td><a class=\"{class}\" href=\"{href}\"
2226 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2227 <td class='docblock-short'>
2231 name = *myitem.name.as_ref().unwrap(),
2232 stab_docs = stab_docs,
2233 docs = if cx.render_type == RenderType::Hoedown {
2235 shorter(Some(&Markdown(doc_value, &myitem.links(),
2236 RenderType::Hoedown).to_string())))
2238 format!("{}", MarkdownSummaryLine(doc_value, &myitem.links()))
2240 class = myitem.type_(),
2241 stab = myitem.stability_class().unwrap_or("".to_string()),
2242 unsafety_flag = unsafety_flag,
2243 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2244 title_type = myitem.type_(),
2245 title = full_path(cx, myitem))?;
2250 if curty.is_some() {
2251 write!(w, "</table>")?;
2256 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2257 let mut stability = vec![];
2259 if let Some(stab) = item.stability.as_ref() {
2260 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2261 format!(": {}", stab.deprecated_reason)
2265 if !stab.deprecated_since.is_empty() {
2266 let since = if show_reason {
2267 format!(" since {}", Escape(&stab.deprecated_since))
2271 let text = format!("Deprecated{}{}",
2273 MarkdownHtml(&deprecated_reason, cx.render_type));
2274 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2277 if stab.level == stability::Unstable {
2279 let unstable_extra = match (!stab.feature.is_empty(),
2280 &cx.shared.issue_tracker_base_url,
2282 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2283 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2284 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2285 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2286 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2289 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2292 if stab.unstable_reason.is_empty() {
2293 stability.push(format!("<div class='stab unstable'>\
2294 <span class=microscope>🔬</span> \
2295 This is a nightly-only experimental API. {}\
2299 let text = format!("<summary><span class=microscope>🔬</span> \
2300 This is a nightly-only experimental API. {}\
2303 MarkdownHtml(&stab.unstable_reason, cx.render_type));
2304 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2308 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2311 } else if let Some(depr) = item.deprecation.as_ref() {
2312 let note = if show_reason && !depr.note.is_empty() {
2313 format!(": {}", depr.note)
2317 let since = if show_reason && !depr.since.is_empty() {
2318 format!(" since {}", Escape(&depr.since))
2323 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
2324 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2327 if let Some(ref cfg) = item.attrs.cfg {
2328 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2329 cfg.render_long_html()
2331 cfg.render_short_html()
2338 struct Initializer<'a>(&'a str);
2340 impl<'a> fmt::Display for Initializer<'a> {
2341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2342 let Initializer(s) = *self;
2343 if s.is_empty() { return Ok(()); }
2344 write!(f, "<code> = </code>")?;
2345 write!(f, "<code>{}</code>", Escape(s))
2349 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2350 c: &clean::Constant) -> fmt::Result {
2351 write!(w, "<pre class='rust const'>")?;
2352 render_attributes(w, it)?;
2353 write!(w, "{vis}const \
2354 {name}: {typ}{init}</pre>",
2355 vis = VisSpace(&it.visibility),
2356 name = it.name.as_ref().unwrap(),
2358 init = Initializer(&c.expr))?;
2362 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2363 s: &clean::Static) -> fmt::Result {
2364 write!(w, "<pre class='rust static'>")?;
2365 render_attributes(w, it)?;
2366 write!(w, "{vis}static {mutability}\
2367 {name}: {typ}{init}</pre>",
2368 vis = VisSpace(&it.visibility),
2369 mutability = MutableSpace(s.mutability),
2370 name = it.name.as_ref().unwrap(),
2372 init = Initializer(&s.expr))?;
2376 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2377 f: &clean::Function) -> fmt::Result {
2378 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2379 VisSpace(&it.visibility),
2380 ConstnessSpace(f.constness),
2381 UnsafetySpace(f.unsafety),
2383 it.name.as_ref().unwrap(),
2385 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2386 render_attributes(w, it)?;
2388 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2389 vis = VisSpace(&it.visibility),
2390 constness = ConstnessSpace(f.constness),
2391 unsafety = UnsafetySpace(f.unsafety),
2392 abi = AbiSpace(f.abi),
2393 name = it.name.as_ref().unwrap(),
2394 generics = f.generics,
2395 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2404 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2405 t: &clean::Trait) -> fmt::Result {
2406 let mut bounds = String::new();
2407 let mut bounds_plain = String::new();
2408 if !t.bounds.is_empty() {
2409 if !bounds.is_empty() {
2411 bounds_plain.push(' ');
2413 bounds.push_str(": ");
2414 bounds_plain.push_str(": ");
2415 for (i, p) in t.bounds.iter().enumerate() {
2417 bounds.push_str(" + ");
2418 bounds_plain.push_str(" + ");
2420 bounds.push_str(&format!("{}", *p));
2421 bounds_plain.push_str(&format!("{:#}", *p));
2425 // Output the trait definition
2426 write!(w, "<pre class='rust trait'>")?;
2427 render_attributes(w, it)?;
2428 write!(w, "{}{}{}trait {}{}{}",
2429 VisSpace(&it.visibility),
2430 UnsafetySpace(t.unsafety),
2431 if t.is_auto { "auto " } else { "" },
2432 it.name.as_ref().unwrap(),
2436 if !t.generics.where_predicates.is_empty() {
2437 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2442 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2443 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2444 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2445 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2447 if t.items.is_empty() {
2448 write!(w, "{{ }}")?;
2450 // FIXME: we should be using a derived_id for the Anchors here
2454 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2457 if !types.is_empty() && !consts.is_empty() {
2462 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2465 if !consts.is_empty() && !required.is_empty() {
2468 for (pos, m) in required.iter().enumerate() {
2470 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2473 if pos < required.len() - 1 {
2474 write!(w, "<div class='item-spacer'></div>")?;
2477 if !required.is_empty() && !provided.is_empty() {
2480 for (pos, m) in provided.iter().enumerate() {
2482 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2484 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2485 write!(w, ",\n {{ ... }}\n")?;
2488 write!(w, " {{ ... }}\n")?;
2491 if pos < provided.len() - 1 {
2492 write!(w, "<div class='item-spacer'></div>")?;
2497 write!(w, "</pre>")?;
2499 // Trait documentation
2500 document(w, cx, it)?;
2502 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2504 let name = m.name.as_ref().unwrap();
2505 let item_type = m.type_();
2506 let id = derive_id(format!("{}.{}", item_type, name));
2507 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2508 write!(w, "{extra}<h3 id='{id}' class='method'>\
2509 <span id='{ns_id}' class='invisible'><code>",
2510 extra = render_spotlight_traits(m)?,
2513 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2514 write!(w, "</code>")?;
2515 render_stability_since(w, m, t)?;
2516 write!(w, "</span></h3>")?;
2517 document(w, cx, m)?;
2521 if !types.is_empty() {
2523 <h2 id='associated-types' class='small-section-header'>
2524 Associated Types<a href='#associated-types' class='anchor'></a>
2526 <div class='methods'>
2529 trait_item(w, cx, *t, it)?;
2531 write!(w, "</div>")?;
2534 if !consts.is_empty() {
2536 <h2 id='associated-const' class='small-section-header'>
2537 Associated Constants<a href='#associated-const' class='anchor'></a>
2539 <div class='methods'>
2542 trait_item(w, cx, *t, it)?;
2544 write!(w, "</div>")?;
2547 // Output the documentation for each function individually
2548 if !required.is_empty() {
2550 <h2 id='required-methods' class='small-section-header'>
2551 Required Methods<a href='#required-methods' class='anchor'></a>
2553 <div class='methods'>
2555 for m in &required {
2556 trait_item(w, cx, *m, it)?;
2558 write!(w, "</div>")?;
2560 if !provided.is_empty() {
2562 <h2 id='provided-methods' class='small-section-header'>
2563 Provided Methods<a href='#provided-methods' class='anchor'></a>
2565 <div class='methods'>
2567 for m in &provided {
2568 trait_item(w, cx, *m, it)?;
2570 write!(w, "</div>")?;
2573 // If there are methods directly on this trait object, render them here.
2574 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2576 let cache = cache();
2578 <h2 id='implementors' class='small-section-header'>
2579 Implementors<a href='#implementors' class='anchor'></a>
2581 <ul class='item-list' id='implementors-list'>
2583 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2584 // The DefId is for the first Type found with that name. The bool is
2585 // if any Types with the same name but different DefId have been found.
2586 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2587 for implementor in implementors {
2588 match implementor.inner_impl().for_ {
2589 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2590 clean::BorrowedRef {
2591 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2594 let &mut (prev_did, ref mut has_duplicates) =
2595 implementor_dups.entry(path.last_name()).or_insert((did, false));
2596 if prev_did != did {
2597 *has_duplicates = true;
2604 let (local, foreign) = implementors.iter()
2605 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2606 .map_or(true, |d| cache.paths.contains_key(&d)));
2608 if !foreign.is_empty() {
2610 <h2 id='foreign-impls' class='small-section-header'>
2611 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2615 for implementor in foreign {
2616 let assoc_link = AssocItemLink::GotoSource(
2617 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2619 render_impl(w, cx, &implementor, assoc_link,
2620 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2624 write!(w, "{}", impl_header)?;
2626 for implementor in local {
2628 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2629 write!(w, "<div class='out-of-band'>")?;
2630 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2631 l, "goto source code")?;
2632 write!(w, "</div>")?;
2634 write!(w, "<code>")?;
2635 // If there's already another implementor that has the same abbridged name, use the
2636 // full path, for example in `std::iter::ExactSizeIterator`
2637 let use_absolute = match implementor.inner_impl().for_ {
2638 clean::ResolvedPath { ref path, is_generic: false, .. } |
2639 clean::BorrowedRef {
2640 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2642 } => implementor_dups[path.last_name()].1,
2645 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2646 for it in &implementor.inner_impl().items {
2647 if let clean::TypedefItem(ref tydef, _) = it.inner {
2648 write!(w, "<span class=\"where fmt-newline\"> ")?;
2649 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2650 write!(w, ";</span>")?;
2653 writeln!(w, "</code></li>")?;
2656 // even without any implementations to write in, we still want the heading and list, so the
2657 // implementors javascript file pulled in below has somewhere to write the impls into
2658 write!(w, "{}", impl_header)?;
2660 write!(w, "</ul>")?;
2661 write!(w, r#"<script type="text/javascript" async
2662 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2664 root_path = vec![".."; cx.current.len()].join("/"),
2665 path = if it.def_id.is_local() {
2666 cx.current.join("/")
2668 let (ref path, _) = cache.external_paths[&it.def_id];
2669 path[..path.len() - 1].join("/")
2671 ty = it.type_().css_class(),
2672 name = *it.name.as_ref().unwrap())?;
2676 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2677 use html::item_type::ItemType::*;
2679 let name = it.name.as_ref().unwrap();
2680 let ty = match it.type_() {
2681 Typedef | AssociatedType => AssociatedType,
2685 let anchor = format!("#{}.{}", ty, name);
2687 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2688 AssocItemLink::Anchor(None) => anchor,
2689 AssocItemLink::GotoSource(did, _) => {
2690 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2695 fn assoc_const(w: &mut fmt::Formatter,
2698 _default: Option<&String>,
2699 link: AssocItemLink) -> fmt::Result {
2700 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2701 VisSpace(&it.visibility),
2702 naive_assoc_href(it, link),
2703 it.name.as_ref().unwrap(),
2708 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2709 bounds: &Vec<clean::TyParamBound>,
2710 default: Option<&clean::Type>,
2711 link: AssocItemLink) -> fmt::Result {
2712 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2713 naive_assoc_href(it, link),
2714 it.name.as_ref().unwrap())?;
2715 if !bounds.is_empty() {
2716 write!(w, ": {}", TyParamBounds(bounds))?
2718 if let Some(default) = default {
2719 write!(w, " = {}", default)?;
2724 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2725 ver: Option<&'a str>,
2726 containing_ver: Option<&'a str>) -> fmt::Result {
2727 if let Some(v) = ver {
2728 if containing_ver != ver && v.len() > 0 {
2729 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2736 fn render_stability_since(w: &mut fmt::Formatter,
2738 containing_item: &clean::Item) -> fmt::Result {
2739 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2742 fn render_assoc_item(w: &mut fmt::Formatter,
2744 link: AssocItemLink,
2745 parent: ItemType) -> fmt::Result {
2746 fn method(w: &mut fmt::Formatter,
2748 unsafety: hir::Unsafety,
2749 constness: hir::Constness,
2751 g: &clean::Generics,
2753 link: AssocItemLink,
2756 let name = meth.name.as_ref().unwrap();
2757 let anchor = format!("#{}.{}", meth.type_(), name);
2758 let href = match link {
2759 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2760 AssocItemLink::Anchor(None) => anchor,
2761 AssocItemLink::GotoSource(did, provided_methods) => {
2762 // We're creating a link from an impl-item to the corresponding
2763 // trait-item and need to map the anchored type accordingly.
2764 let ty = if provided_methods.contains(name) {
2770 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2773 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2774 VisSpace(&meth.visibility),
2775 ConstnessSpace(constness),
2776 UnsafetySpace(unsafety),
2780 let (indent, end_newline) = if parent == ItemType::Trait {
2786 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2787 {generics}{decl}{where_clause}",
2788 VisSpace(&meth.visibility),
2789 ConstnessSpace(constness),
2790 UnsafetySpace(unsafety),
2800 where_clause = WhereClause {
2807 clean::StrippedItem(..) => Ok(()),
2808 clean::TyMethodItem(ref m) => {
2809 method(w, item, m.unsafety, hir::Constness::NotConst,
2810 m.abi, &m.generics, &m.decl, link, parent)
2812 clean::MethodItem(ref m) => {
2813 method(w, item, m.unsafety, m.constness,
2814 m.abi, &m.generics, &m.decl, link, parent)
2816 clean::AssociatedConstItem(ref ty, ref default) => {
2817 assoc_const(w, item, ty, default.as_ref(), link)
2819 clean::AssociatedTypeItem(ref bounds, ref default) => {
2820 assoc_type(w, item, bounds, default.as_ref(), link)
2822 _ => panic!("render_assoc_item called on non-associated-item")
2826 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2827 s: &clean::Struct) -> fmt::Result {
2828 write!(w, "<pre class='rust struct'>")?;
2829 render_attributes(w, it)?;
2837 write!(w, "</pre>")?;
2839 document(w, cx, it)?;
2840 let mut fields = s.fields.iter().filter_map(|f| {
2842 clean::StructFieldItem(ref ty) => Some((f, ty)),
2846 if let doctree::Plain = s.struct_type {
2847 if fields.peek().is_some() {
2848 write!(w, "<h2 id='fields' class='fields small-section-header'>
2849 Fields<a href='#fields' class='anchor'></a></h2>")?;
2850 for (field, ty) in fields {
2851 let id = derive_id(format!("{}.{}",
2852 ItemType::StructField,
2853 field.name.as_ref().unwrap()));
2854 let ns_id = derive_id(format!("{}.{}",
2855 field.name.as_ref().unwrap(),
2856 ItemType::StructField.name_space()));
2857 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2858 <a href=\"#{id}\" class=\"anchor field\"></a>
2859 <span id=\"{ns_id}\" class='invisible'>
2860 <code>{name}: {ty}</code>
2862 item_type = ItemType::StructField,
2865 name = field.name.as_ref().unwrap(),
2867 if let Some(stability_class) = field.stability_class() {
2868 write!(w, "<span class='stab {stab}'></span>",
2869 stab = stability_class)?;
2871 document(w, cx, field)?;
2875 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2878 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2879 s: &clean::Union) -> fmt::Result {
2880 write!(w, "<pre class='rust union'>")?;
2881 render_attributes(w, it)?;
2888 write!(w, "</pre>")?;
2890 document(w, cx, it)?;
2891 let mut fields = s.fields.iter().filter_map(|f| {
2893 clean::StructFieldItem(ref ty) => Some((f, ty)),
2897 if fields.peek().is_some() {
2898 write!(w, "<h2 id='fields' class='fields small-section-header'>
2899 Fields<a href='#fields' class='anchor'></a></h2>")?;
2900 for (field, ty) in fields {
2901 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2903 shortty = ItemType::StructField,
2904 name = field.name.as_ref().unwrap(),
2906 if let Some(stability_class) = field.stability_class() {
2907 write!(w, "<span class='stab {stab}'></span>",
2908 stab = stability_class)?;
2910 document(w, cx, field)?;
2913 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2916 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2917 e: &clean::Enum) -> fmt::Result {
2918 write!(w, "<pre class='rust enum'>")?;
2919 render_attributes(w, it)?;
2920 write!(w, "{}enum {}{}{}",
2921 VisSpace(&it.visibility),
2922 it.name.as_ref().unwrap(),
2924 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2925 if e.variants.is_empty() && !e.variants_stripped {
2926 write!(w, " {{}}")?;
2928 write!(w, " {{\n")?;
2929 for v in &e.variants {
2931 let name = v.name.as_ref().unwrap();
2933 clean::VariantItem(ref var) => {
2935 clean::VariantKind::CLike => write!(w, "{}", name)?,
2936 clean::VariantKind::Tuple(ref tys) => {
2937 write!(w, "{}(", name)?;
2938 for (i, ty) in tys.iter().enumerate() {
2940 write!(w, ", ")?
2942 write!(w, "{}", *ty)?;
2946 clean::VariantKind::Struct(ref s) => {
2962 if e.variants_stripped {
2963 write!(w, " // some variants omitted\n")?;
2967 write!(w, "</pre>")?;
2969 document(w, cx, it)?;
2970 if !e.variants.is_empty() {
2971 write!(w, "<h2 id='variants' class='variants small-section-header'>
2972 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2973 for variant in &e.variants {
2974 let id = derive_id(format!("{}.{}",
2976 variant.name.as_ref().unwrap()));
2977 let ns_id = derive_id(format!("{}.{}",
2978 variant.name.as_ref().unwrap(),
2979 ItemType::Variant.name_space()));
2980 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2981 <a href=\"#{id}\" class=\"anchor field\"></a>\
2982 <span id='{ns_id}' class='invisible'><code>{name}",
2985 name = variant.name.as_ref().unwrap())?;
2986 if let clean::VariantItem(ref var) = variant.inner {
2987 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2989 for (i, ty) in tys.iter().enumerate() {
2991 write!(w, ", ")?;
2993 write!(w, "{}", *ty)?;
2998 write!(w, "</code></span></span>")?;
2999 document(w, cx, variant)?;
3001 use clean::{Variant, VariantKind};
3002 if let clean::VariantItem(Variant {
3003 kind: VariantKind::Struct(ref s)
3004 }) = variant.inner {
3005 let variant_id = derive_id(format!("{}.{}.fields",
3007 variant.name.as_ref().unwrap()));
3008 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3010 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3011 <table>", name = variant.name.as_ref().unwrap())?;
3012 for field in &s.fields {
3013 use clean::StructFieldItem;
3014 if let StructFieldItem(ref ty) = field.inner {
3015 let id = derive_id(format!("variant.{}.field.{}",
3016 variant.name.as_ref().unwrap(),
3017 field.name.as_ref().unwrap()));
3018 let ns_id = derive_id(format!("{}.{}.{}.{}",
3019 variant.name.as_ref().unwrap(),
3020 ItemType::Variant.name_space(),
3021 field.name.as_ref().unwrap(),
3022 ItemType::StructField.name_space()));
3023 write!(w, "<tr><td \
3025 <span id='{ns_id}' class='invisible'>\
3026 <code>{f}: {t}</code></span></td><td>",
3029 f = field.name.as_ref().unwrap(),
3031 document(w, cx, field)?;
3032 write!(w, "</td></tr>")?;
3035 write!(w, "</table></span>")?;
3037 render_stability_since(w, variant, it)?;
3040 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3044 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3045 let name = attr.name();
3048 Some(format!("{}", name))
3049 } else if let Some(v) = attr.value_str() {
3050 Some(format!("{} = {:?}", name, v.as_str()))
3051 } else if let Some(values) = attr.meta_item_list() {
3052 let display: Vec<_> = values.iter().filter_map(|attr| {
3053 attr.meta_item().and_then(|mi| render_attribute(mi))
3056 if display.len() > 0 {
3057 Some(format!("{}({})", name, display.join(", ")))
3066 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3073 "unsafe_destructor_blind_to_params"
3076 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3077 let mut attrs = String::new();
3079 for attr in &it.attrs.other_attrs {
3080 let name = attr.name().unwrap();
3081 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3084 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3085 attrs.push_str(&format!("#[{}]\n", s));
3088 if attrs.len() > 0 {
3089 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3094 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3095 g: Option<&clean::Generics>,
3096 ty: doctree::StructType,
3097 fields: &[clean::Item],
3099 structhead: bool) -> fmt::Result {
3101 VisSpace(&it.visibility),
3102 if structhead {"struct "} else {""},
3103 it.name.as_ref().unwrap())?;
3104 if let Some(g) = g {
3109 if let Some(g) = g {
3110 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3112 let mut has_visible_fields = false;
3114 for field in fields {
3115 if let clean::StructFieldItem(ref ty) = field.inner {
3116 write!(w, "\n{} {}{}: {},",
3118 VisSpace(&field.visibility),
3119 field.name.as_ref().unwrap(),
3121 has_visible_fields = true;
3125 if has_visible_fields {
3126 if it.has_stripped_fields().unwrap() {
3127 write!(w, "\n{} // some fields omitted", tab)?;
3129 write!(w, "\n{}", tab)?;
3130 } else if it.has_stripped_fields().unwrap() {
3131 // If there are no visible fields we can just display
3132 // `{ /* fields omitted */ }` to save space.
3133 write!(w, " /* fields omitted */ ")?;
3139 for (i, field) in fields.iter().enumerate() {
3144 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3147 clean::StructFieldItem(ref ty) => {
3148 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3154 if let Some(g) = g {
3155 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3160 // Needed for PhantomData.
3161 if let Some(g) = g {
3162 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3170 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3171 g: Option<&clean::Generics>,
3172 fields: &[clean::Item],
3174 structhead: bool) -> fmt::Result {
3176 VisSpace(&it.visibility),
3177 if structhead {"union "} else {""},
3178 it.name.as_ref().unwrap())?;
3179 if let Some(g) = g {
3180 write!(w, "{}", g)?;
3181 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3184 write!(w, " {{\n{}", tab)?;
3185 for field in fields {
3186 if let clean::StructFieldItem(ref ty) = field.inner {
3187 write!(w, " {}{}: {},\n{}",
3188 VisSpace(&field.visibility),
3189 field.name.as_ref().unwrap(),
3195 if it.has_stripped_fields().unwrap() {
3196 write!(w, " // some fields omitted\n{}", tab)?;
3202 #[derive(Copy, Clone)]
3203 enum AssocItemLink<'a> {
3204 Anchor(Option<&'a str>),
3205 GotoSource(DefId, &'a FxHashSet<String>),
3208 impl<'a> AssocItemLink<'a> {
3209 fn anchor(&self, id: &'a String) -> Self {
3211 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3212 ref other => *other,
3217 enum AssocItemRender<'a> {
3219 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3222 #[derive(Copy, Clone, PartialEq)]
3225 ForDeref { mut_: bool },
3228 fn render_assoc_items(w: &mut fmt::Formatter,
3230 containing_item: &clean::Item,
3232 what: AssocItemRender) -> fmt::Result {
3234 let v = match c.impls.get(&it) {
3236 None => return Ok(()),
3238 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3239 i.inner_impl().trait_.is_none()
3241 if !non_trait.is_empty() {
3242 let render_mode = match what {
3243 AssocItemRender::All => {
3245 <h2 id='methods' class='small-section-header'>
3246 Methods<a href='#methods' class='anchor'></a>
3251 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3253 <h2 id='deref-methods' class='small-section-header'>
3254 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3257 RenderMode::ForDeref { mut_: deref_mut_ }
3260 for i in &non_trait {
3261 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3262 containing_item.stable_since(), true)?;
3265 if let AssocItemRender::DerefFor { .. } = what {
3268 if !traits.is_empty() {
3269 let deref_impl = traits.iter().find(|t| {
3270 t.inner_impl().trait_.def_id() == c.deref_trait_did
3272 if let Some(impl_) = deref_impl {
3273 let has_deref_mut = traits.iter().find(|t| {
3274 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3276 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3279 <h2 id='implementations' class='small-section-header'>
3280 Trait Implementations<a href='#implementations' class='anchor'></a>
3284 let did = i.trait_did().unwrap();
3285 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3286 render_impl(w, cx, i, assoc_link,
3287 RenderMode::Normal, containing_item.stable_since(), true)?;
3293 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3294 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3295 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3296 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3298 clean::TypedefItem(ref t, true) => Some(&t.type_),
3301 }).next().expect("Expected associated type binding");
3302 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3303 deref_mut_: deref_mut };
3304 if let Some(did) = target.def_id() {
3305 render_assoc_items(w, cx, container_item, did, what)
3307 if let Some(prim) = target.primitive_type() {
3308 if let Some(&did) = cache().primitive_locations.get(&prim) {
3309 render_assoc_items(w, cx, container_item, did, what)?;
3316 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3317 let self_type_opt = match item.inner {
3318 clean::MethodItem(ref method) => method.decl.self_type(),
3319 clean::TyMethodItem(ref method) => method.decl.self_type(),
3323 if let Some(self_ty) = self_type_opt {
3324 let (by_mut_ref, by_box, by_value) = match self_ty {
3325 SelfTy::SelfBorrowed(_, mutability) |
3326 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3327 (mutability == Mutability::Mutable, false, false)
3329 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3330 (false, Some(did) == cache().owned_box_did, false)
3332 SelfTy::SelfValue => (false, false, true),
3333 _ => (false, false, false),
3336 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3342 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3343 let mut out = String::new();
3346 clean::FunctionItem(clean::Function { ref decl, .. }) |
3347 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3348 clean::MethodItem(clean::Method { ref decl, .. }) |
3349 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3350 out = spotlight_decl(decl)?;
3358 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3359 let mut out = String::new();
3360 let mut trait_ = String::new();
3362 if let Some(did) = decl.output.def_id() {
3364 if let Some(impls) = c.impls.get(&did) {
3366 let impl_ = i.inner_impl();
3367 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3370 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3371 <code class=\"content\">",
3373 trait_.push_str(&format!("{}", impl_.for_));
3376 //use the "where" class here to make it small
3377 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3378 let t_did = impl_.trait_.def_id().unwrap();
3379 for it in &impl_.items {
3380 if let clean::TypedefItem(ref tydef, _) = it.inner {
3381 out.push_str("<span class=\"where fmt-newline\"> ");
3382 assoc_type(&mut out, it, &vec![],
3384 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3385 out.push_str(";</span>");
3393 if !out.is_empty() {
3394 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3395 <span class='tooltiptext'>Important traits for {}</span></div>\
3396 <div class=\"content hidden\">",
3398 out.push_str("</code></div></div>");
3404 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3405 render_mode: RenderMode, outer_version: Option<&str>,
3406 show_def_docs: bool) -> fmt::Result {
3407 if render_mode == RenderMode::Normal {
3408 let id = derive_id(match i.inner_impl().trait_ {
3409 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3410 None => "impl".to_string(),
3412 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3413 id, i.inner_impl())?;
3414 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3415 write!(w, "</span><span class='out-of-band'>")?;
3416 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3417 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3418 write!(w, "<div class='ghost'></div>")?;
3419 render_stability_since_raw(w, since, outer_version)?;
3420 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3421 l, "goto source code")?;
3423 render_stability_since_raw(w, since, outer_version)?;
3425 write!(w, "</span>")?;
3426 write!(w, "</h3>\n")?;
3427 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3428 write!(w, "<div class='docblock'>{}</div>",
3429 Markdown(&*dox, &i.impl_item.links(), cx.render_type))?;
3433 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3434 link: AssocItemLink, render_mode: RenderMode,
3435 is_default_item: bool, outer_version: Option<&str>,
3436 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3437 let item_type = item.type_();
3438 let name = item.name.as_ref().unwrap();
3440 let render_method_item: bool = match render_mode {
3441 RenderMode::Normal => true,
3442 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3446 clean::MethodItem(clean::Method { ref decl, .. }) |
3447 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3448 // Only render when the method is not static or we allow static methods
3449 if render_method_item {
3450 let id = derive_id(format!("{}.{}", item_type, name));
3451 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3452 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3453 write!(w, "{}", spotlight_decl(decl)?)?;
3454 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3455 write!(w, "<code>")?;
3456 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3457 write!(w, "</code>")?;
3458 if let Some(l) = (Item { cx, item }).src_href() {
3459 write!(w, "</span><span class='out-of-band'>")?;
3460 write!(w, "<div class='ghost'></div>")?;
3461 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3462 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3463 l, "goto source code")?;
3465 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3467 write!(w, "</span></h4>\n")?;
3470 clean::TypedefItem(ref tydef, _) => {
3471 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3472 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3473 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3474 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3475 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3476 write!(w, "</code></span></h4>\n")?;
3478 clean::AssociatedConstItem(ref ty, ref default) => {
3479 let id = derive_id(format!("{}.{}", item_type, name));
3480 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3481 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3482 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3483 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3484 write!(w, "</code></span></h4>\n")?;
3486 clean::AssociatedTypeItem(ref bounds, ref default) => {
3487 let id = derive_id(format!("{}.{}", item_type, name));
3488 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3489 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3490 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3491 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3492 write!(w, "</code></span></h4>\n")?;
3494 clean::StrippedItem(..) => return Ok(()),
3495 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3498 if render_method_item || render_mode == RenderMode::Normal {
3499 let prefix = render_assoc_const_value(item);
3501 if !is_default_item {
3502 if let Some(t) = trait_ {
3503 // The trait item may have been stripped so we might not
3504 // find any documentation or stability for it.
3505 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3506 // We need the stability of the item from the trait
3507 // because impls can't have a stability.
3508 document_stability(w, cx, it)?;
3509 if item.doc_value().is_some() {
3510 document_full(w, item, cx, &prefix)?;
3511 } else if show_def_docs {
3512 // In case the item isn't documented,
3513 // provide short documentation from the trait.
3514 document_short(w, it, link, cx, &prefix)?;
3518 document_stability(w, cx, item)?;
3520 document_full(w, item, cx, &prefix)?;
3524 document_stability(w, cx, item)?;
3526 document_short(w, item, link, cx, &prefix)?;
3533 let traits = &cache().traits;
3534 let trait_ = i.trait_did().map(|did| &traits[&did]);
3537 write!(w, "<span class='docblock autohide'>")?;
3540 write!(w, "<div class='impl-items'>")?;
3541 for trait_item in &i.inner_impl().items {
3542 doc_impl_item(w, cx, trait_item, link, render_mode,
3543 false, outer_version, trait_, show_def_docs)?;
3546 fn render_default_items(w: &mut fmt::Formatter,
3550 render_mode: RenderMode,
3551 outer_version: Option<&str>,
3552 show_def_docs: bool) -> fmt::Result {
3553 for trait_item in &t.items {
3554 let n = trait_item.name.clone();
3555 if i.items.iter().find(|m| m.name == n).is_some() {
3558 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3559 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3561 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3562 outer_version, None, show_def_docs)?;
3567 // If we've implemented a trait, then also emit documentation for all
3568 // default items which weren't overridden in the implementation block.
3569 if let Some(t) = trait_ {
3570 render_default_items(w, cx, t, &i.inner_impl(),
3571 render_mode, outer_version, show_def_docs)?;
3573 write!(w, "</div>")?;
3576 write!(w, "</span>")?;
3582 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3583 t: &clean::Typedef) -> fmt::Result {
3584 write!(w, "<pre class='rust typedef'>")?;
3585 render_attributes(w, it)?;
3586 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3587 it.name.as_ref().unwrap(),
3589 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3592 document(w, cx, it)?;
3594 // Render any items associated directly to this alias, as otherwise they
3595 // won't be visible anywhere in the docs. It would be nice to also show
3596 // associated items from the aliased type (see discussion in #32077), but
3597 // we need #14072 to make sense of the generics.
3598 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3601 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3602 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3603 render_attributes(w, it)?;
3606 " {}type {};\n}}</pre>",
3607 VisSpace(&it.visibility),
3608 it.name.as_ref().unwrap(),
3611 document(w, cx, it)?;
3613 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3616 impl<'a> fmt::Display for Sidebar<'a> {
3617 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3620 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3621 let mut should_close = false;
3623 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3624 || it.is_enum() || it.is_mod() || it.is_typedef()
3626 write!(fmt, "<p class='location'>")?;
3628 clean::StructItem(..) => write!(fmt, "Struct ")?,
3629 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3630 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3631 clean::UnionItem(..) => write!(fmt, "Union ")?,
3632 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3633 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3634 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3635 clean::ModuleItem(..) => if it.is_crate() {
3636 write!(fmt, "Crate ")?;
3638 write!(fmt, "Module ")?;
3642 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3643 write!(fmt, "</p>")?;
3646 if let Some(ref version) = cache().crate_version {
3648 "<div class='block version'>\
3655 write!(fmt, "<div class=\"sidebar-elems\">")?;
3656 should_close = true;
3658 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3659 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3660 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3661 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3662 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3663 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3664 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3665 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3670 // The sidebar is designed to display sibling functions, modules and
3671 // other miscellaneous information. since there are lots of sibling
3672 // items (and that causes quadratic growth in large modules),
3673 // we refactor common parts into a shared JavaScript file per module.
3674 // still, we don't move everything into JS because we want to preserve
3675 // as much HTML as possible in order to allow non-JS-enabled browsers
3676 // to navigate the documentation (though slightly inefficiently).
3678 write!(fmt, "<p class='location'>")?;
3679 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3681 write!(fmt, "::<wbr>")?;
3683 write!(fmt, "<a href='{}index.html'>{}</a>",
3684 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3687 write!(fmt, "</p>")?;
3689 // Sidebar refers to the enclosing module, not this module.
3690 let relpath = if it.is_mod() { "../" } else { "" };
3692 "<script>window.sidebarCurrent = {{\
3697 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3698 ty = it.type_().css_class(),
3701 // There is no sidebar-items.js beyond the crate root path
3702 // FIXME maybe dynamic crate loading can be merged here
3704 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3708 // Closes sidebar-elems div.
3709 write!(fmt, "</div>")?;
3716 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3717 i.items.iter().filter_map(|item| {
3719 // Maybe check with clean::Visibility::Public as well?
3720 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3721 if !for_deref || should_render_item(item, false) {
3722 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3729 }).collect::<Vec<_>>()
3732 // The point is to url encode any potential character from a type with genericity.
3733 fn small_url_encode(s: &str) -> String {
3734 s.replace("<", "%3C")
3735 .replace(">", "%3E")
3736 .replace(" ", "%20")
3737 .replace("?", "%3F")
3738 .replace("'", "%27")
3739 .replace("&", "%26")
3740 .replace(",", "%2C")
3741 .replace(":", "%3A")
3742 .replace(";", "%3B")
3743 .replace("[", "%5B")
3744 .replace("]", "%5D")
3745 .replace("\"", "%22")
3748 fn sidebar_assoc_items(it: &clean::Item) -> String {
3749 let mut out = String::new();
3751 if let Some(v) = c.impls.get(&it.def_id) {
3753 .filter(|i| i.inner_impl().trait_.is_none())
3754 .flat_map(|i| get_methods(i.inner_impl(), false))
3755 .collect::<String>();
3756 if !ret.is_empty() {
3757 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3758 </a><div class=\"sidebar-links\">{}</div>", ret));
3761 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3762 if let Some(impl_) = v.iter()
3763 .filter(|i| i.inner_impl().trait_.is_some())
3764 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3765 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3767 clean::TypedefItem(ref t, true) => Some(&t.type_),
3771 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3772 c.primitive_locations.get(&prim).cloned()
3773 })).and_then(|did| c.impls.get(&did));
3774 if let Some(impls) = inner_impl {
3775 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3776 out.push_str(&format!("Methods from {}<Target={}>",
3777 Escape(&format!("{:#}",
3778 impl_.inner_impl().trait_.as_ref().unwrap())),
3779 Escape(&format!("{:#}", target))));
3780 out.push_str("</a>");
3781 let ret = impls.iter()
3782 .filter(|i| i.inner_impl().trait_.is_none())
3783 .flat_map(|i| get_methods(i.inner_impl(), true))
3784 .collect::<String>();
3785 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3789 let mut links = HashSet::new();
3792 let is_negative_impl = is_negative_impl(i.inner_impl());
3793 if let Some(ref i) = i.inner_impl().trait_ {
3794 let i_display = format!("{:#}", i);
3795 let out = Escape(&i_display);
3796 let encoded = small_url_encode(&format!("{:#}", i));
3797 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3799 if is_negative_impl { "!" } else { "" },
3801 if !links.contains(&generated) && links.insert(generated.clone()) {
3810 .collect::<String>();
3811 if !ret.is_empty() {
3812 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3813 Trait Implementations</a>");
3814 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3822 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3823 s: &clean::Struct) -> fmt::Result {
3824 let mut sidebar = String::new();
3825 let fields = get_struct_fields_name(&s.fields);
3827 if !fields.is_empty() {
3828 if let doctree::Plain = s.struct_type {
3829 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3830 <div class=\"sidebar-links\">{}</div>", fields));
3834 sidebar.push_str(&sidebar_assoc_items(it));
3836 if !sidebar.is_empty() {
3837 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3842 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3844 clean::ItemEnum::ImplItem(ref i) => {
3845 if let Some(ref trait_) = i.trait_ {
3846 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3855 fn is_negative_impl(i: &clean::Impl) -> bool {
3856 i.polarity == Some(clean::ImplPolarity::Negative)
3859 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3860 t: &clean::Trait) -> fmt::Result {
3861 let mut sidebar = String::new();
3867 Some(ref name) if m.is_associated_type() => {
3868 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3874 .collect::<String>();
3875 let consts = t.items
3879 Some(ref name) if m.is_associated_const() => {
3880 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3886 .collect::<String>();
3887 let required = t.items
3891 Some(ref name) if m.is_ty_method() => {
3892 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3898 .collect::<String>();
3899 let provided = t.items
3903 Some(ref name) if m.is_method() => {
3904 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3909 .collect::<String>();
3911 if !types.is_empty() {
3912 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3913 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3916 if !consts.is_empty() {
3917 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3918 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3921 if !required.is_empty() {
3922 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3923 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3926 if !provided.is_empty() {
3927 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3928 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3934 if let Some(implementors) = c.implementors.get(&it.def_id) {
3935 let res = implementors.iter()
3936 .filter(|i| i.inner_impl().for_.def_id()
3937 .map_or(false, |d| !c.paths.contains_key(&d)))
3939 match extract_for_impl_name(&i.impl_item) {
3940 Some((ref name, ref url)) => {
3941 Some(format!("<a href=\"#impl-{}\">{}</a>",
3942 small_url_encode(url),
3948 .collect::<String>();
3949 if !res.is_empty() {
3950 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3951 Implementations on Foreign Types</a><div \
3952 class=\"sidebar-links\">{}</div>",
3957 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3959 sidebar.push_str(&sidebar_assoc_items(it));
3961 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3964 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3965 _p: &clean::PrimitiveType) -> fmt::Result {
3966 let sidebar = sidebar_assoc_items(it);
3968 if !sidebar.is_empty() {
3969 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3974 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3975 _t: &clean::Typedef) -> fmt::Result {
3976 let sidebar = sidebar_assoc_items(it);
3978 if !sidebar.is_empty() {
3979 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3984 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3986 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3991 .filter_map(|f| match f.name {
3992 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3993 {name}</a>", name=name)),
3999 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4000 u: &clean::Union) -> fmt::Result {
4001 let mut sidebar = String::new();
4002 let fields = get_struct_fields_name(&u.fields);
4004 if !fields.is_empty() {
4005 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4006 <div class=\"sidebar-links\">{}</div>", fields));
4009 sidebar.push_str(&sidebar_assoc_items(it));
4011 if !sidebar.is_empty() {
4012 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4017 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4018 e: &clean::Enum) -> fmt::Result {
4019 let mut sidebar = String::new();
4021 let variants = e.variants.iter()
4022 .filter_map(|v| match v.name {
4023 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4024 </a>", name = name)),
4027 .collect::<String>();
4028 if !variants.is_empty() {
4029 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4030 <div class=\"sidebar-links\">{}</div>", variants));
4033 sidebar.push_str(&sidebar_assoc_items(it));
4035 if !sidebar.is_empty() {
4036 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4041 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4042 items: &[clean::Item]) -> fmt::Result {
4043 let mut sidebar = String::new();
4045 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4046 it.type_() == ItemType::Import) {
4047 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4049 name = "Re-exports"));
4052 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4053 // to print its headings
4054 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4055 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4056 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4057 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4058 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4059 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4060 let (short, name) = match myty {
4061 ItemType::ExternCrate |
4062 ItemType::Import => ("reexports", "Re-exports"),
4063 ItemType::Module => ("modules", "Modules"),
4064 ItemType::Struct => ("structs", "Structs"),
4065 ItemType::Union => ("unions", "Unions"),
4066 ItemType::Enum => ("enums", "Enums"),
4067 ItemType::Function => ("functions", "Functions"),
4068 ItemType::Typedef => ("types", "Type Definitions"),
4069 ItemType::Static => ("statics", "Statics"),
4070 ItemType::Constant => ("constants", "Constants"),
4071 ItemType::Trait => ("traits", "Traits"),
4072 ItemType::Impl => ("impls", "Implementations"),
4073 ItemType::TyMethod => ("tymethods", "Type Methods"),
4074 ItemType::Method => ("methods", "Methods"),
4075 ItemType::StructField => ("fields", "Struct Fields"),
4076 ItemType::Variant => ("variants", "Variants"),
4077 ItemType::Macro => ("macros", "Macros"),
4078 ItemType::Primitive => ("primitives", "Primitive Types"),
4079 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4080 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4081 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4083 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4089 if !sidebar.is_empty() {
4090 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4095 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4096 let sidebar = sidebar_assoc_items(it);
4097 if !sidebar.is_empty() {
4098 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4103 impl<'a> fmt::Display for Source<'a> {
4104 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4105 let Source(s) = *self;
4106 let lines = s.lines().count();
4108 let mut tmp = lines;
4113 write!(fmt, "<pre class=\"line-numbers\">")?;
4114 for i in 1..lines + 1 {
4115 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4117 write!(fmt, "</pre>")?;
4119 highlight::render_with_highlighting(s, None, None, None, None))?;
4124 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4125 t: &clean::Macro) -> fmt::Result {
4126 w.write_str(&highlight::render_with_highlighting(&t.source,
4134 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4136 _p: &clean::PrimitiveType) -> fmt::Result {
4137 document(w, cx, it)?;
4138 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4141 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4143 fn make_item_keywords(it: &clean::Item) -> String {
4144 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4147 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4148 let decl = match item.inner {
4149 clean::FunctionItem(ref f) => &f.decl,
4150 clean::MethodItem(ref m) => &m.decl,
4151 clean::TyMethodItem(ref m) => &m.decl,
4155 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4156 let output = match decl.output {
4157 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4161 Some(IndexItemFunctionType { inputs: inputs, output: output })
4164 fn get_index_type(clean_type: &clean::Type) -> Type {
4166 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4167 generics: get_generics(clean_type),
4172 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4174 clean::ResolvedPath { ref path, .. } => {
4175 let segments = &path.segments;
4176 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4177 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4178 clean_type, accept_generic
4180 Some(path_segment.name.clone())
4182 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4183 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4184 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4185 // FIXME: add all from clean::Type.
4190 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4191 clean_type.generics()
4193 let r = types.iter()
4194 .filter_map(|t| get_index_type_name(t, false))
4195 .map(|s| s.to_ascii_lowercase())
4196 .collect::<Vec<_>>();
4205 pub fn cache() -> Arc<Cache> {
4206 CACHE_KEY.with(|c| c.borrow().clone())
4211 fn test_unique_id() {
4212 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4213 "method.into_iter", "foo", "main", "search", "methods",
4214 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4215 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4216 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4217 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4220 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4221 assert_eq!(&actual[..], expected);
4230 fn test_name_key() {
4231 assert_eq!(name_key("0"), ("", 0, 1));
4232 assert_eq!(name_key("123"), ("", 123, 0));
4233 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4234 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4235 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4236 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4237 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4238 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4243 fn test_name_sorting() {
4244 let names = ["Apple",
4246 "Fruit", "Fruit0", "Fruit00",
4247 "Fruit1", "Fruit01",
4248 "Fruit2", "Fruit02",
4252 let mut sorted = names.to_owned();
4253 sorted.sort_by_key(|&s| name_key(s));
4254 assert_eq!(names, sorted);