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.
36 pub use self::ExternalLocation::*;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, HashSet, VecDeque};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
45 use std::fs::{self, File, OpenOptions};
46 use std::io::prelude::*;
47 use std::io::{self, BufWriter, BufReader};
48 use std::iter::repeat;
50 use std::path::{PathBuf, Path, Component};
54 use externalfiles::ExternalHtml;
56 use serialize::json::{ToJson, Json, as_json};
57 use syntax::{abi, ast};
58 use syntax::codemap::FileName;
59 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
60 use rustc::middle::privacy::AccessLevels;
61 use rustc::middle::stability;
63 use rustc::util::nodemap::{FxHashMap, FxHashSet};
64 use rustc_data_structures::flock;
66 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
69 use html::escape::Escape;
70 use html::format::{ConstnessSpace};
71 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
72 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
73 use html::format::fmt_impl_for_trait_page;
74 use html::item_type::ItemType;
75 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
76 use html::{highlight, layout};
78 /// A pair of name and its optional document.
79 pub type NameDoc = (String, Option<String>);
81 /// Major driving force in all rustdoc rendering. This contains information
82 /// about where in the tree-like hierarchy rendering is occurring and controls
83 /// how the current page is being rendered.
85 /// It is intended that this context is a lightweight object which can be fairly
86 /// easily cloned because it is cloned per work-job (about once per item in the
90 /// Current hierarchy of components leading down to what's currently being
92 pub current: Vec<String>,
93 /// The current destination folder of where HTML artifacts should be placed.
94 /// This changes as the context descends into the module hierarchy.
96 /// A flag, which when `true`, will render pages which redirect to the
97 /// real location of an item. This is used to allow external links to
98 /// publicly reused items to redirect to the right location.
99 pub render_redirect_pages: bool,
100 pub shared: Arc<SharedContext>,
103 pub struct SharedContext {
104 /// The path to the crate root source minus the file name.
105 /// Used for simplifying paths to the highlighted source code files.
106 pub src_root: PathBuf,
107 /// This describes the layout of each page, and is not modified after
108 /// creation of the context (contains info like the favicon and added html).
109 pub layout: layout::Layout,
110 /// This flag indicates whether [src] links should be generated or not. If
111 /// the source files are present in the html rendering, then this will be
113 pub include_sources: bool,
114 /// The local file sources we've emitted and their respective url-paths.
115 pub local_sources: FxHashMap<PathBuf, String>,
116 /// All the passes that were run on this crate.
117 pub passes: FxHashSet<String>,
118 /// The base-URL of the issue tracker for when an item has been tagged with
120 pub issue_tracker_base_url: Option<String>,
121 /// The given user css file which allow to customize the generated
122 /// documentation theme.
123 pub css_file_extension: Option<PathBuf>,
124 /// The directories that have already been created in this doc run. Used to reduce the number
125 /// of spurious `create_dir_all` calls.
126 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
127 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
128 /// should be ordered alphabetically or in order of appearance (in the source code).
129 pub sort_modules_alphabetically: bool,
130 /// Additional themes to be added to the generated docs.
131 pub themes: Vec<PathBuf>,
132 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
134 pub resource_suffix: String,
138 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
139 let mut dirs = self.created_dirs.borrow_mut();
140 if !dirs.contains(dst) {
141 fs::create_dir_all(dst)?;
142 dirs.insert(dst.to_path_buf());
150 /// Returns whether the `collapse-docs` pass was run on this crate.
151 pub fn was_collapsed(&self) -> bool {
152 self.passes.contains("collapse-docs")
155 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
156 /// `collapsed_doc_value` of the given item.
157 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
158 if self.was_collapsed() {
159 item.collapsed_doc_value().map(|s| s.into())
161 item.doc_value().map(|s| s.into())
166 /// Indicates where an external crate can be found.
167 pub enum ExternalLocation {
168 /// Remote URL root of the external crate
170 /// This external crate can be found in the local doc/ folder
172 /// The external crate could not be found.
176 /// Metadata about implementations for a type or trait.
179 pub impl_item: clean::Item,
183 fn inner_impl(&self) -> &clean::Impl {
184 match self.impl_item.inner {
185 clean::ImplItem(ref impl_) => impl_,
186 _ => panic!("non-impl item found in impl")
190 fn trait_did(&self) -> Option<DefId> {
191 self.inner_impl().trait_.def_id()
201 impl error::Error for Error {
202 fn description(&self) -> &str {
203 self.error.description()
207 impl Display for Error {
208 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
209 write!(f, "\"{}\": {}", self.file.display(), self.error)
214 pub fn new(e: io::Error, file: &Path) -> Error {
216 file: file.to_path_buf(),
222 macro_rules! try_none {
223 ($e:expr, $file:expr) => ({
227 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
233 macro_rules! try_err {
234 ($e:expr, $file:expr) => ({
237 Err(e) => return Err(Error::new(e, $file)),
242 /// This cache is used to store information about the `clean::Crate` being
243 /// rendered in order to provide more useful documentation. This contains
244 /// information like all implementors of a trait, all traits a type implements,
245 /// documentation for all known traits, etc.
247 /// This structure purposefully does not implement `Clone` because it's intended
248 /// to be a fairly large and expensive structure to clone. Instead this adheres
249 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
250 /// rendering threads.
253 /// Mapping of typaram ids to the name of the type parameter. This is used
254 /// when pretty-printing a type (so pretty printing doesn't have to
255 /// painfully maintain a context like this)
256 pub typarams: FxHashMap<DefId, String>,
258 /// Maps a type id to all known implementations for that type. This is only
259 /// recognized for intra-crate `ResolvedPath` types, and is used to print
260 /// out extra documentation on the page of an enum/struct.
262 /// The values of the map are a list of implementations and documentation
263 /// found on that implementation.
264 pub impls: FxHashMap<DefId, Vec<Impl>>,
266 /// Maintains a mapping of local crate node ids to the fully qualified name
267 /// and "short type description" of that node. This is used when generating
268 /// URLs when a type is being linked to. External paths are not located in
269 /// this map because the `External` type itself has all the information
271 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
273 /// Similar to `paths`, but only holds external paths. This is only used for
274 /// generating explicit hyperlinks to other crates.
275 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
277 /// Maps local def ids of exported types to fully qualified paths.
278 /// Unlike 'paths', this mapping ignores any renames that occur
279 /// due to 'use' statements.
281 /// This map is used when writing out the special 'implementors'
282 /// javascript file. By using the exact path that the type
283 /// is declared with, we ensure that each path will be identical
284 /// to the path used if the corresponding type is inlined. By
285 /// doing this, we can detect duplicate impls on a trait page, and only display
286 /// the impl for the inlined type.
287 pub exact_paths: FxHashMap<DefId, Vec<String>>,
289 /// This map contains information about all known traits of this crate.
290 /// Implementations of a crate should inherit the documentation of the
291 /// parent trait if no extra documentation is specified, and default methods
292 /// should show up in documentation about trait implementations.
293 pub traits: FxHashMap<DefId, clean::Trait>,
295 /// When rendering traits, it's often useful to be able to list all
296 /// implementors of the trait, and this mapping is exactly, that: a mapping
297 /// of trait ids to the list of known implementors of the trait
298 pub implementors: FxHashMap<DefId, Vec<Impl>>,
300 /// Cache of where external crate documentation can be found.
301 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
303 /// Cache of where documentation for primitives can be found.
304 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
306 // Note that external items for which `doc(hidden)` applies to are shown as
307 // non-reachable while local items aren't. This is because we're reusing
308 // the access levels from crateanalysis.
309 pub access_levels: Arc<AccessLevels<DefId>>,
311 /// The version of the crate being documented, if given fron the `--crate-version` flag.
312 pub crate_version: Option<String>,
314 // Private fields only used when initially crawling a crate to build a cache
317 parent_stack: Vec<DefId>,
318 parent_is_trait_impl: bool,
319 search_index: Vec<IndexItem>,
321 deref_trait_did: Option<DefId>,
322 deref_mut_trait_did: Option<DefId>,
323 owned_box_did: Option<DefId>,
324 masked_crates: FxHashSet<CrateNum>,
326 // In rare case where a structure is defined in one module but implemented
327 // in another, if the implementing module is parsed before defining module,
328 // then the fully qualified name of the structure isn't presented in `paths`
329 // yet when its implementation methods are being indexed. Caches such methods
330 // and their parent id here and indexes them at the end of crate parsing.
331 orphan_impl_items: Vec<(DefId, clean::Item)>,
334 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
335 /// Later on moved into `CACHE_KEY`.
337 pub struct RenderInfo {
338 pub inlined: FxHashSet<DefId>,
339 pub external_paths: ::core::ExternalPaths,
340 pub external_typarams: FxHashMap<DefId, String>,
341 pub exact_paths: FxHashMap<DefId, Vec<String>>,
342 pub deref_trait_did: Option<DefId>,
343 pub deref_mut_trait_did: Option<DefId>,
344 pub owned_box_did: Option<DefId>,
347 /// Helper struct to render all source code to HTML pages
348 struct SourceCollector<'a> {
349 scx: &'a mut SharedContext,
351 /// Root destination to place all HTML output into
355 /// Wrapper struct to render the source code of a file. This will do things like
356 /// adding line numbers to the left-hand side.
357 struct Source<'a>(&'a str);
359 // Helper structs for rendering items/sidebars and carrying along contextual
362 #[derive(Copy, Clone)]
365 item: &'a clean::Item,
368 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
370 /// Struct representing one entry in the JS search index. These are all emitted
371 /// by hand to a large JS file at the end of cache-creation.
377 parent: Option<DefId>,
378 parent_idx: Option<usize>,
379 search_type: Option<IndexItemFunctionType>,
382 impl ToJson for IndexItem {
383 fn to_json(&self) -> Json {
384 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
386 let mut data = Vec::with_capacity(6);
387 data.push((self.ty as usize).to_json());
388 data.push(self.name.to_json());
389 data.push(self.path.to_json());
390 data.push(self.desc.to_json());
391 data.push(self.parent_idx.to_json());
392 data.push(self.search_type.to_json());
398 /// A type used for the search index.
400 name: Option<String>,
401 generics: Option<Vec<String>>,
404 impl ToJson for Type {
405 fn to_json(&self) -> Json {
408 let mut data = BTreeMap::new();
409 data.insert("name".to_owned(), name.to_json());
410 if let Some(ref generics) = self.generics {
411 data.insert("generics".to_owned(), generics.to_json());
420 /// Full type of functions/methods in the search index.
421 struct IndexItemFunctionType {
426 impl ToJson for IndexItemFunctionType {
427 fn to_json(&self) -> Json {
428 // If we couldn't figure out a type, just write `null`.
429 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
432 let mut data = BTreeMap::new();
433 data.insert("inputs".to_owned(), self.inputs.to_json());
434 data.insert("output".to_owned(), self.output.to_json());
440 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
441 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
442 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
444 fn init_ids() -> FxHashMap<String, usize> {
456 "synthetic-implementors",
458 "synthetic-implementors-list",
462 ].into_iter().map(|id| (String::from(*id), 1)).collect()
465 /// This method resets the local table of used ID attributes. This is typically
466 /// used at the beginning of rendering an entire HTML page to reset from the
467 /// previous state (if any).
468 pub fn reset_ids(embedded: bool) {
469 USED_ID_MAP.with(|s| {
470 *s.borrow_mut() = if embedded {
478 pub fn derive_id(candidate: String) -> String {
479 USED_ID_MAP.with(|map| {
480 let id = match map.borrow_mut().get_mut(&candidate) {
483 let id = format!("{}-{}", candidate, *a);
489 map.borrow_mut().insert(id.clone(), 1);
494 /// Generates the documentation for `crate` into the directory `dst`
495 pub fn run(mut krate: clean::Crate,
496 external_html: &ExternalHtml,
497 playground_url: Option<String>,
499 resource_suffix: String,
500 passes: FxHashSet<String>,
501 css_file_extension: Option<PathBuf>,
502 renderinfo: RenderInfo,
503 sort_modules_alphabetically: bool,
504 themes: Vec<PathBuf>) -> Result<(), Error> {
505 let src_root = match krate.src {
506 FileName::Real(ref p) => match p.parent() {
507 Some(p) => p.to_path_buf(),
508 None => PathBuf::new(),
512 let mut scx = SharedContext {
515 include_sources: true,
516 local_sources: FxHashMap(),
517 issue_tracker_base_url: None,
518 layout: layout::Layout {
519 logo: "".to_string(),
520 favicon: "".to_string(),
521 external_html: external_html.clone(),
522 krate: krate.name.clone(),
524 css_file_extension: css_file_extension.clone(),
525 created_dirs: RefCell::new(FxHashSet()),
526 sort_modules_alphabetically,
531 // If user passed in `--playground-url` arg, we fill in crate name here
532 if let Some(url) = playground_url {
533 markdown::PLAYGROUND.with(|slot| {
534 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
538 // Crawl the crate attributes looking for attributes which control how we're
539 // going to emit HTML
540 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
541 for attr in attrs.lists("doc") {
542 let name = attr.name().map(|s| s.as_str());
543 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
544 (Some("html_favicon_url"), Some(s)) => {
545 scx.layout.favicon = s.to_string();
547 (Some("html_logo_url"), Some(s)) => {
548 scx.layout.logo = s.to_string();
550 (Some("html_playground_url"), Some(s)) => {
551 markdown::PLAYGROUND.with(|slot| {
552 let name = krate.name.clone();
553 *slot.borrow_mut() = Some((Some(name), s.to_string()));
556 (Some("issue_tracker_base_url"), Some(s)) => {
557 scx.issue_tracker_base_url = Some(s.to_string());
559 (Some("html_no_source"), None) if attr.is_word() => {
560 scx.include_sources = false;
566 try_err!(fs::create_dir_all(&dst), &dst);
567 krate = render_sources(&dst, &mut scx, krate)?;
571 render_redirect_pages: false,
572 shared: Arc::new(scx),
575 // Crawl the crate to build various caches used for the output
586 let external_paths = external_paths.into_iter()
587 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
590 let mut cache = Cache {
595 implementors: FxHashMap(),
597 parent_stack: Vec::new(),
598 search_index: Vec::new(),
599 parent_is_trait_impl: false,
600 extern_locations: FxHashMap(),
601 primitive_locations: FxHashMap(),
603 access_levels: krate.access_levels.clone(),
604 crate_version: krate.version.take(),
605 orphan_impl_items: Vec::new(),
606 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
610 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
611 typarams: external_typarams,
614 // Cache where all our extern crates are located
615 for &(n, ref e) in &krate.externs {
616 let src_root = match e.src {
617 FileName::Real(ref p) => match p.parent() {
618 Some(p) => p.to_path_buf(),
619 None => PathBuf::new(),
623 cache.extern_locations.insert(n, (e.name.clone(), src_root,
624 extern_location(e, &cx.dst)));
626 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
627 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
630 // Cache where all known primitives have their documentation located.
632 // Favor linking to as local extern as possible, so iterate all crates in
633 // reverse topological order.
634 for &(_, ref e) in krate.externs.iter().rev() {
635 for &(def_id, prim, _) in &e.primitives {
636 cache.primitive_locations.insert(prim, def_id);
639 for &(def_id, prim, _) in &krate.primitives {
640 cache.primitive_locations.insert(prim, def_id);
643 cache.stack.push(krate.name.clone());
644 krate = cache.fold_crate(krate);
646 // Build our search index
647 let index = build_index(&krate, &mut cache);
649 // Freeze the cache now that the index has been built. Put an Arc into TLS
650 // for future parallelization opportunities
651 let cache = Arc::new(cache);
652 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
653 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
655 write_shared(&cx, &krate, &*cache, index)?;
657 // And finally render the whole crate's documentation
661 /// Build the search index from the collected metadata
662 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
663 let mut nodeid_to_pathid = FxHashMap();
664 let mut crate_items = Vec::with_capacity(cache.search_index.len());
665 let mut crate_paths = Vec::<Json>::new();
667 let Cache { ref mut search_index,
668 ref orphan_impl_items,
669 ref mut paths, .. } = *cache;
671 // Attach all orphan items to the type's definition if the type
672 // has since been learned.
673 for &(did, ref item) in orphan_impl_items {
674 if let Some(&(ref fqp, _)) = paths.get(&did) {
675 search_index.push(IndexItem {
677 name: item.name.clone().unwrap(),
678 path: fqp[..fqp.len() - 1].join("::"),
679 desc: plain_summary_line(item.doc_value()),
682 search_type: get_index_search_type(&item),
687 // Reduce `NodeId` in paths into smaller sequential numbers,
688 // and prune the paths that do not appear in the index.
689 let mut lastpath = String::new();
690 let mut lastpathid = 0usize;
692 for item in search_index {
693 item.parent_idx = item.parent.map(|nodeid| {
694 if nodeid_to_pathid.contains_key(&nodeid) {
695 *nodeid_to_pathid.get(&nodeid).unwrap()
697 let pathid = lastpathid;
698 nodeid_to_pathid.insert(nodeid, pathid);
701 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
702 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
707 // Omit the parent path if it is same to that of the prior item.
708 if lastpath == item.path {
711 lastpath = item.path.clone();
713 crate_items.push(item.to_json());
716 let crate_doc = krate.module.as_ref().map(|module| {
717 plain_summary_line(module.doc_value())
718 }).unwrap_or(String::new());
720 let mut crate_data = BTreeMap::new();
721 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
722 crate_data.insert("items".to_owned(), Json::Array(crate_items));
723 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
725 // Collect the index into a string
726 format!("searchIndex[{}] = {};",
727 as_json(&krate.name),
728 Json::Object(crate_data))
731 fn write_shared(cx: &Context,
732 krate: &clean::Crate,
734 search_index: String) -> Result<(), Error> {
735 // Write out the shared files. Note that these are shared among all rustdoc
736 // docs placed in the output directory, so this needs to be a synchronized
737 // operation with respect to all other rustdocs running around.
738 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
740 // Add all the static files. These may already exist, but we just
741 // overwrite them anyway to make sure that they're fresh and up-to-date.
743 write(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
744 include_bytes!("static/rustdoc.css"))?;
746 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
747 // then we'll run over the "official" styles.
748 let mut themes: HashSet<String> = HashSet::new();
750 for entry in &cx.shared.themes {
751 let mut content = Vec::with_capacity(100000);
753 let mut f = try_err!(File::open(&entry), &entry);
754 try_err!(f.read_to_end(&mut content), &entry);
755 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
756 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
757 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
758 content.as_slice())?;
759 themes.insert(theme.to_owned());
762 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
763 include_bytes!("static/brush.svg"))?;
764 write(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
765 include_bytes!("static/themes/light.css"))?;
766 themes.insert("light".to_owned());
767 write(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
768 include_bytes!("static/themes/dark.css"))?;
769 themes.insert("dark".to_owned());
771 let mut themes: Vec<&String> = themes.iter().collect();
773 // To avoid theme switch latencies as much as possible, we put everything theme related
774 // at the beginning of the html files into another js file.
775 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
777 r#"var themes = document.getElementById("theme-choices");
778 var themePicker = document.getElementById("theme-picker");
779 themePicker.onclick = function() {{
780 if (themes.style.display === "block") {{
781 themes.style.display = "none";
782 themePicker.style.borderBottomRightRadius = "3px";
783 themePicker.style.borderBottomLeftRadius = "3px";
785 themes.style.display = "block";
786 themePicker.style.borderBottomRightRadius = "0";
787 themePicker.style.borderBottomLeftRadius = "0";
790 [{}].forEach(function(item) {{
791 var but = document.createElement('button');
792 but.innerHTML = item;
793 but.onclick = function(el) {{
794 switchTheme(currentTheme, mainTheme, item);
796 themes.appendChild(but);
800 .map(|s| format!("\"{}\"", s))
801 .collect::<Vec<String>>()
802 .join(",")).as_bytes(),
805 write(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
806 include_bytes!("static/main.js"))?;
809 let mut data = format!("var resourcesSuffix = \"{}\";\n",
810 cx.shared.resource_suffix).into_bytes();
811 data.extend_from_slice(include_bytes!("static/storage.js"));
812 write(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)), &data)?;
815 if let Some(ref css) = cx.shared.css_file_extension {
816 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
817 try_err!(fs::copy(css, out), css);
819 write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
820 include_bytes!("static/normalize.css"))?;
821 write(cx.dst.join("FiraSans-Regular.woff"),
822 include_bytes!("static/FiraSans-Regular.woff"))?;
823 write(cx.dst.join("FiraSans-Medium.woff"),
824 include_bytes!("static/FiraSans-Medium.woff"))?;
825 write(cx.dst.join("FiraSans-LICENSE.txt"),
826 include_bytes!("static/FiraSans-LICENSE.txt"))?;
827 write(cx.dst.join("Heuristica-Italic.woff"),
828 include_bytes!("static/Heuristica-Italic.woff"))?;
829 write(cx.dst.join("Heuristica-LICENSE.txt"),
830 include_bytes!("static/Heuristica-LICENSE.txt"))?;
831 write(cx.dst.join("SourceSerifPro-Regular.woff"),
832 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
833 write(cx.dst.join("SourceSerifPro-Bold.woff"),
834 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
835 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
836 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
837 write(cx.dst.join("SourceCodePro-Regular.woff"),
838 include_bytes!("static/SourceCodePro-Regular.woff"))?;
839 write(cx.dst.join("SourceCodePro-Semibold.woff"),
840 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
841 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
842 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
843 write(cx.dst.join("LICENSE-MIT.txt"),
844 include_bytes!("static/LICENSE-MIT.txt"))?;
845 write(cx.dst.join("LICENSE-APACHE.txt"),
846 include_bytes!("static/LICENSE-APACHE.txt"))?;
847 write(cx.dst.join("COPYRIGHT.txt"),
848 include_bytes!("static/COPYRIGHT.txt"))?;
850 fn collect(path: &Path, krate: &str,
851 key: &str) -> io::Result<Vec<String>> {
852 let mut ret = Vec::new();
854 for line in BufReader::new(File::open(path)?).lines() {
856 if !line.starts_with(key) {
859 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
862 ret.push(line.to_string());
868 // Update the search index
869 let dst = cx.dst.join("search-index.js");
870 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
871 all_indexes.push(search_index);
872 // Sort the indexes by crate so the file will be generated identically even
873 // with rustdoc running in parallel.
875 let mut w = try_err!(File::create(&dst), &dst);
876 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
877 for index in &all_indexes {
878 try_err!(writeln!(&mut w, "{}", *index), &dst);
880 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
882 // Update the list of all implementors for traits
883 let dst = cx.dst.join("implementors");
884 for (&did, imps) in &cache.implementors {
885 // Private modules can leak through to this phase of rustdoc, which
886 // could contain implementations for otherwise private types. In some
887 // rare cases we could find an implementation for an item which wasn't
888 // indexed, so we just skip this step in that case.
890 // FIXME: this is a vague explanation for why this can't be a `get`, in
891 // theory it should be...
892 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
894 None => match cache.external_paths.get(&did) {
900 let mut have_impls = false;
901 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
903 // If the trait and implementation are in the same crate, then
904 // there's no need to emit information about it (there's inlining
905 // going on). If they're in different crates then the crate defining
906 // the trait will be interested in our implementation.
907 if imp.impl_item.def_id.krate == did.krate { continue }
908 // If the implementation is from another crate then that crate
910 if !imp.impl_item.def_id.is_local() { continue }
912 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
913 as_json(&imp.inner_impl().to_string()),
914 imp.inner_impl().synthetic,
915 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
917 implementors.push_str("];");
919 // Only create a js file if we have impls to add to it. If the trait is
920 // documented locally though we always create the file to avoid dead
922 if !have_impls && !cache.paths.contains_key(&did) {
926 let mut mydst = dst.clone();
927 for part in &remote_path[..remote_path.len() - 1] {
930 try_err!(fs::create_dir_all(&mydst), &mydst);
931 mydst.push(&format!("{}.{}.js",
932 remote_item_type.css_class(),
933 remote_path[remote_path.len() - 1]));
935 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
936 all_implementors.push(implementors);
937 // Sort the implementors by crate so the file will be generated
938 // identically even with rustdoc running in parallel.
939 all_implementors.sort();
941 let mut f = try_err!(File::create(&mydst), &mydst);
942 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
943 for implementor in &all_implementors {
944 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
946 try_err!(writeln!(&mut f, "{}", r"
947 if (window.register_implementors) {
948 window.register_implementors(implementors);
950 window.pending_implementors = implementors;
953 try_err!(writeln!(&mut f, r"}})()"), &mydst);
958 fn render_sources(dst: &Path, scx: &mut SharedContext,
959 krate: clean::Crate) -> Result<clean::Crate, Error> {
960 info!("emitting source files");
961 let dst = dst.join("src").join(&krate.name);
962 try_err!(fs::create_dir_all(&dst), &dst);
963 let mut folder = SourceCollector {
967 Ok(folder.fold_crate(krate))
970 /// Writes the entire contents of a string to a destination, not attempting to
971 /// catch any errors.
972 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
973 Ok(try_err!(fs::write(&dst, contents), &dst))
976 /// Takes a path to a source file and cleans the path to it. This canonicalizes
977 /// things like ".." to components which preserve the "top down" hierarchy of a
978 /// static HTML tree. Each component in the cleaned path will be passed as an
979 /// argument to `f`. The very last component of the path (ie the file name) will
980 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
981 // FIXME (#9639): The closure should deal with &[u8] instead of &str
982 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
983 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
986 // make it relative, if possible
987 let p = p.strip_prefix(src_root).unwrap_or(p);
989 let mut iter = p.components().peekable();
991 while let Some(c) = iter.next() {
992 if !keep_filename && iter.peek().is_none() {
997 Component::ParentDir => f("up"),
998 Component::Normal(c) => f(c.to_str().unwrap()),
1004 /// Attempts to find where an external crate is located, given that we're
1005 /// rendering in to the specified source destination.
1006 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1007 // See if there's documentation generated into the local directory
1008 let local_location = dst.join(&e.name);
1009 if local_location.is_dir() {
1013 // Failing that, see if there's an attribute specifying where to find this
1015 e.attrs.lists("doc")
1016 .filter(|a| a.check_name("html_root_url"))
1017 .filter_map(|a| a.value_str())
1019 let mut url = url.to_string();
1020 if !url.ends_with("/") {
1024 }).next().unwrap_or(Unknown) // Well, at least we tried.
1027 impl<'a> DocFolder for SourceCollector<'a> {
1028 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1029 // If we're including source files, and we haven't seen this file yet,
1030 // then we need to render it out to the filesystem.
1031 if self.scx.include_sources
1032 // skip all invalid or macro spans
1033 && item.source.filename.is_real()
1034 // skip non-local items
1035 && item.def_id.is_local() {
1037 // If it turns out that we couldn't read this file, then we probably
1038 // can't read any of the files (generating html output from json or
1039 // something like that), so just don't include sources for the
1040 // entire crate. The other option is maintaining this mapping on a
1041 // per-file basis, but that's probably not worth it...
1043 .include_sources = match self.emit_source(&item.source.filename) {
1046 println!("warning: source code was requested to be rendered, \
1047 but processing `{}` had an error: {}",
1048 item.source.filename, e);
1049 println!(" skipping rendering of source code");
1054 self.fold_item_recur(item)
1058 impl<'a> SourceCollector<'a> {
1059 /// Renders the given filename into its corresponding HTML source file.
1060 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1061 let p = match *filename {
1062 FileName::Real(ref file) => file,
1065 if self.scx.local_sources.contains_key(&**p) {
1066 // We've already emitted this source
1070 let contents = fs::read_to_string(&p)?;
1072 // Remove the utf-8 BOM if any
1073 let contents = if contents.starts_with("\u{feff}") {
1079 // Create the intermediate directories
1080 let mut cur = self.dst.clone();
1081 let mut root_path = String::from("../../");
1082 let mut href = String::new();
1083 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1084 cur.push(component);
1085 fs::create_dir_all(&cur).unwrap();
1086 root_path.push_str("../");
1087 href.push_str(component);
1090 let mut fname = p.file_name().expect("source has no filename")
1092 fname.push(".html");
1094 href.push_str(&fname.to_string_lossy());
1096 let mut w = BufWriter::new(File::create(&cur)?);
1097 let title = format!("{} -- source", cur.file_name().unwrap()
1098 .to_string_lossy());
1099 let desc = format!("Source to the Rust file `{}`.", filename);
1100 let page = layout::Page {
1102 css_class: "source",
1103 root_path: &root_path,
1105 keywords: BASIC_KEYWORDS,
1106 resource_suffix: &self.scx.resource_suffix,
1108 layout::render(&mut w, &self.scx.layout,
1109 &page, &(""), &Source(contents),
1110 self.scx.css_file_extension.is_some(),
1113 self.scx.local_sources.insert(p.clone(), href);
1118 impl DocFolder for Cache {
1119 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1120 // If this is a stripped module,
1121 // we don't want it or its children in the search index.
1122 let orig_stripped_mod = match item.inner {
1123 clean::StrippedItem(box clean::ModuleItem(..)) => {
1124 mem::replace(&mut self.stripped_mod, true)
1126 _ => self.stripped_mod,
1129 // If the impl is from a masked crate or references something from a
1130 // masked crate then remove it completely.
1131 if let clean::ImplItem(ref i) = item.inner {
1132 if self.masked_crates.contains(&item.def_id.krate) ||
1133 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1134 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1139 // Register any generics to their corresponding string. This is used
1140 // when pretty-printing types.
1141 if let Some(generics) = item.inner.generics() {
1142 self.generics(generics);
1145 // Propagate a trait method's documentation to all implementors of the
1147 if let clean::TraitItem(ref t) = item.inner {
1148 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1151 // Collect all the implementors of traits.
1152 if let clean::ImplItem(ref i) = item.inner {
1153 if let Some(did) = i.trait_.def_id() {
1154 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1155 impl_item: item.clone(),
1160 // Index this method for searching later on.
1161 if let Some(ref s) = item.name {
1162 let (parent, is_inherent_impl_item) = match item.inner {
1163 clean::StrippedItem(..) => ((None, None), false),
1164 clean::AssociatedConstItem(..) |
1165 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1166 // skip associated items in trait impls
1167 ((None, None), false)
1169 clean::AssociatedTypeItem(..) |
1170 clean::TyMethodItem(..) |
1171 clean::StructFieldItem(..) |
1172 clean::VariantItem(..) => {
1173 ((Some(*self.parent_stack.last().unwrap()),
1174 Some(&self.stack[..self.stack.len() - 1])),
1177 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1178 if self.parent_stack.is_empty() {
1179 ((None, None), false)
1181 let last = self.parent_stack.last().unwrap();
1183 let path = match self.paths.get(&did) {
1184 // The current stack not necessarily has correlation
1185 // for where the type was defined. On the other
1186 // hand, `paths` always has the right
1187 // information if present.
1188 Some(&(ref fqp, ItemType::Trait)) |
1189 Some(&(ref fqp, ItemType::Struct)) |
1190 Some(&(ref fqp, ItemType::Union)) |
1191 Some(&(ref fqp, ItemType::Enum)) =>
1192 Some(&fqp[..fqp.len() - 1]),
1193 Some(..) => Some(&*self.stack),
1196 ((Some(*last), path), true)
1199 _ => ((None, Some(&*self.stack)), false)
1203 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1204 debug_assert!(!item.is_stripped());
1206 // A crate has a module at its root, containing all items,
1207 // which should not be indexed. The crate-item itself is
1208 // inserted later on when serializing the search-index.
1209 if item.def_id.index != CRATE_DEF_INDEX {
1210 self.search_index.push(IndexItem {
1212 name: s.to_string(),
1213 path: path.join("::").to_string(),
1214 desc: plain_summary_line(item.doc_value()),
1217 search_type: get_index_search_type(&item),
1221 (Some(parent), None) if is_inherent_impl_item => {
1222 // We have a parent, but we don't know where they're
1223 // defined yet. Wait for later to index this item.
1224 self.orphan_impl_items.push((parent, item.clone()));
1230 // Keep track of the fully qualified path for this item.
1231 let pushed = match item.name {
1232 Some(ref n) if !n.is_empty() => {
1233 self.stack.push(n.to_string());
1240 clean::StructItem(..) | clean::EnumItem(..) |
1241 clean::TypedefItem(..) | clean::TraitItem(..) |
1242 clean::FunctionItem(..) | clean::ModuleItem(..) |
1243 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1244 clean::ConstantItem(..) | clean::StaticItem(..) |
1245 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1246 if !self.stripped_mod => {
1247 // Re-exported items mean that the same id can show up twice
1248 // in the rustdoc ast that we're looking at. We know,
1249 // however, that a re-exported item doesn't show up in the
1250 // `public_items` map, so we can skip inserting into the
1251 // paths map if there was already an entry present and we're
1252 // not a public item.
1254 !self.paths.contains_key(&item.def_id) ||
1255 self.access_levels.is_public(item.def_id)
1257 self.paths.insert(item.def_id,
1258 (self.stack.clone(), item.type_()));
1261 // Link variants to their parent enum because pages aren't emitted
1262 // for each variant.
1263 clean::VariantItem(..) if !self.stripped_mod => {
1264 let mut stack = self.stack.clone();
1266 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1269 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1270 self.paths.insert(item.def_id, (self.stack.clone(),
1277 // Maintain the parent stack
1278 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1279 let parent_pushed = match item.inner {
1280 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1281 clean::StructItem(..) | clean::UnionItem(..) => {
1282 self.parent_stack.push(item.def_id);
1283 self.parent_is_trait_impl = false;
1286 clean::ImplItem(ref i) => {
1287 self.parent_is_trait_impl = i.trait_.is_some();
1289 clean::ResolvedPath{ did, .. } => {
1290 self.parent_stack.push(did);
1294 let prim_did = t.primitive_type().and_then(|t| {
1295 self.primitive_locations.get(&t).cloned()
1299 self.parent_stack.push(did);
1310 // Once we've recursively found all the generics, hoard off all the
1311 // implementations elsewhere.
1312 let ret = self.fold_item_recur(item).and_then(|item| {
1313 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1314 // Figure out the id of this impl. This may map to a
1315 // primitive rather than always to a struct/enum.
1316 // Note: matching twice to restrict the lifetime of the `i` borrow.
1317 let mut dids = FxHashSet();
1318 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1320 clean::ResolvedPath { did, .. } |
1321 clean::BorrowedRef {
1322 type_: box clean::ResolvedPath { did, .. }, ..
1327 let did = t.primitive_type().and_then(|t| {
1328 self.primitive_locations.get(&t).cloned()
1331 if let Some(did) = did {
1337 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1338 for bound in generics {
1339 if let Some(did) = bound.def_id() {
1348 self.impls.entry(did).or_insert(vec![]).push(Impl {
1349 impl_item: item.clone(),
1358 if pushed { self.stack.pop().unwrap(); }
1359 if parent_pushed { self.parent_stack.pop().unwrap(); }
1360 self.stripped_mod = orig_stripped_mod;
1361 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1367 fn generics(&mut self, generics: &clean::Generics) {
1368 for param in &generics.params {
1369 if let clean::GenericParam::Type(ref typ) = *param {
1370 self.typarams.insert(typ.did, typ.name.clone());
1377 /// String representation of how to get back to the root path of the 'doc/'
1378 /// folder in terms of a relative URL.
1379 fn root_path(&self) -> String {
1380 repeat("../").take(self.current.len()).collect::<String>()
1383 /// Recurse in the directory structure and change the "root path" to make
1384 /// sure it always points to the top (relatively).
1385 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1386 F: FnOnce(&mut Context) -> T,
1389 panic!("Unexpected empty destination: {:?}", self.current);
1391 let prev = self.dst.clone();
1393 self.current.push(s);
1395 info!("Recursing into {}", self.dst.display());
1399 info!("Recursed; leaving {}", self.dst.display());
1401 // Go back to where we were at
1403 self.current.pop().unwrap();
1408 /// Main method for rendering a crate.
1410 /// This currently isn't parallelized, but it'd be pretty easy to add
1411 /// parallelization to this function.
1412 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1413 let mut item = match krate.module.take() {
1415 None => return Ok(()),
1417 item.name = Some(krate.name);
1419 // Render the crate documentation
1420 let mut work = vec![(self, item)];
1422 while let Some((mut cx, item)) = work.pop() {
1423 cx.item(item, |cx, item| {
1424 work.push((cx.clone(), item))
1430 fn render_item(&self,
1431 writer: &mut io::Write,
1435 // A little unfortunate that this is done like this, but it sure
1436 // does make formatting *a lot* nicer.
1437 CURRENT_LOCATION_KEY.with(|slot| {
1438 *slot.borrow_mut() = self.current.clone();
1441 let mut title = if it.is_primitive() {
1442 // No need to include the namespace for primitive types
1445 self.current.join("::")
1448 if !title.is_empty() {
1449 title.push_str("::");
1451 title.push_str(it.name.as_ref().unwrap());
1453 title.push_str(" - Rust");
1454 let tyname = it.type_().css_class();
1455 let desc = if it.is_crate() {
1456 format!("API documentation for the Rust `{}` crate.",
1457 self.shared.layout.krate)
1459 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1460 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1462 let keywords = make_item_keywords(it);
1463 let page = layout::Page {
1465 root_path: &self.root_path(),
1468 keywords: &keywords,
1469 resource_suffix: &self.shared.resource_suffix,
1474 if !self.render_redirect_pages {
1475 layout::render(writer, &self.shared.layout, &page,
1476 &Sidebar{ cx: self, item: it },
1477 &Item{ cx: self, item: it },
1478 self.shared.css_file_extension.is_some(),
1479 &self.shared.themes)?;
1481 let mut url = self.root_path();
1482 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1483 for name in &names[..names.len() - 1] {
1487 url.push_str(&item_path(ty, names.last().unwrap()));
1488 layout::redirect(writer, &url)?;
1494 /// Non-parallelized version of rendering an item. This will take the input
1495 /// item, render its contents, and then invoke the specified closure with
1496 /// all sub-items which need to be rendered.
1498 /// The rendering driver uses this closure to queue up more work.
1499 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1500 F: FnMut(&mut Context, clean::Item),
1502 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1503 // if they contain impls for public types. These modules can also
1504 // contain items such as publicly re-exported structures.
1506 // External crates will provide links to these structures, so
1507 // these modules are recursed into, but not rendered normally
1508 // (a flag on the context).
1509 if !self.render_redirect_pages {
1510 self.render_redirect_pages = item.is_stripped();
1514 // modules are special because they add a namespace. We also need to
1515 // recurse into the items of the module as well.
1516 let name = item.name.as_ref().unwrap().to_string();
1517 let mut item = Some(item);
1518 self.recurse(name, |this| {
1519 let item = item.take().unwrap();
1521 let mut buf = Vec::new();
1522 this.render_item(&mut buf, &item, false).unwrap();
1523 // buf will be empty if the module is stripped and there is no redirect for it
1524 if !buf.is_empty() {
1525 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1526 let joint_dst = this.dst.join("index.html");
1527 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1528 try_err!(dst.write_all(&buf), &joint_dst);
1531 let m = match item.inner {
1532 clean::StrippedItem(box clean::ModuleItem(m)) |
1533 clean::ModuleItem(m) => m,
1537 // Render sidebar-items.js used throughout this module.
1538 if !this.render_redirect_pages {
1539 let items = this.build_sidebar_items(&m);
1540 let js_dst = this.dst.join("sidebar-items.js");
1541 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1542 try_err!(write!(&mut js_out, "initSidebarItems({});",
1543 as_json(&items)), &js_dst);
1546 for item in m.items {
1552 } else if item.name.is_some() {
1553 let mut buf = Vec::new();
1554 self.render_item(&mut buf, &item, true).unwrap();
1555 // buf will be empty if the item is stripped and there is no redirect for it
1556 if !buf.is_empty() {
1557 let name = item.name.as_ref().unwrap();
1558 let item_type = item.type_();
1559 let file_name = &item_path(item_type, name);
1560 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1561 let joint_dst = self.dst.join(file_name);
1562 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1563 try_err!(dst.write_all(&buf), &joint_dst);
1565 // Redirect from a sane URL using the namespace to Rustdoc's
1566 // URL for the page.
1567 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1568 let redir_dst = self.dst.join(redir_name);
1569 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1572 let mut redirect_out = BufWriter::new(redirect_out);
1573 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1576 // If the item is a macro, redirect from the old macro URL (with !)
1577 // to the new one (without).
1578 // FIXME(#35705) remove this redirect.
1579 if item_type == ItemType::Macro {
1580 let redir_name = format!("{}.{}!.html", item_type, name);
1581 let redir_dst = self.dst.join(redir_name);
1582 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1583 let mut redirect_out = BufWriter::new(redirect_out);
1584 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1591 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1592 // BTreeMap instead of HashMap to get a sorted output
1593 let mut map = BTreeMap::new();
1594 for item in &m.items {
1595 if item.is_stripped() { continue }
1597 let short = item.type_().css_class();
1598 let myname = match item.name {
1600 Some(ref s) => s.to_string(),
1602 let short = short.to_string();
1603 map.entry(short).or_insert(vec![])
1604 .push((myname, Some(plain_summary_line(item.doc_value()))));
1607 if self.shared.sort_modules_alphabetically {
1608 for (_, items) in &mut map {
1617 /// Generate a url appropriate for an `href` attribute back to the source of
1620 /// The url generated, when clicked, will redirect the browser back to the
1621 /// original source code.
1623 /// If `None` is returned, then a source link couldn't be generated. This
1624 /// may happen, for example, with externally inlined items where the source
1625 /// of their crate documentation isn't known.
1626 fn src_href(&self) -> Option<String> {
1627 let mut root = self.cx.root_path();
1629 let cache = cache();
1630 let mut path = String::new();
1632 // We can safely ignore macros from other libraries
1633 let file = match self.item.source.filename {
1634 FileName::Real(ref path) => path,
1638 let (krate, path) = if self.item.def_id.is_local() {
1639 if let Some(path) = self.cx.shared.local_sources.get(file) {
1640 (&self.cx.shared.layout.krate, path)
1645 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1646 Some(&(ref name, ref src, Local)) => (name, src),
1647 Some(&(ref name, ref src, Remote(ref s))) => {
1648 root = s.to_string();
1651 Some(&(_, _, Unknown)) | None => return None,
1654 clean_srcpath(&src_root, file, false, |component| {
1655 path.push_str(component);
1658 let mut fname = file.file_name().expect("source has no filename")
1660 fname.push(".html");
1661 path.push_str(&fname.to_string_lossy());
1665 let lines = if self.item.source.loline == self.item.source.hiline {
1666 format!("{}", self.item.source.loline)
1668 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1670 Some(format!("{root}src/{krate}/{path}#{lines}",
1671 root = Escape(&root),
1678 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
1679 f: F) -> fmt::Result
1680 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
1681 write!(w, "<div class=\"docblock type-decl\">")?;
1686 impl<'a> fmt::Display for Item<'a> {
1687 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1688 debug_assert!(!self.item.is_stripped());
1689 // Write the breadcrumb trail header for the top
1690 write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
1691 match self.item.inner {
1692 clean::ModuleItem(ref m) => if m.is_crate {
1693 write!(fmt, "Crate ")?;
1695 write!(fmt, "Module ")?;
1697 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1698 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1699 clean::StructItem(..) => write!(fmt, "Struct ")?,
1700 clean::UnionItem(..) => write!(fmt, "Union ")?,
1701 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1702 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1703 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1704 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1705 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1706 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1707 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1709 // We don't generate pages for any other type.
1713 if !self.item.is_primitive() {
1714 let cur = &self.cx.current;
1715 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1716 for (i, component) in cur.iter().enumerate().take(amt) {
1717 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1718 repeat("../").take(cur.len() - i - 1)
1719 .collect::<String>(),
1723 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1724 self.item.type_(), self.item.name.as_ref().unwrap())?;
1726 write!(fmt, "</span>")?; // in-band
1727 write!(fmt, "<span class='out-of-band'>")?;
1728 if let Some(version) = self.item.stable_since() {
1729 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1733 r##"<span id='render-detail'>
1734 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1735 [<span class='inner'>−</span>]
1741 // When this item is part of a `pub use` in a downstream crate, the
1742 // [src] link in the downstream documentation will actually come back to
1743 // this page, and this link will be auto-clicked. The `id` attribute is
1744 // used to find the link to auto-click.
1745 if self.cx.shared.include_sources && !self.item.is_primitive() {
1746 if let Some(l) = self.src_href() {
1747 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1748 l, "goto source code")?;
1752 write!(fmt, "</span></h1>")?; // out-of-band
1754 match self.item.inner {
1755 clean::ModuleItem(ref m) =>
1756 item_module(fmt, self.cx, self.item, &m.items),
1757 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1758 item_function(fmt, self.cx, self.item, f),
1759 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1760 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1761 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1762 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1763 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1764 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1765 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1766 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1767 item_static(fmt, self.cx, self.item, i),
1768 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1769 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1771 // We don't generate pages for any other type.
1778 fn item_path(ty: ItemType, name: &str) -> String {
1780 ItemType::Module => format!("{}/index.html", name),
1781 _ => format!("{}.{}.html", ty.css_class(), name),
1785 fn full_path(cx: &Context, item: &clean::Item) -> String {
1786 let mut s = cx.current.join("::");
1788 s.push_str(item.name.as_ref().unwrap());
1792 fn shorter<'a>(s: Option<&'a str>) -> String {
1794 Some(s) => s.lines()
1795 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1797 (*line).chars().any(|chr|{
1798 !chr.is_whitespace()
1800 }).collect::<Vec<_>>().join("\n"),
1801 None => "".to_string()
1806 fn plain_summary_line(s: Option<&str>) -> String {
1807 let line = shorter(s).replace("\n", " ");
1808 markdown::plain_summary_line(&line[..])
1811 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1812 if let Some(ref name) = item.name {
1813 info!("Documenting {}", name);
1815 document_stability(w, cx, item)?;
1816 let prefix = render_assoc_const_value(item);
1817 document_full(w, item, cx, &prefix)?;
1821 /// Render md_text as markdown.
1822 fn render_markdown(w: &mut fmt::Formatter,
1824 links: Vec<(String, String)>,
1827 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1830 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1831 prefix: &str) -> fmt::Result {
1832 if let Some(s) = item.doc_value() {
1833 let markdown = if s.contains('\n') {
1834 format!("{} [Read more]({})",
1835 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1837 format!("{}", &plain_summary_line(Some(s)))
1839 render_markdown(w, &markdown, item.links(), prefix)?;
1840 } else if !prefix.is_empty() {
1841 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1846 fn render_assoc_const_value(item: &clean::Item) -> String {
1848 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1849 highlight::render_with_highlighting(
1850 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1861 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1862 cx: &Context, prefix: &str) -> fmt::Result {
1863 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1864 debug!("Doc block: =====\n{}\n=====", s);
1865 render_markdown(w, &*s, item.links(), prefix)?;
1866 } else if !prefix.is_empty() {
1867 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1872 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1873 let stabilities = short_stability(item, cx, true);
1874 if !stabilities.is_empty() {
1875 write!(w, "<div class='stability'>")?;
1876 for stability in stabilities {
1877 write!(w, "{}", stability)?;
1879 write!(w, "</div>")?;
1884 fn name_key(name: &str) -> (&str, u64, usize) {
1885 // find number at end
1886 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1888 // count leading zeroes
1890 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1892 // sort leading zeroes last
1893 let num_zeroes = after_zeroes - split;
1895 match name[split..].parse() {
1896 Ok(n) => (&name[..split], n, num_zeroes),
1897 Err(_) => (name, 0, num_zeroes),
1901 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1902 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1903 document(w, cx, item)?;
1905 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1907 // the order of item types in the listing
1908 fn reorder(ty: ItemType) -> u8 {
1910 ItemType::ExternCrate => 0,
1911 ItemType::Import => 1,
1912 ItemType::Primitive => 2,
1913 ItemType::Module => 3,
1914 ItemType::Macro => 4,
1915 ItemType::Struct => 5,
1916 ItemType::Enum => 6,
1917 ItemType::Constant => 7,
1918 ItemType::Static => 8,
1919 ItemType::Trait => 9,
1920 ItemType::Function => 10,
1921 ItemType::Typedef => 12,
1922 ItemType::Union => 13,
1927 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1928 let ty1 = i1.type_();
1929 let ty2 = i2.type_();
1931 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1933 let s1 = i1.stability.as_ref().map(|s| s.level);
1934 let s2 = i2.stability.as_ref().map(|s| s.level);
1936 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1937 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1940 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1941 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1942 name_key(lhs).cmp(&name_key(rhs))
1945 if cx.shared.sort_modules_alphabetically {
1946 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1948 // This call is to remove re-export duplicates in cases such as:
1953 // pub trait Double { fn foo(); }
1957 // pub use foo::bar::*;
1961 // `Double` will appear twice in the generated docs.
1963 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1964 // can be identical even if the elements are different (mostly in imports).
1965 // So in case this is an import, we keep everything by adding a "unique id"
1966 // (which is the position in the vector).
1967 indices.dedup_by_key(|i| (items[*i].def_id,
1968 if items[*i].name.as_ref().is_some() {
1969 Some(full_path(cx, &items[*i]).clone())
1974 if items[*i].is_import() {
1980 debug!("{:?}", indices);
1981 let mut curty = None;
1982 for &idx in &indices {
1983 let myitem = &items[idx];
1984 if myitem.is_stripped() {
1988 let myty = Some(myitem.type_());
1989 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1990 // Put `extern crate` and `use` re-exports in the same section.
1992 } else if myty != curty {
1993 if curty.is_some() {
1994 write!(w, "</table>")?;
1997 let (short, name) = match myty.unwrap() {
1998 ItemType::ExternCrate |
1999 ItemType::Import => ("reexports", "Re-exports"),
2000 ItemType::Module => ("modules", "Modules"),
2001 ItemType::Struct => ("structs", "Structs"),
2002 ItemType::Union => ("unions", "Unions"),
2003 ItemType::Enum => ("enums", "Enums"),
2004 ItemType::Function => ("functions", "Functions"),
2005 ItemType::Typedef => ("types", "Type Definitions"),
2006 ItemType::Static => ("statics", "Statics"),
2007 ItemType::Constant => ("constants", "Constants"),
2008 ItemType::Trait => ("traits", "Traits"),
2009 ItemType::Impl => ("impls", "Implementations"),
2010 ItemType::TyMethod => ("tymethods", "Type Methods"),
2011 ItemType::Method => ("methods", "Methods"),
2012 ItemType::StructField => ("fields", "Struct Fields"),
2013 ItemType::Variant => ("variants", "Variants"),
2014 ItemType::Macro => ("macros", "Macros"),
2015 ItemType::Primitive => ("primitives", "Primitive Types"),
2016 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2017 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2018 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2020 write!(w, "<h2 id='{id}' class='section-header'>\
2021 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2022 id = derive_id(short.to_owned()), name = name)?;
2025 match myitem.inner {
2026 clean::ExternCrateItem(ref name, ref src) => {
2027 use html::format::HRef;
2031 write!(w, "<tr><td><code>{}extern crate {} as {};",
2032 VisSpace(&myitem.visibility),
2033 HRef::new(myitem.def_id, src),
2037 write!(w, "<tr><td><code>{}extern crate {};",
2038 VisSpace(&myitem.visibility),
2039 HRef::new(myitem.def_id, name))?
2042 write!(w, "</code></td></tr>")?;
2045 clean::ImportItem(ref import) => {
2046 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2047 VisSpace(&myitem.visibility), *import)?;
2051 if myitem.name.is_none() { continue }
2053 let stabilities = short_stability(myitem, cx, false);
2055 let stab_docs = if !stabilities.is_empty() {
2057 .map(|s| format!("[{}]", s))
2058 .collect::<Vec<_>>()
2065 let unsafety_flag = match myitem.inner {
2066 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2067 if func.unsafety == hir::Unsafety::Unsafe => {
2068 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2073 let doc_value = myitem.doc_value().unwrap_or("");
2075 <tr class='{stab} module-item'>
2076 <td><a class=\"{class}\" href=\"{href}\"
2077 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2078 <td class='docblock-short'>
2082 name = *myitem.name.as_ref().unwrap(),
2083 stab_docs = stab_docs,
2084 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2085 class = myitem.type_(),
2086 stab = myitem.stability_class().unwrap_or("".to_string()),
2087 unsafety_flag = unsafety_flag,
2088 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2089 title_type = myitem.type_(),
2090 title = full_path(cx, myitem))?;
2095 if curty.is_some() {
2096 write!(w, "</table>")?;
2101 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2102 let mut stability = vec![];
2104 if let Some(stab) = item.stability.as_ref() {
2105 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2106 format!(": {}", stab.deprecated_reason)
2110 if !stab.deprecated_since.is_empty() {
2111 let since = if show_reason {
2112 format!(" since {}", Escape(&stab.deprecated_since))
2116 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2117 format!("Deprecated{}{}",
2119 MarkdownHtml(&deprecated_reason))
2121 format!("Deprecating in {}{}",
2122 Escape(&stab.deprecated_since),
2123 MarkdownHtml(&deprecated_reason))
2125 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2128 if stab.level == stability::Unstable {
2130 let unstable_extra = match (!stab.feature.is_empty(),
2131 &cx.shared.issue_tracker_base_url,
2133 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2134 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2135 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2136 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2137 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2140 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2143 if stab.unstable_reason.is_empty() {
2144 stability.push(format!("<div class='stab unstable'>\
2145 <span class=microscope>🔬</span> \
2146 This is a nightly-only experimental API. {}\
2150 let text = format!("<summary><span class=microscope>🔬</span> \
2151 This is a nightly-only experimental API. {}\
2154 MarkdownHtml(&stab.unstable_reason));
2155 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2159 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2162 } else if let Some(depr) = item.deprecation.as_ref() {
2163 let note = if show_reason && !depr.note.is_empty() {
2164 format!(": {}", depr.note)
2168 let since = if show_reason && !depr.since.is_empty() {
2169 format!(" since {}", Escape(&depr.since))
2174 let text = if stability::deprecation_in_effect(&depr.since) {
2175 format!("Deprecated{}{}",
2177 MarkdownHtml(¬e))
2179 format!("Deprecating in {}{}",
2180 Escape(&depr.since),
2181 MarkdownHtml(¬e))
2183 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2186 if let Some(ref cfg) = item.attrs.cfg {
2187 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2188 cfg.render_long_html()
2190 cfg.render_short_html()
2197 struct Initializer<'a>(&'a str);
2199 impl<'a> fmt::Display for Initializer<'a> {
2200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2201 let Initializer(s) = *self;
2202 if s.is_empty() { return Ok(()); }
2203 write!(f, "<code> = </code>")?;
2204 write!(f, "<code>{}</code>", Escape(s))
2208 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2209 c: &clean::Constant) -> fmt::Result {
2210 write!(w, "<pre class='rust const'>")?;
2211 render_attributes(w, it)?;
2212 write!(w, "{vis}const \
2213 {name}: {typ}{init}</pre>",
2214 vis = VisSpace(&it.visibility),
2215 name = it.name.as_ref().unwrap(),
2217 init = Initializer(&c.expr))?;
2221 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2222 s: &clean::Static) -> fmt::Result {
2223 write!(w, "<pre class='rust static'>")?;
2224 render_attributes(w, it)?;
2225 write!(w, "{vis}static {mutability}\
2226 {name}: {typ}{init}</pre>",
2227 vis = VisSpace(&it.visibility),
2228 mutability = MutableSpace(s.mutability),
2229 name = it.name.as_ref().unwrap(),
2231 init = Initializer(&s.expr))?;
2235 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2236 f: &clean::Function) -> fmt::Result {
2237 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2238 VisSpace(&it.visibility),
2239 ConstnessSpace(f.constness),
2240 UnsafetySpace(f.unsafety),
2242 it.name.as_ref().unwrap(),
2244 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2245 render_attributes(w, it)?;
2247 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2248 vis = VisSpace(&it.visibility),
2249 constness = ConstnessSpace(f.constness),
2250 unsafety = UnsafetySpace(f.unsafety),
2251 abi = AbiSpace(f.abi),
2252 name = it.name.as_ref().unwrap(),
2253 generics = f.generics,
2254 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2263 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2264 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2265 write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2266 // If there's already another implementor that has the same abbridged name, use the
2267 // full path, for example in `std::iter::ExactSizeIterator`
2268 let use_absolute = match implementor.inner_impl().for_ {
2269 clean::ResolvedPath { ref path, is_generic: false, .. } |
2270 clean::BorrowedRef {
2271 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2273 } => implementor_dups[path.last_name()].1,
2276 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2277 for it in &implementor.inner_impl().items {
2278 if let clean::TypedefItem(ref tydef, _) = it.inner {
2279 write!(w, "<span class=\"where fmt-newline\"> ")?;
2280 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2281 write!(w, ";</span>")?;
2284 write!(w, "</code><td>")?;
2285 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2286 write!(w, "<div class='out-of-band'>")?;
2287 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2288 l, "goto source code")?;
2289 write!(w, "</div>")?;
2291 writeln!(w, "</td></tr></tbody></table></li>")?;
2295 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2296 traits: Vec<&&Impl>,
2297 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2299 let did = i.trait_did().unwrap();
2300 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2301 render_impl(w, cx, i, assoc_link,
2302 RenderMode::Normal, containing_item.stable_since(), true)?;
2307 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2308 t: &clean::Trait) -> fmt::Result {
2309 let mut bounds = String::new();
2310 let mut bounds_plain = String::new();
2311 if !t.bounds.is_empty() {
2312 if !bounds.is_empty() {
2314 bounds_plain.push(' ');
2316 bounds.push_str(": ");
2317 bounds_plain.push_str(": ");
2318 for (i, p) in t.bounds.iter().enumerate() {
2320 bounds.push_str(" + ");
2321 bounds_plain.push_str(" + ");
2323 bounds.push_str(&format!("{}", *p));
2324 bounds_plain.push_str(&format!("{:#}", *p));
2328 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2329 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2330 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2331 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2333 // Output the trait definition
2334 wrap_into_docblock(w, |w| {
2335 write!(w, "<pre class='rust trait'>")?;
2336 render_attributes(w, it)?;
2337 write!(w, "{}{}{}trait {}{}{}",
2338 VisSpace(&it.visibility),
2339 UnsafetySpace(t.unsafety),
2340 if t.is_auto { "auto " } else { "" },
2341 it.name.as_ref().unwrap(),
2345 if !t.generics.where_predicates.is_empty() {
2346 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2351 if t.items.is_empty() {
2352 write!(w, "{{ }}")?;
2354 // FIXME: we should be using a derived_id for the Anchors here
2358 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2361 if !types.is_empty() && !consts.is_empty() {
2366 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2369 if !consts.is_empty() && !required.is_empty() {
2372 for (pos, m) in required.iter().enumerate() {
2374 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2377 if pos < required.len() - 1 {
2378 write!(w, "<div class='item-spacer'></div>")?;
2381 if !required.is_empty() && !provided.is_empty() {
2384 for (pos, m) in provided.iter().enumerate() {
2386 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2388 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2389 write!(w, ",\n {{ ... }}\n")?;
2392 write!(w, " {{ ... }}\n")?;
2395 if pos < provided.len() - 1 {
2396 write!(w, "<div class='item-spacer'></div>")?;
2404 // Trait documentation
2405 document(w, cx, it)?;
2407 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2409 let name = m.name.as_ref().unwrap();
2410 let item_type = m.type_();
2411 let id = derive_id(format!("{}.{}", item_type, name));
2412 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2413 write!(w, "{extra}<h3 id='{id}' class='method'>\
2414 <span id='{ns_id}' class='invisible'><code>",
2415 extra = render_spotlight_traits(m)?,
2418 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2419 write!(w, "</code>")?;
2420 render_stability_since(w, m, t)?;
2421 write!(w, "</span></h3>")?;
2422 document(w, cx, m)?;
2426 if !types.is_empty() {
2428 <h2 id='associated-types' class='small-section-header'>
2429 Associated Types<a href='#associated-types' class='anchor'></a>
2431 <div class='methods'>
2434 trait_item(w, cx, *t, it)?;
2436 write!(w, "</div>")?;
2439 if !consts.is_empty() {
2441 <h2 id='associated-const' class='small-section-header'>
2442 Associated Constants<a href='#associated-const' class='anchor'></a>
2444 <div class='methods'>
2447 trait_item(w, cx, *t, it)?;
2449 write!(w, "</div>")?;
2452 // Output the documentation for each function individually
2453 if !required.is_empty() {
2455 <h2 id='required-methods' class='small-section-header'>
2456 Required Methods<a href='#required-methods' class='anchor'></a>
2458 <div class='methods'>
2460 for m in &required {
2461 trait_item(w, cx, *m, it)?;
2463 write!(w, "</div>")?;
2465 if !provided.is_empty() {
2467 <h2 id='provided-methods' class='small-section-header'>
2468 Provided Methods<a href='#provided-methods' class='anchor'></a>
2470 <div class='methods'>
2472 for m in &provided {
2473 trait_item(w, cx, *m, it)?;
2475 write!(w, "</div>")?;
2478 // If there are methods directly on this trait object, render them here.
2479 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2481 let cache = cache();
2483 <h2 id='implementors' class='small-section-header'>
2484 Implementors<a href='#implementors' class='anchor'></a>
2486 <ul class='item-list' id='implementors-list'>
2489 let synthetic_impl_header = "
2490 <h2 id='synthetic-implementors' class='small-section-header'>
2491 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2493 <ul class='item-list' id='synthetic-implementors-list'>
2496 let mut synthetic_types = Vec::new();
2498 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2499 // The DefId is for the first Type found with that name. The bool is
2500 // if any Types with the same name but different DefId have been found.
2501 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2502 for implementor in implementors {
2503 match implementor.inner_impl().for_ {
2504 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2505 clean::BorrowedRef {
2506 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2509 let &mut (prev_did, ref mut has_duplicates) =
2510 implementor_dups.entry(path.last_name()).or_insert((did, false));
2511 if prev_did != did {
2512 *has_duplicates = true;
2519 let (local, foreign) = implementors.iter()
2520 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2521 .map_or(true, |d| cache.paths.contains_key(&d)));
2524 let (synthetic, concrete) = local.iter()
2525 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2528 if !foreign.is_empty() {
2530 <h2 id='foreign-impls' class='small-section-header'>
2531 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2535 for implementor in foreign {
2536 let assoc_link = AssocItemLink::GotoSource(
2537 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2539 render_impl(w, cx, &implementor, assoc_link,
2540 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2544 write!(w, "{}", impl_header)?;
2545 for implementor in concrete {
2546 render_implementor(cx, implementor, w, &implementor_dups)?;
2548 write!(w, "</ul>")?;
2551 write!(w, "{}", synthetic_impl_header)?;
2552 for implementor in synthetic {
2553 synthetic_types.extend(
2554 collect_paths_for_type(implementor.inner_impl().for_.clone())
2556 render_implementor(cx, implementor, w, &implementor_dups)?;
2558 write!(w, "</ul>")?;
2561 // even without any implementations to write in, we still want the heading and list, so the
2562 // implementors javascript file pulled in below has somewhere to write the impls into
2563 write!(w, "{}", impl_header)?;
2564 write!(w, "</ul>")?;
2567 write!(w, "{}", synthetic_impl_header)?;
2568 write!(w, "</ul>")?;
2571 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2572 as_json(&synthetic_types))?;
2574 write!(w, r#"<script type="text/javascript" async
2575 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2577 root_path = vec![".."; cx.current.len()].join("/"),
2578 path = if it.def_id.is_local() {
2579 cx.current.join("/")
2581 let (ref path, _) = cache.external_paths[&it.def_id];
2582 path[..path.len() - 1].join("/")
2584 ty = it.type_().css_class(),
2585 name = *it.name.as_ref().unwrap())?;
2589 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2590 use html::item_type::ItemType::*;
2592 let name = it.name.as_ref().unwrap();
2593 let ty = match it.type_() {
2594 Typedef | AssociatedType => AssociatedType,
2598 let anchor = format!("#{}.{}", ty, name);
2600 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2601 AssocItemLink::Anchor(None) => anchor,
2602 AssocItemLink::GotoSource(did, _) => {
2603 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2608 fn assoc_const(w: &mut fmt::Formatter,
2611 _default: Option<&String>,
2612 link: AssocItemLink) -> fmt::Result {
2613 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2614 VisSpace(&it.visibility),
2615 naive_assoc_href(it, link),
2616 it.name.as_ref().unwrap(),
2621 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2622 bounds: &Vec<clean::TyParamBound>,
2623 default: Option<&clean::Type>,
2624 link: AssocItemLink) -> fmt::Result {
2625 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2626 naive_assoc_href(it, link),
2627 it.name.as_ref().unwrap())?;
2628 if !bounds.is_empty() {
2629 write!(w, ": {}", TyParamBounds(bounds))?
2631 if let Some(default) = default {
2632 write!(w, " = {}", default)?;
2637 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2638 ver: Option<&'a str>,
2639 containing_ver: Option<&'a str>) -> fmt::Result {
2640 if let Some(v) = ver {
2641 if containing_ver != ver && v.len() > 0 {
2642 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2649 fn render_stability_since(w: &mut fmt::Formatter,
2651 containing_item: &clean::Item) -> fmt::Result {
2652 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2655 fn render_assoc_item(w: &mut fmt::Formatter,
2657 link: AssocItemLink,
2658 parent: ItemType) -> fmt::Result {
2659 fn method(w: &mut fmt::Formatter,
2661 unsafety: hir::Unsafety,
2662 constness: hir::Constness,
2664 g: &clean::Generics,
2666 link: AssocItemLink,
2669 let name = meth.name.as_ref().unwrap();
2670 let anchor = format!("#{}.{}", meth.type_(), name);
2671 let href = match link {
2672 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2673 AssocItemLink::Anchor(None) => anchor,
2674 AssocItemLink::GotoSource(did, provided_methods) => {
2675 // We're creating a link from an impl-item to the corresponding
2676 // trait-item and need to map the anchored type accordingly.
2677 let ty = if provided_methods.contains(name) {
2683 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2686 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2687 VisSpace(&meth.visibility),
2688 ConstnessSpace(constness),
2689 UnsafetySpace(unsafety),
2693 let (indent, end_newline) = if parent == ItemType::Trait {
2699 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2700 {generics}{decl}{where_clause}",
2701 VisSpace(&meth.visibility),
2702 ConstnessSpace(constness),
2703 UnsafetySpace(unsafety),
2713 where_clause = WhereClause {
2720 clean::StrippedItem(..) => Ok(()),
2721 clean::TyMethodItem(ref m) => {
2722 method(w, item, m.unsafety, hir::Constness::NotConst,
2723 m.abi, &m.generics, &m.decl, link, parent)
2725 clean::MethodItem(ref m) => {
2726 method(w, item, m.unsafety, m.constness,
2727 m.abi, &m.generics, &m.decl, link, parent)
2729 clean::AssociatedConstItem(ref ty, ref default) => {
2730 assoc_const(w, item, ty, default.as_ref(), link)
2732 clean::AssociatedTypeItem(ref bounds, ref default) => {
2733 assoc_type(w, item, bounds, default.as_ref(), link)
2735 _ => panic!("render_assoc_item called on non-associated-item")
2739 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2740 s: &clean::Struct) -> fmt::Result {
2741 wrap_into_docblock(w, |w| {
2742 write!(w, "<pre class='rust struct'>")?;
2743 render_attributes(w, it)?;
2754 document(w, cx, it)?;
2755 let mut fields = s.fields.iter().filter_map(|f| {
2757 clean::StructFieldItem(ref ty) => Some((f, ty)),
2761 if let doctree::Plain = s.struct_type {
2762 if fields.peek().is_some() {
2763 write!(w, "<h2 id='fields' class='fields small-section-header'>
2764 Fields<a href='#fields' class='anchor'></a></h2>")?;
2765 for (field, ty) in fields {
2766 let id = derive_id(format!("{}.{}",
2767 ItemType::StructField,
2768 field.name.as_ref().unwrap()));
2769 let ns_id = derive_id(format!("{}.{}",
2770 field.name.as_ref().unwrap(),
2771 ItemType::StructField.name_space()));
2772 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2773 <a href=\"#{id}\" class=\"anchor field\"></a>
2774 <span id=\"{ns_id}\" class='invisible'>
2775 <code>{name}: {ty}</code>
2777 item_type = ItemType::StructField,
2780 name = field.name.as_ref().unwrap(),
2782 if let Some(stability_class) = field.stability_class() {
2783 write!(w, "<span class='stab {stab}'></span>",
2784 stab = stability_class)?;
2786 document(w, cx, field)?;
2790 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2793 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2794 s: &clean::Union) -> fmt::Result {
2795 wrap_into_docblock(w, |w| {
2796 write!(w, "<pre class='rust union'>")?;
2797 render_attributes(w, it)?;
2807 document(w, cx, it)?;
2808 let mut fields = s.fields.iter().filter_map(|f| {
2810 clean::StructFieldItem(ref ty) => Some((f, ty)),
2814 if fields.peek().is_some() {
2815 write!(w, "<h2 id='fields' class='fields small-section-header'>
2816 Fields<a href='#fields' class='anchor'></a></h2>")?;
2817 for (field, ty) in fields {
2818 let name = field.name.as_ref().expect("union field name");
2819 let id = format!("{}.{}", ItemType::StructField, name);
2820 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2821 <a href=\"#{id}\" class=\"anchor field\"></a>\
2822 <span class='invisible'><code>{name}: {ty}</code></span>\
2826 shortty = ItemType::StructField,
2828 if let Some(stability_class) = field.stability_class() {
2829 write!(w, "<span class='stab {stab}'></span>",
2830 stab = stability_class)?;
2832 document(w, cx, field)?;
2835 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2838 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2839 e: &clean::Enum) -> fmt::Result {
2840 wrap_into_docblock(w, |w| {
2841 write!(w, "<pre class='rust enum'>")?;
2842 render_attributes(w, it)?;
2843 write!(w, "{}enum {}{}{}",
2844 VisSpace(&it.visibility),
2845 it.name.as_ref().unwrap(),
2847 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2848 if e.variants.is_empty() && !e.variants_stripped {
2849 write!(w, " {{}}")?;
2851 write!(w, " {{\n")?;
2852 for v in &e.variants {
2854 let name = v.name.as_ref().unwrap();
2856 clean::VariantItem(ref var) => {
2858 clean::VariantKind::CLike => write!(w, "{}", name)?,
2859 clean::VariantKind::Tuple(ref tys) => {
2860 write!(w, "{}(", name)?;
2861 for (i, ty) in tys.iter().enumerate() {
2863 write!(w, ", ")?
2865 write!(w, "{}", *ty)?;
2869 clean::VariantKind::Struct(ref s) => {
2885 if e.variants_stripped {
2886 write!(w, " // some variants omitted\n")?;
2893 document(w, cx, it)?;
2894 if !e.variants.is_empty() {
2895 write!(w, "<h2 id='variants' class='variants small-section-header'>
2896 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2897 for variant in &e.variants {
2898 let id = derive_id(format!("{}.{}",
2900 variant.name.as_ref().unwrap()));
2901 let ns_id = derive_id(format!("{}.{}",
2902 variant.name.as_ref().unwrap(),
2903 ItemType::Variant.name_space()));
2904 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2905 <a href=\"#{id}\" class=\"anchor field\"></a>\
2906 <span id='{ns_id}' class='invisible'><code>{name}",
2909 name = variant.name.as_ref().unwrap())?;
2910 if let clean::VariantItem(ref var) = variant.inner {
2911 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2913 for (i, ty) in tys.iter().enumerate() {
2915 write!(w, ", ")?;
2917 write!(w, "{}", *ty)?;
2922 write!(w, "</code></span></span>")?;
2923 document(w, cx, variant)?;
2925 use clean::{Variant, VariantKind};
2926 if let clean::VariantItem(Variant {
2927 kind: VariantKind::Struct(ref s)
2928 }) = variant.inner {
2929 let variant_id = derive_id(format!("{}.{}.fields",
2931 variant.name.as_ref().unwrap()));
2932 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2934 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2935 <table>", name = variant.name.as_ref().unwrap())?;
2936 for field in &s.fields {
2937 use clean::StructFieldItem;
2938 if let StructFieldItem(ref ty) = field.inner {
2939 let id = derive_id(format!("variant.{}.field.{}",
2940 variant.name.as_ref().unwrap(),
2941 field.name.as_ref().unwrap()));
2942 let ns_id = derive_id(format!("{}.{}.{}.{}",
2943 variant.name.as_ref().unwrap(),
2944 ItemType::Variant.name_space(),
2945 field.name.as_ref().unwrap(),
2946 ItemType::StructField.name_space()));
2947 write!(w, "<tr><td \
2949 <span id='{ns_id}' class='invisible'>\
2950 <code>{f}: {t}</code></span></td><td>",
2953 f = field.name.as_ref().unwrap(),
2955 document(w, cx, field)?;
2956 write!(w, "</td></tr>")?;
2959 write!(w, "</table></span>")?;
2961 render_stability_since(w, variant, it)?;
2964 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2968 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2969 let name = attr.name();
2972 Some(format!("{}", name))
2973 } else if let Some(v) = attr.value_str() {
2974 Some(format!("{} = {:?}", name, v.as_str()))
2975 } else if let Some(values) = attr.meta_item_list() {
2976 let display: Vec<_> = values.iter().filter_map(|attr| {
2977 attr.meta_item().and_then(|mi| render_attribute(mi))
2980 if display.len() > 0 {
2981 Some(format!("{}({})", name, display.join(", ")))
2990 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2997 "unsafe_destructor_blind_to_params"
3000 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3001 let mut attrs = String::new();
3003 for attr in &it.attrs.other_attrs {
3004 let name = attr.name().unwrap();
3005 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3008 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3009 attrs.push_str(&format!("#[{}]\n", s));
3012 if attrs.len() > 0 {
3013 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3018 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3019 g: Option<&clean::Generics>,
3020 ty: doctree::StructType,
3021 fields: &[clean::Item],
3023 structhead: bool) -> fmt::Result {
3025 VisSpace(&it.visibility),
3026 if structhead {"struct "} else {""},
3027 it.name.as_ref().unwrap())?;
3028 if let Some(g) = g {
3033 if let Some(g) = g {
3034 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3036 let mut has_visible_fields = false;
3038 for field in fields {
3039 if let clean::StructFieldItem(ref ty) = field.inner {
3040 write!(w, "\n{} {}{}: {},",
3042 VisSpace(&field.visibility),
3043 field.name.as_ref().unwrap(),
3045 has_visible_fields = true;
3049 if has_visible_fields {
3050 if it.has_stripped_fields().unwrap() {
3051 write!(w, "\n{} // some fields omitted", tab)?;
3053 write!(w, "\n{}", tab)?;
3054 } else if it.has_stripped_fields().unwrap() {
3055 // If there are no visible fields we can just display
3056 // `{ /* fields omitted */ }` to save space.
3057 write!(w, " /* fields omitted */ ")?;
3063 for (i, field) in fields.iter().enumerate() {
3068 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3071 clean::StructFieldItem(ref ty) => {
3072 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3078 if let Some(g) = g {
3079 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3084 // Needed for PhantomData.
3085 if let Some(g) = g {
3086 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3094 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3095 g: Option<&clean::Generics>,
3096 fields: &[clean::Item],
3098 structhead: bool) -> fmt::Result {
3100 VisSpace(&it.visibility),
3101 if structhead {"union "} else {""},
3102 it.name.as_ref().unwrap())?;
3103 if let Some(g) = g {
3104 write!(w, "{}", g)?;
3105 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3108 write!(w, " {{\n{}", tab)?;
3109 for field in fields {
3110 if let clean::StructFieldItem(ref ty) = field.inner {
3111 write!(w, " {}{}: {},\n{}",
3112 VisSpace(&field.visibility),
3113 field.name.as_ref().unwrap(),
3119 if it.has_stripped_fields().unwrap() {
3120 write!(w, " // some fields omitted\n{}", tab)?;
3126 #[derive(Copy, Clone)]
3127 enum AssocItemLink<'a> {
3128 Anchor(Option<&'a str>),
3129 GotoSource(DefId, &'a FxHashSet<String>),
3132 impl<'a> AssocItemLink<'a> {
3133 fn anchor(&self, id: &'a String) -> Self {
3135 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3136 ref other => *other,
3141 enum AssocItemRender<'a> {
3143 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3146 #[derive(Copy, Clone, PartialEq)]
3149 ForDeref { mut_: bool },
3152 fn render_assoc_items(w: &mut fmt::Formatter,
3154 containing_item: &clean::Item,
3156 what: AssocItemRender) -> fmt::Result {
3158 let v = match c.impls.get(&it) {
3160 None => return Ok(()),
3162 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3163 i.inner_impl().trait_.is_none()
3165 if !non_trait.is_empty() {
3166 let render_mode = match what {
3167 AssocItemRender::All => {
3169 <h2 id='methods' class='small-section-header'>
3170 Methods<a href='#methods' class='anchor'></a>
3175 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3177 <h2 id='deref-methods' class='small-section-header'>
3178 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3181 RenderMode::ForDeref { mut_: deref_mut_ }
3184 for i in &non_trait {
3185 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3186 containing_item.stable_since(), true)?;
3189 if let AssocItemRender::DerefFor { .. } = what {
3192 if !traits.is_empty() {
3193 let deref_impl = traits.iter().find(|t| {
3194 t.inner_impl().trait_.def_id() == c.deref_trait_did
3196 if let Some(impl_) = deref_impl {
3197 let has_deref_mut = traits.iter().find(|t| {
3198 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3200 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3203 let (synthetic, concrete) = traits
3205 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3208 <h2 id='implementations' class='small-section-header'>
3209 Trait Implementations<a href='#implementations' class='anchor'></a>
3211 <div id='implementations-list'>
3213 render_impls(cx, w, concrete, containing_item)?;
3214 write!(w, "</div>")?;
3216 if !synthetic.is_empty() {
3218 <h2 id='synthetic-implementations' class='small-section-header'>
3219 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3221 <div id='synthetic-implementations-list'>
3223 render_impls(cx, w, synthetic, containing_item)?;
3224 write!(w, "</div>")?;
3230 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3231 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3232 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3233 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3235 clean::TypedefItem(ref t, true) => Some(&t.type_),
3238 }).next().expect("Expected associated type binding");
3239 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3240 deref_mut_: deref_mut };
3241 if let Some(did) = target.def_id() {
3242 render_assoc_items(w, cx, container_item, did, what)
3244 if let Some(prim) = target.primitive_type() {
3245 if let Some(&did) = cache().primitive_locations.get(&prim) {
3246 render_assoc_items(w, cx, container_item, did, what)?;
3253 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3254 let self_type_opt = match item.inner {
3255 clean::MethodItem(ref method) => method.decl.self_type(),
3256 clean::TyMethodItem(ref method) => method.decl.self_type(),
3260 if let Some(self_ty) = self_type_opt {
3261 let (by_mut_ref, by_box, by_value) = match self_ty {
3262 SelfTy::SelfBorrowed(_, mutability) |
3263 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3264 (mutability == Mutability::Mutable, false, false)
3266 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3267 (false, Some(did) == cache().owned_box_did, false)
3269 SelfTy::SelfValue => (false, false, true),
3270 _ => (false, false, false),
3273 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3279 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3280 let mut out = String::new();
3283 clean::FunctionItem(clean::Function { ref decl, .. }) |
3284 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3285 clean::MethodItem(clean::Method { ref decl, .. }) |
3286 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3287 out = spotlight_decl(decl)?;
3295 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3296 let mut out = String::new();
3297 let mut trait_ = String::new();
3299 if let Some(did) = decl.output.def_id() {
3301 if let Some(impls) = c.impls.get(&did) {
3303 let impl_ = i.inner_impl();
3304 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3307 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3308 <code class=\"content\">",
3310 trait_.push_str(&format!("{}", impl_.for_));
3313 //use the "where" class here to make it small
3314 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3315 let t_did = impl_.trait_.def_id().unwrap();
3316 for it in &impl_.items {
3317 if let clean::TypedefItem(ref tydef, _) = it.inner {
3318 out.push_str("<span class=\"where fmt-newline\"> ");
3319 assoc_type(&mut out, it, &vec![],
3321 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3322 out.push_str(";</span>");
3330 if !out.is_empty() {
3331 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3332 <span class='tooltiptext'>Important traits for {}</span></div>\
3333 <div class=\"content hidden\">",
3335 out.push_str("</code></div></div>");
3341 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3342 render_mode: RenderMode, outer_version: Option<&str>,
3343 show_def_docs: bool) -> fmt::Result {
3344 if render_mode == RenderMode::Normal {
3345 let id = derive_id(match i.inner_impl().trait_ {
3346 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3347 None => "impl".to_string(),
3349 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3350 <tbody><tr><td><code>{}</code>",
3351 id, i.inner_impl())?;
3352 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3353 write!(w, "</span></td><td><span class='out-of-band'>")?;
3354 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3355 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3356 write!(w, "<div class='ghost'></div>")?;
3357 render_stability_since_raw(w, since, outer_version)?;
3358 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3359 l, "goto source code")?;
3361 render_stability_since_raw(w, since, outer_version)?;
3363 write!(w, "</span></td></tr></tbody></table></h3>")?;
3364 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3365 write!(w, "<div class='docblock'>{}</div>",
3366 Markdown(&*dox, &i.impl_item.links()))?;
3370 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3371 link: AssocItemLink, render_mode: RenderMode,
3372 is_default_item: bool, outer_version: Option<&str>,
3373 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3374 let item_type = item.type_();
3375 let name = item.name.as_ref().unwrap();
3377 let render_method_item: bool = match render_mode {
3378 RenderMode::Normal => true,
3379 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3383 clean::MethodItem(clean::Method { ref decl, .. }) |
3384 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3385 // Only render when the method is not static or we allow static methods
3386 if render_method_item {
3387 let id = derive_id(format!("{}.{}", item_type, name));
3388 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3389 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3390 write!(w, "{}", spotlight_decl(decl)?)?;
3391 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3392 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3393 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3394 write!(w, "</code>")?;
3395 if let Some(l) = (Item { cx, item }).src_href() {
3396 write!(w, "</span></td><td><span class='out-of-band'>")?;
3397 write!(w, "<div class='ghost'></div>")?;
3398 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3399 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3400 l, "goto source code")?;
3402 write!(w, "</td><td>")?;
3403 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3405 write!(w, "</td></tr></tbody></table></span></h4>")?;
3408 clean::TypedefItem(ref tydef, _) => {
3409 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3410 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3411 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3412 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3413 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3414 write!(w, "</code></span></h4>\n")?;
3416 clean::AssociatedConstItem(ref ty, ref default) => {
3417 let id = derive_id(format!("{}.{}", item_type, name));
3418 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3419 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3420 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3421 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3422 write!(w, "</code></span></h4>\n")?;
3424 clean::AssociatedTypeItem(ref bounds, ref default) => {
3425 let id = derive_id(format!("{}.{}", item_type, name));
3426 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3427 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3428 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3429 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3430 write!(w, "</code></span></h4>\n")?;
3432 clean::StrippedItem(..) => return Ok(()),
3433 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3436 if render_method_item || render_mode == RenderMode::Normal {
3437 let prefix = render_assoc_const_value(item);
3439 if !is_default_item {
3440 if let Some(t) = trait_ {
3441 // The trait item may have been stripped so we might not
3442 // find any documentation or stability for it.
3443 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3444 // We need the stability of the item from the trait
3445 // because impls can't have a stability.
3446 document_stability(w, cx, it)?;
3447 if item.doc_value().is_some() {
3448 document_full(w, item, cx, &prefix)?;
3449 } else if show_def_docs {
3450 // In case the item isn't documented,
3451 // provide short documentation from the trait.
3452 document_short(w, it, link, &prefix)?;
3456 document_stability(w, cx, item)?;
3458 document_full(w, item, cx, &prefix)?;
3462 document_stability(w, cx, item)?;
3464 document_short(w, item, link, &prefix)?;
3471 let traits = &cache().traits;
3472 let trait_ = i.trait_did().map(|did| &traits[&did]);
3475 write!(w, "<span class='docblock autohide'>")?;
3478 write!(w, "<div class='impl-items'>")?;
3479 for trait_item in &i.inner_impl().items {
3480 doc_impl_item(w, cx, trait_item, link, render_mode,
3481 false, outer_version, trait_, show_def_docs)?;
3484 fn render_default_items(w: &mut fmt::Formatter,
3488 render_mode: RenderMode,
3489 outer_version: Option<&str>,
3490 show_def_docs: bool) -> fmt::Result {
3491 for trait_item in &t.items {
3492 let n = trait_item.name.clone();
3493 if i.items.iter().find(|m| m.name == n).is_some() {
3496 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3497 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3499 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3500 outer_version, None, show_def_docs)?;
3505 // If we've implemented a trait, then also emit documentation for all
3506 // default items which weren't overridden in the implementation block.
3507 if let Some(t) = trait_ {
3508 render_default_items(w, cx, t, &i.inner_impl(),
3509 render_mode, outer_version, show_def_docs)?;
3511 write!(w, "</div>")?;
3514 write!(w, "</span>")?;
3520 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3521 t: &clean::Typedef) -> fmt::Result {
3522 write!(w, "<pre class='rust typedef'>")?;
3523 render_attributes(w, it)?;
3524 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3525 it.name.as_ref().unwrap(),
3527 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3530 document(w, cx, it)?;
3532 // Render any items associated directly to this alias, as otherwise they
3533 // won't be visible anywhere in the docs. It would be nice to also show
3534 // associated items from the aliased type (see discussion in #32077), but
3535 // we need #14072 to make sense of the generics.
3536 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3539 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3540 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3541 render_attributes(w, it)?;
3544 " {}type {};\n}}</pre>",
3545 VisSpace(&it.visibility),
3546 it.name.as_ref().unwrap(),
3549 document(w, cx, it)?;
3551 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3554 impl<'a> fmt::Display for Sidebar<'a> {
3555 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3558 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3560 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3561 || it.is_enum() || it.is_mod() || it.is_typedef() {
3562 write!(fmt, "<p class='location'>")?;
3564 clean::StructItem(..) => write!(fmt, "Struct ")?,
3565 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3566 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3567 clean::UnionItem(..) => write!(fmt, "Union ")?,
3568 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3569 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3570 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3571 clean::ModuleItem(..) => if it.is_crate() {
3572 write!(fmt, "Crate ")?;
3574 write!(fmt, "Module ")?;
3578 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3579 write!(fmt, "</p>")?;
3583 if let Some(ref version) = cache().crate_version {
3585 "<div class='block version'>\
3592 write!(fmt, "<div class=\"sidebar-elems\">")?;
3594 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3595 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3596 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3597 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3598 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3599 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3600 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3601 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3605 // The sidebar is designed to display sibling functions, modules and
3606 // other miscellaneous information. since there are lots of sibling
3607 // items (and that causes quadratic growth in large modules),
3608 // we refactor common parts into a shared JavaScript file per module.
3609 // still, we don't move everything into JS because we want to preserve
3610 // as much HTML as possible in order to allow non-JS-enabled browsers
3611 // to navigate the documentation (though slightly inefficiently).
3613 write!(fmt, "<p class='location'>")?;
3614 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3616 write!(fmt, "::<wbr>")?;
3618 write!(fmt, "<a href='{}index.html'>{}</a>",
3619 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3622 write!(fmt, "</p>")?;
3624 // Sidebar refers to the enclosing module, not this module.
3625 let relpath = if it.is_mod() { "../" } else { "" };
3627 "<script>window.sidebarCurrent = {{\
3632 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3633 ty = it.type_().css_class(),
3636 // There is no sidebar-items.js beyond the crate root path
3637 // FIXME maybe dynamic crate loading can be merged here
3639 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3642 // Closes sidebar-elems div.
3643 write!(fmt, "</div>")?;
3649 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3650 i.items.iter().filter_map(|item| {
3652 // Maybe check with clean::Visibility::Public as well?
3653 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3654 if !for_deref || should_render_item(item, false) {
3655 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3662 }).collect::<Vec<_>>()
3665 // The point is to url encode any potential character from a type with genericity.
3666 fn small_url_encode(s: &str) -> String {
3667 s.replace("<", "%3C")
3668 .replace(">", "%3E")
3669 .replace(" ", "%20")
3670 .replace("?", "%3F")
3671 .replace("'", "%27")
3672 .replace("&", "%26")
3673 .replace(",", "%2C")
3674 .replace(":", "%3A")
3675 .replace(";", "%3B")
3676 .replace("[", "%5B")
3677 .replace("]", "%5D")
3678 .replace("\"", "%22")
3681 fn sidebar_assoc_items(it: &clean::Item) -> String {
3682 let mut out = String::new();
3684 if let Some(v) = c.impls.get(&it.def_id) {
3686 .filter(|i| i.inner_impl().trait_.is_none())
3687 .flat_map(|i| get_methods(i.inner_impl(), false))
3688 .collect::<String>();
3689 if !ret.is_empty() {
3690 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3691 </a><div class=\"sidebar-links\">{}</div>", ret));
3694 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3695 if let Some(impl_) = v.iter()
3696 .filter(|i| i.inner_impl().trait_.is_some())
3697 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3698 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3700 clean::TypedefItem(ref t, true) => Some(&t.type_),
3704 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3705 c.primitive_locations.get(&prim).cloned()
3706 })).and_then(|did| c.impls.get(&did));
3707 if let Some(impls) = inner_impl {
3708 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3709 out.push_str(&format!("Methods from {}<Target={}>",
3710 Escape(&format!("{:#}",
3711 impl_.inner_impl().trait_.as_ref().unwrap())),
3712 Escape(&format!("{:#}", target))));
3713 out.push_str("</a>");
3714 let ret = impls.iter()
3715 .filter(|i| i.inner_impl().trait_.is_none())
3716 .flat_map(|i| get_methods(i.inner_impl(), true))
3717 .collect::<String>();
3718 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3722 let format_impls = |impls: Vec<&Impl>| {
3723 let mut links = HashSet::new();
3726 let is_negative_impl = is_negative_impl(i.inner_impl());
3727 if let Some(ref i) = i.inner_impl().trait_ {
3728 let i_display = format!("{:#}", i);
3729 let out = Escape(&i_display);
3730 let encoded = small_url_encode(&format!("{:#}", i));
3731 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3733 if is_negative_impl { "!" } else { "" },
3735 if links.insert(generated.clone()) {
3744 .collect::<String>()
3747 let (synthetic, concrete) = v
3749 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3751 let concrete_format = format_impls(concrete);
3752 let synthetic_format = format_impls(synthetic);
3754 if !concrete_format.is_empty() {
3755 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3756 Trait Implementations</a>");
3757 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3760 if !synthetic_format.is_empty() {
3761 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3762 Auto Trait Implementations</a>");
3763 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3771 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3772 s: &clean::Struct) -> fmt::Result {
3773 let mut sidebar = String::new();
3774 let fields = get_struct_fields_name(&s.fields);
3776 if !fields.is_empty() {
3777 if let doctree::Plain = s.struct_type {
3778 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3779 <div class=\"sidebar-links\">{}</div>", fields));
3783 sidebar.push_str(&sidebar_assoc_items(it));
3785 if !sidebar.is_empty() {
3786 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3791 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3793 clean::ItemEnum::ImplItem(ref i) => {
3794 if let Some(ref trait_) = i.trait_ {
3795 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3804 fn is_negative_impl(i: &clean::Impl) -> bool {
3805 i.polarity == Some(clean::ImplPolarity::Negative)
3808 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3809 t: &clean::Trait) -> fmt::Result {
3810 let mut sidebar = String::new();
3816 Some(ref name) if m.is_associated_type() => {
3817 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3823 .collect::<String>();
3824 let consts = t.items
3828 Some(ref name) if m.is_associated_const() => {
3829 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3835 .collect::<String>();
3836 let required = t.items
3840 Some(ref name) if m.is_ty_method() => {
3841 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3847 .collect::<String>();
3848 let provided = t.items
3852 Some(ref name) if m.is_method() => {
3853 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3858 .collect::<String>();
3860 if !types.is_empty() {
3861 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3862 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3865 if !consts.is_empty() {
3866 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3867 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3870 if !required.is_empty() {
3871 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3872 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3875 if !provided.is_empty() {
3876 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3877 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3883 if let Some(implementors) = c.implementors.get(&it.def_id) {
3884 let res = implementors.iter()
3885 .filter(|i| i.inner_impl().for_.def_id()
3886 .map_or(false, |d| !c.paths.contains_key(&d)))
3888 match extract_for_impl_name(&i.impl_item) {
3889 Some((ref name, ref url)) => {
3890 Some(format!("<a href=\"#impl-{}\">{}</a>",
3891 small_url_encode(url),
3897 .collect::<String>();
3898 if !res.is_empty() {
3899 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3900 Implementations on Foreign Types</a><div \
3901 class=\"sidebar-links\">{}</div>",
3906 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3908 sidebar.push_str("<a class=\"sidebar-title\" \
3909 href=\"#synthetic-implementors\">Auto Implementors</a>");
3912 sidebar.push_str(&sidebar_assoc_items(it));
3914 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3917 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3918 _p: &clean::PrimitiveType) -> fmt::Result {
3919 let sidebar = sidebar_assoc_items(it);
3921 if !sidebar.is_empty() {
3922 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3927 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3928 _t: &clean::Typedef) -> fmt::Result {
3929 let sidebar = sidebar_assoc_items(it);
3931 if !sidebar.is_empty() {
3932 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3937 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3939 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3944 .filter_map(|f| match f.name {
3945 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3946 {name}</a>", name=name)),
3952 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3953 u: &clean::Union) -> fmt::Result {
3954 let mut sidebar = String::new();
3955 let fields = get_struct_fields_name(&u.fields);
3957 if !fields.is_empty() {
3958 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3959 <div class=\"sidebar-links\">{}</div>", fields));
3962 sidebar.push_str(&sidebar_assoc_items(it));
3964 if !sidebar.is_empty() {
3965 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3970 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3971 e: &clean::Enum) -> fmt::Result {
3972 let mut sidebar = String::new();
3974 let variants = e.variants.iter()
3975 .filter_map(|v| match v.name {
3976 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3977 </a>", name = name)),
3980 .collect::<String>();
3981 if !variants.is_empty() {
3982 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3983 <div class=\"sidebar-links\">{}</div>", variants));
3986 sidebar.push_str(&sidebar_assoc_items(it));
3988 if !sidebar.is_empty() {
3989 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3994 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3995 items: &[clean::Item]) -> fmt::Result {
3996 let mut sidebar = String::new();
3998 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3999 it.type_() == ItemType::Import) {
4000 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4002 name = "Re-exports"));
4005 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4006 // to print its headings
4007 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4008 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4009 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4010 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4011 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4012 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4013 let (short, name) = match myty {
4014 ItemType::ExternCrate |
4015 ItemType::Import => ("reexports", "Re-exports"),
4016 ItemType::Module => ("modules", "Modules"),
4017 ItemType::Struct => ("structs", "Structs"),
4018 ItemType::Union => ("unions", "Unions"),
4019 ItemType::Enum => ("enums", "Enums"),
4020 ItemType::Function => ("functions", "Functions"),
4021 ItemType::Typedef => ("types", "Type Definitions"),
4022 ItemType::Static => ("statics", "Statics"),
4023 ItemType::Constant => ("constants", "Constants"),
4024 ItemType::Trait => ("traits", "Traits"),
4025 ItemType::Impl => ("impls", "Implementations"),
4026 ItemType::TyMethod => ("tymethods", "Type Methods"),
4027 ItemType::Method => ("methods", "Methods"),
4028 ItemType::StructField => ("fields", "Struct Fields"),
4029 ItemType::Variant => ("variants", "Variants"),
4030 ItemType::Macro => ("macros", "Macros"),
4031 ItemType::Primitive => ("primitives", "Primitive Types"),
4032 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4033 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4034 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4036 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4042 if !sidebar.is_empty() {
4043 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4048 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4049 let sidebar = sidebar_assoc_items(it);
4050 if !sidebar.is_empty() {
4051 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4056 impl<'a> fmt::Display for Source<'a> {
4057 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4058 let Source(s) = *self;
4059 let lines = s.lines().count();
4061 let mut tmp = lines;
4066 write!(fmt, "<pre class=\"line-numbers\">")?;
4067 for i in 1..lines + 1 {
4068 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4070 write!(fmt, "</pre>")?;
4072 highlight::render_with_highlighting(s, None, None, None, None))?;
4077 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4078 t: &clean::Macro) -> fmt::Result {
4079 wrap_into_docblock(w, |w| {
4080 w.write_str(&highlight::render_with_highlighting(&t.source,
4089 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4091 _p: &clean::PrimitiveType) -> fmt::Result {
4092 document(w, cx, it)?;
4093 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4096 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4098 fn make_item_keywords(it: &clean::Item) -> String {
4099 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4102 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4103 let decl = match item.inner {
4104 clean::FunctionItem(ref f) => &f.decl,
4105 clean::MethodItem(ref m) => &m.decl,
4106 clean::TyMethodItem(ref m) => &m.decl,
4110 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4111 let output = match decl.output {
4112 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4116 Some(IndexItemFunctionType { inputs: inputs, output: output })
4119 fn get_index_type(clean_type: &clean::Type) -> Type {
4121 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4122 generics: get_generics(clean_type),
4127 /// Returns a list of all paths used in the type.
4128 /// This is used to help deduplicate imported impls
4129 /// for reexported types. If any of the contained
4130 /// types are re-exported, we don't use the corresponding
4131 /// entry from the js file, as inlining will have already
4132 /// picked up the impl
4133 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4134 let mut out = Vec::new();
4135 let mut visited = FxHashSet();
4136 let mut work = VecDeque::new();
4137 let cache = cache();
4139 work.push_back(first_ty);
4141 while let Some(ty) = work.pop_front() {
4142 if !visited.insert(ty.clone()) {
4147 clean::Type::ResolvedPath { did, .. } => {
4148 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4149 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4153 out.push(path.join("::"));
4159 clean::Type::Tuple(tys) => {
4160 work.extend(tys.into_iter());
4162 clean::Type::Slice(ty) => {
4163 work.push_back(*ty);
4165 clean::Type::Array(ty, _) => {
4166 work.push_back(*ty);
4168 clean::Type::Unique(ty) => {
4169 work.push_back(*ty);
4171 clean::Type::RawPointer(_, ty) => {
4172 work.push_back(*ty);
4174 clean::Type::BorrowedRef { type_, .. } => {
4175 work.push_back(*type_);
4177 clean::Type::QPath { self_type, trait_, .. } => {
4178 work.push_back(*self_type);
4179 work.push_back(*trait_);
4187 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4189 clean::ResolvedPath { ref path, .. } => {
4190 let segments = &path.segments;
4191 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4192 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4193 clean_type, accept_generic
4195 Some(path_segment.name.clone())
4197 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4198 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4199 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4200 // FIXME: add all from clean::Type.
4205 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4206 clean_type.generics()
4208 let r = types.iter()
4209 .filter_map(|t| get_index_type_name(t, false))
4210 .map(|s| s.to_ascii_lowercase())
4211 .collect::<Vec<_>>();
4220 pub fn cache() -> Arc<Cache> {
4221 CACHE_KEY.with(|c| c.borrow().clone())
4226 fn test_unique_id() {
4227 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4228 "method.into_iter", "foo", "main", "search", "methods",
4229 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4230 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4231 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4232 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4235 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4236 assert_eq!(&actual[..], expected);
4245 fn test_name_key() {
4246 assert_eq!(name_key("0"), ("", 0, 1));
4247 assert_eq!(name_key("123"), ("", 123, 0));
4248 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4249 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4250 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4251 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4252 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4253 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4258 fn test_name_sorting() {
4259 let names = ["Apple",
4261 "Fruit", "Fruit0", "Fruit00",
4262 "Fruit1", "Fruit01",
4263 "Fruit2", "Fruit02",
4267 let mut sorted = names.to_owned();
4268 sorted.sort_by_key(|&s| name_key(s));
4269 assert_eq!(names, sorted);