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 "main.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 "main.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!("main{}.css", cx.shared.resource_suffix)),
765 include_bytes!("static/themes/main.css"))?;
766 themes.insert("main".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_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 impl<'a> fmt::Display for Item<'a> {
1679 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1680 debug_assert!(!self.item.is_stripped());
1681 // Write the breadcrumb trail header for the top
1682 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1683 match self.item.inner {
1684 clean::ModuleItem(ref m) => if m.is_crate {
1685 write!(fmt, "Crate ")?;
1687 write!(fmt, "Module ")?;
1689 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1690 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1691 clean::StructItem(..) => write!(fmt, "Struct ")?,
1692 clean::UnionItem(..) => write!(fmt, "Union ")?,
1693 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1694 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1695 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1696 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1697 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1698 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1699 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1701 // We don't generate pages for any other type.
1705 if !self.item.is_primitive() {
1706 let cur = &self.cx.current;
1707 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1708 for (i, component) in cur.iter().enumerate().take(amt) {
1709 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1710 repeat("../").take(cur.len() - i - 1)
1711 .collect::<String>(),
1715 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1716 self.item.type_(), self.item.name.as_ref().unwrap())?;
1718 write!(fmt, "</span>")?; // in-band
1719 write!(fmt, "<span class='out-of-band'>")?;
1720 if let Some(version) = self.item.stable_since() {
1721 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1725 r##"<span id='render-detail'>
1726 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1727 [<span class='inner'>−</span>]
1733 // When this item is part of a `pub use` in a downstream crate, the
1734 // [src] link in the downstream documentation will actually come back to
1735 // this page, and this link will be auto-clicked. The `id` attribute is
1736 // used to find the link to auto-click.
1737 if self.cx.shared.include_sources && !self.item.is_primitive() {
1738 if let Some(l) = self.src_href() {
1739 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1740 l, "goto source code")?;
1744 write!(fmt, "</span>")?; // out-of-band
1746 write!(fmt, "</h1>\n")?;
1748 match self.item.inner {
1749 clean::ModuleItem(ref m) => {
1750 item_module(fmt, self.cx, self.item, &m.items)
1752 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1753 item_function(fmt, self.cx, self.item, f),
1754 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1755 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1756 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1757 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1758 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1759 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1760 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1761 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1762 item_static(fmt, self.cx, self.item, i),
1763 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1764 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1766 // We don't generate pages for any other type.
1773 fn item_path(ty: ItemType, name: &str) -> String {
1775 ItemType::Module => format!("{}/index.html", name),
1776 _ => format!("{}.{}.html", ty.css_class(), name),
1780 fn full_path(cx: &Context, item: &clean::Item) -> String {
1781 let mut s = cx.current.join("::");
1783 s.push_str(item.name.as_ref().unwrap());
1787 fn shorter<'a>(s: Option<&'a str>) -> String {
1789 Some(s) => s.lines()
1790 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1792 (*line).chars().any(|chr|{
1793 !chr.is_whitespace()
1795 }).collect::<Vec<_>>().join("\n"),
1796 None => "".to_string()
1801 fn plain_summary_line(s: Option<&str>) -> String {
1802 let line = shorter(s).replace("\n", " ");
1803 markdown::plain_summary_line(&line[..])
1806 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1807 if let Some(ref name) = item.name {
1808 info!("Documenting {}", name);
1810 document_stability(w, cx, item)?;
1811 let prefix = render_assoc_const_value(item);
1812 document_full(w, item, cx, &prefix)?;
1816 /// Render md_text as markdown.
1817 fn render_markdown(w: &mut fmt::Formatter,
1819 links: Vec<(String, String)>,
1822 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1825 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1826 prefix: &str) -> fmt::Result {
1827 if let Some(s) = item.doc_value() {
1828 let markdown = if s.contains('\n') {
1829 format!("{} [Read more]({})",
1830 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1832 format!("{}", &plain_summary_line(Some(s)))
1834 render_markdown(w, &markdown, item.links(), prefix)?;
1835 } else if !prefix.is_empty() {
1836 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1841 fn render_assoc_const_value(item: &clean::Item) -> String {
1843 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1844 highlight::render_with_highlighting(
1845 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1856 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1857 cx: &Context, prefix: &str) -> fmt::Result {
1858 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1859 debug!("Doc block: =====\n{}\n=====", s);
1860 render_markdown(w, &*s, item.links(), prefix)?;
1861 } else if !prefix.is_empty() {
1862 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1867 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1868 let stabilities = short_stability(item, cx, true);
1869 if !stabilities.is_empty() {
1870 write!(w, "<div class='stability'>")?;
1871 for stability in stabilities {
1872 write!(w, "{}", stability)?;
1874 write!(w, "</div>")?;
1879 fn name_key(name: &str) -> (&str, u64, usize) {
1880 // find number at end
1881 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1883 // count leading zeroes
1885 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1887 // sort leading zeroes last
1888 let num_zeroes = after_zeroes - split;
1890 match name[split..].parse() {
1891 Ok(n) => (&name[..split], n, num_zeroes),
1892 Err(_) => (name, 0, num_zeroes),
1896 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1897 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1898 document(w, cx, item)?;
1900 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1902 // the order of item types in the listing
1903 fn reorder(ty: ItemType) -> u8 {
1905 ItemType::ExternCrate => 0,
1906 ItemType::Import => 1,
1907 ItemType::Primitive => 2,
1908 ItemType::Module => 3,
1909 ItemType::Macro => 4,
1910 ItemType::Struct => 5,
1911 ItemType::Enum => 6,
1912 ItemType::Constant => 7,
1913 ItemType::Static => 8,
1914 ItemType::Trait => 9,
1915 ItemType::Function => 10,
1916 ItemType::Typedef => 12,
1917 ItemType::Union => 13,
1922 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1923 let ty1 = i1.type_();
1924 let ty2 = i2.type_();
1926 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1928 let s1 = i1.stability.as_ref().map(|s| s.level);
1929 let s2 = i2.stability.as_ref().map(|s| s.level);
1931 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1932 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1935 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1936 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1937 name_key(lhs).cmp(&name_key(rhs))
1940 if cx.shared.sort_modules_alphabetically {
1941 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1943 // This call is to remove re-export duplicates in cases such as:
1948 // pub trait Double { fn foo(); }
1952 // pub use foo::bar::*;
1956 // `Double` will appear twice in the generated docs.
1958 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1959 // can be identical even if the elements are different (mostly in imports).
1960 // So in case this is an import, we keep everything by adding a "unique id"
1961 // (which is the position in the vector).
1962 indices.dedup_by_key(|i| (items[*i].def_id,
1963 if items[*i].name.as_ref().is_some() {
1964 Some(full_path(cx, &items[*i]).clone())
1969 if items[*i].is_import() {
1975 debug!("{:?}", indices);
1976 let mut curty = None;
1977 for &idx in &indices {
1978 let myitem = &items[idx];
1979 if myitem.is_stripped() {
1983 let myty = Some(myitem.type_());
1984 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1985 // Put `extern crate` and `use` re-exports in the same section.
1987 } else if myty != curty {
1988 if curty.is_some() {
1989 write!(w, "</table>")?;
1992 let (short, name) = match myty.unwrap() {
1993 ItemType::ExternCrate |
1994 ItemType::Import => ("reexports", "Re-exports"),
1995 ItemType::Module => ("modules", "Modules"),
1996 ItemType::Struct => ("structs", "Structs"),
1997 ItemType::Union => ("unions", "Unions"),
1998 ItemType::Enum => ("enums", "Enums"),
1999 ItemType::Function => ("functions", "Functions"),
2000 ItemType::Typedef => ("types", "Type Definitions"),
2001 ItemType::Static => ("statics", "Statics"),
2002 ItemType::Constant => ("constants", "Constants"),
2003 ItemType::Trait => ("traits", "Traits"),
2004 ItemType::Impl => ("impls", "Implementations"),
2005 ItemType::TyMethod => ("tymethods", "Type Methods"),
2006 ItemType::Method => ("methods", "Methods"),
2007 ItemType::StructField => ("fields", "Struct Fields"),
2008 ItemType::Variant => ("variants", "Variants"),
2009 ItemType::Macro => ("macros", "Macros"),
2010 ItemType::Primitive => ("primitives", "Primitive Types"),
2011 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2012 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2013 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2015 write!(w, "<h2 id='{id}' class='section-header'>\
2016 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2017 id = derive_id(short.to_owned()), name = name)?;
2020 match myitem.inner {
2021 clean::ExternCrateItem(ref name, ref src) => {
2022 use html::format::HRef;
2026 write!(w, "<tr><td><code>{}extern crate {} as {};",
2027 VisSpace(&myitem.visibility),
2028 HRef::new(myitem.def_id, src),
2032 write!(w, "<tr><td><code>{}extern crate {};",
2033 VisSpace(&myitem.visibility),
2034 HRef::new(myitem.def_id, name))?
2037 write!(w, "</code></td></tr>")?;
2040 clean::ImportItem(ref import) => {
2041 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2042 VisSpace(&myitem.visibility), *import)?;
2046 if myitem.name.is_none() { continue }
2048 let stabilities = short_stability(myitem, cx, false);
2050 let stab_docs = if !stabilities.is_empty() {
2052 .map(|s| format!("[{}]", s))
2053 .collect::<Vec<_>>()
2060 let unsafety_flag = match myitem.inner {
2061 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2062 if func.unsafety == hir::Unsafety::Unsafe => {
2063 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2068 let doc_value = myitem.doc_value().unwrap_or("");
2070 <tr class='{stab} module-item'>
2071 <td><a class=\"{class}\" href=\"{href}\"
2072 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2073 <td class='docblock-short'>
2077 name = *myitem.name.as_ref().unwrap(),
2078 stab_docs = stab_docs,
2079 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2080 class = myitem.type_(),
2081 stab = myitem.stability_class().unwrap_or("".to_string()),
2082 unsafety_flag = unsafety_flag,
2083 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2084 title_type = myitem.type_(),
2085 title = full_path(cx, myitem))?;
2090 if curty.is_some() {
2091 write!(w, "</table>")?;
2096 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2097 let mut stability = vec![];
2099 if let Some(stab) = item.stability.as_ref() {
2100 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2101 format!(": {}", stab.deprecated_reason)
2105 if !stab.deprecated_since.is_empty() {
2106 let since = if show_reason {
2107 format!(" since {}", Escape(&stab.deprecated_since))
2111 let text = format!("Deprecated{}{}",
2113 MarkdownHtml(&deprecated_reason));
2114 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2117 if stab.level == stability::Unstable {
2119 let unstable_extra = match (!stab.feature.is_empty(),
2120 &cx.shared.issue_tracker_base_url,
2122 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2123 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2124 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2125 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2126 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2129 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2132 if stab.unstable_reason.is_empty() {
2133 stability.push(format!("<div class='stab unstable'>\
2134 <span class=microscope>🔬</span> \
2135 This is a nightly-only experimental API. {}\
2139 let text = format!("<summary><span class=microscope>🔬</span> \
2140 This is a nightly-only experimental API. {}\
2143 MarkdownHtml(&stab.unstable_reason));
2144 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2148 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2151 } else if let Some(depr) = item.deprecation.as_ref() {
2152 let note = if show_reason && !depr.note.is_empty() {
2153 format!(": {}", depr.note)
2157 let since = if show_reason && !depr.since.is_empty() {
2158 format!(" since {}", Escape(&depr.since))
2163 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e));
2164 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2167 if let Some(ref cfg) = item.attrs.cfg {
2168 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2169 cfg.render_long_html()
2171 cfg.render_short_html()
2178 struct Initializer<'a>(&'a str);
2180 impl<'a> fmt::Display for Initializer<'a> {
2181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2182 let Initializer(s) = *self;
2183 if s.is_empty() { return Ok(()); }
2184 write!(f, "<code> = </code>")?;
2185 write!(f, "<code>{}</code>", Escape(s))
2189 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2190 c: &clean::Constant) -> fmt::Result {
2191 write!(w, "<pre class='rust const'>")?;
2192 render_attributes(w, it)?;
2193 write!(w, "{vis}const \
2194 {name}: {typ}{init}</pre>",
2195 vis = VisSpace(&it.visibility),
2196 name = it.name.as_ref().unwrap(),
2198 init = Initializer(&c.expr))?;
2202 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2203 s: &clean::Static) -> fmt::Result {
2204 write!(w, "<pre class='rust static'>")?;
2205 render_attributes(w, it)?;
2206 write!(w, "{vis}static {mutability}\
2207 {name}: {typ}{init}</pre>",
2208 vis = VisSpace(&it.visibility),
2209 mutability = MutableSpace(s.mutability),
2210 name = it.name.as_ref().unwrap(),
2212 init = Initializer(&s.expr))?;
2216 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2217 f: &clean::Function) -> fmt::Result {
2218 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2219 VisSpace(&it.visibility),
2220 ConstnessSpace(f.constness),
2221 UnsafetySpace(f.unsafety),
2223 it.name.as_ref().unwrap(),
2225 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2226 render_attributes(w, it)?;
2228 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2229 vis = VisSpace(&it.visibility),
2230 constness = ConstnessSpace(f.constness),
2231 unsafety = UnsafetySpace(f.unsafety),
2232 abi = AbiSpace(f.abi),
2233 name = it.name.as_ref().unwrap(),
2234 generics = f.generics,
2235 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2244 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2245 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2247 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2248 write!(w, "<div class='out-of-band'>")?;
2249 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2250 l, "goto source code")?;
2251 write!(w, "</div>")?;
2253 write!(w, "<code>")?;
2254 // If there's already another implementor that has the same abbridged name, use the
2255 // full path, for example in `std::iter::ExactSizeIterator`
2256 let use_absolute = match implementor.inner_impl().for_ {
2257 clean::ResolvedPath { ref path, is_generic: false, .. } |
2258 clean::BorrowedRef {
2259 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2261 } => implementor_dups[path.last_name()].1,
2264 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2265 for it in &implementor.inner_impl().items {
2266 if let clean::TypedefItem(ref tydef, _) = it.inner {
2267 write!(w, "<span class=\"where fmt-newline\"> ")?;
2268 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2269 write!(w, ";</span>")?;
2272 writeln!(w, "</code></li>")?;
2276 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2277 traits: Vec<&&Impl>,
2278 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2280 let did = i.trait_did().unwrap();
2281 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2282 render_impl(w, cx, i, assoc_link,
2283 RenderMode::Normal, containing_item.stable_since(), true)?;
2288 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2289 t: &clean::Trait) -> fmt::Result {
2290 let mut bounds = String::new();
2291 let mut bounds_plain = String::new();
2292 if !t.bounds.is_empty() {
2293 if !bounds.is_empty() {
2295 bounds_plain.push(' ');
2297 bounds.push_str(": ");
2298 bounds_plain.push_str(": ");
2299 for (i, p) in t.bounds.iter().enumerate() {
2301 bounds.push_str(" + ");
2302 bounds_plain.push_str(" + ");
2304 bounds.push_str(&format!("{}", *p));
2305 bounds_plain.push_str(&format!("{:#}", *p));
2309 // Output the trait definition
2310 write!(w, "<pre class='rust trait'>")?;
2311 render_attributes(w, it)?;
2312 write!(w, "{}{}{}trait {}{}{}",
2313 VisSpace(&it.visibility),
2314 UnsafetySpace(t.unsafety),
2315 if t.is_auto { "auto " } else { "" },
2316 it.name.as_ref().unwrap(),
2320 if !t.generics.where_predicates.is_empty() {
2321 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2326 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2327 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2328 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2329 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2331 if t.items.is_empty() {
2332 write!(w, "{{ }}")?;
2334 // FIXME: we should be using a derived_id for the Anchors here
2338 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2341 if !types.is_empty() && !consts.is_empty() {
2346 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2349 if !consts.is_empty() && !required.is_empty() {
2352 for (pos, m) in required.iter().enumerate() {
2354 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2357 if pos < required.len() - 1 {
2358 write!(w, "<div class='item-spacer'></div>")?;
2361 if !required.is_empty() && !provided.is_empty() {
2364 for (pos, m) in provided.iter().enumerate() {
2366 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2368 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2369 write!(w, ",\n {{ ... }}\n")?;
2372 write!(w, " {{ ... }}\n")?;
2375 if pos < provided.len() - 1 {
2376 write!(w, "<div class='item-spacer'></div>")?;
2381 write!(w, "</pre>")?;
2383 // Trait documentation
2384 document(w, cx, it)?;
2386 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2388 let name = m.name.as_ref().unwrap();
2389 let item_type = m.type_();
2390 let id = derive_id(format!("{}.{}", item_type, name));
2391 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2392 write!(w, "{extra}<h3 id='{id}' class='method'>\
2393 <span id='{ns_id}' class='invisible'><code>",
2394 extra = render_spotlight_traits(m)?,
2397 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2398 write!(w, "</code>")?;
2399 render_stability_since(w, m, t)?;
2400 write!(w, "</span></h3>")?;
2401 document(w, cx, m)?;
2405 if !types.is_empty() {
2407 <h2 id='associated-types' class='small-section-header'>
2408 Associated Types<a href='#associated-types' class='anchor'></a>
2410 <div class='methods'>
2413 trait_item(w, cx, *t, it)?;
2415 write!(w, "</div>")?;
2418 if !consts.is_empty() {
2420 <h2 id='associated-const' class='small-section-header'>
2421 Associated Constants<a href='#associated-const' class='anchor'></a>
2423 <div class='methods'>
2426 trait_item(w, cx, *t, it)?;
2428 write!(w, "</div>")?;
2431 // Output the documentation for each function individually
2432 if !required.is_empty() {
2434 <h2 id='required-methods' class='small-section-header'>
2435 Required Methods<a href='#required-methods' class='anchor'></a>
2437 <div class='methods'>
2439 for m in &required {
2440 trait_item(w, cx, *m, it)?;
2442 write!(w, "</div>")?;
2444 if !provided.is_empty() {
2446 <h2 id='provided-methods' class='small-section-header'>
2447 Provided Methods<a href='#provided-methods' class='anchor'></a>
2449 <div class='methods'>
2451 for m in &provided {
2452 trait_item(w, cx, *m, it)?;
2454 write!(w, "</div>")?;
2457 // If there are methods directly on this trait object, render them here.
2458 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2460 let cache = cache();
2462 <h2 id='implementors' class='small-section-header'>
2463 Implementors<a href='#implementors' class='anchor'></a>
2465 <ul class='item-list' id='implementors-list'>
2468 let synthetic_impl_header = "
2469 <h2 id='synthetic-implementors' class='small-section-header'>
2470 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2472 <ul class='item-list' id='synthetic-implementors-list'>
2475 let mut synthetic_types = Vec::new();
2477 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2478 // The DefId is for the first Type found with that name. The bool is
2479 // if any Types with the same name but different DefId have been found.
2480 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2481 for implementor in implementors {
2482 match implementor.inner_impl().for_ {
2483 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2484 clean::BorrowedRef {
2485 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2488 let &mut (prev_did, ref mut has_duplicates) =
2489 implementor_dups.entry(path.last_name()).or_insert((did, false));
2490 if prev_did != did {
2491 *has_duplicates = true;
2498 let (local, foreign) = implementors.iter()
2499 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2500 .map_or(true, |d| cache.paths.contains_key(&d)));
2503 let (synthetic, concrete) = local.iter()
2504 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2507 if !foreign.is_empty() {
2509 <h2 id='foreign-impls' class='small-section-header'>
2510 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2514 for implementor in foreign {
2515 let assoc_link = AssocItemLink::GotoSource(
2516 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2518 render_impl(w, cx, &implementor, assoc_link,
2519 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2523 write!(w, "{}", impl_header)?;
2524 for implementor in concrete {
2525 render_implementor(cx, implementor, w, &implementor_dups)?;
2527 write!(w, "</ul>")?;
2530 write!(w, "{}", synthetic_impl_header)?;
2531 for implementor in synthetic {
2532 synthetic_types.extend(
2533 collect_paths_for_type(implementor.inner_impl().for_.clone())
2535 render_implementor(cx, implementor, w, &implementor_dups)?;
2537 write!(w, "</ul>")?;
2540 // even without any implementations to write in, we still want the heading and list, so the
2541 // implementors javascript file pulled in below has somewhere to write the impls into
2542 write!(w, "{}", impl_header)?;
2543 write!(w, "</ul>")?;
2546 write!(w, "{}", synthetic_impl_header)?;
2547 write!(w, "</ul>")?;
2550 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2551 as_json(&synthetic_types))?;
2553 write!(w, r#"<script type="text/javascript" async
2554 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2556 root_path = vec![".."; cx.current.len()].join("/"),
2557 path = if it.def_id.is_local() {
2558 cx.current.join("/")
2560 let (ref path, _) = cache.external_paths[&it.def_id];
2561 path[..path.len() - 1].join("/")
2563 ty = it.type_().css_class(),
2564 name = *it.name.as_ref().unwrap())?;
2568 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2569 use html::item_type::ItemType::*;
2571 let name = it.name.as_ref().unwrap();
2572 let ty = match it.type_() {
2573 Typedef | AssociatedType => AssociatedType,
2577 let anchor = format!("#{}.{}", ty, name);
2579 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2580 AssocItemLink::Anchor(None) => anchor,
2581 AssocItemLink::GotoSource(did, _) => {
2582 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2587 fn assoc_const(w: &mut fmt::Formatter,
2590 _default: Option<&String>,
2591 link: AssocItemLink) -> fmt::Result {
2592 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2593 VisSpace(&it.visibility),
2594 naive_assoc_href(it, link),
2595 it.name.as_ref().unwrap(),
2600 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2601 bounds: &Vec<clean::TyParamBound>,
2602 default: Option<&clean::Type>,
2603 link: AssocItemLink) -> fmt::Result {
2604 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2605 naive_assoc_href(it, link),
2606 it.name.as_ref().unwrap())?;
2607 if !bounds.is_empty() {
2608 write!(w, ": {}", TyParamBounds(bounds))?
2610 if let Some(default) = default {
2611 write!(w, " = {}", default)?;
2616 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2617 ver: Option<&'a str>,
2618 containing_ver: Option<&'a str>) -> fmt::Result {
2619 if let Some(v) = ver {
2620 if containing_ver != ver && v.len() > 0 {
2621 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2628 fn render_stability_since(w: &mut fmt::Formatter,
2630 containing_item: &clean::Item) -> fmt::Result {
2631 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2634 fn render_assoc_item(w: &mut fmt::Formatter,
2636 link: AssocItemLink,
2637 parent: ItemType) -> fmt::Result {
2638 fn method(w: &mut fmt::Formatter,
2640 unsafety: hir::Unsafety,
2641 constness: hir::Constness,
2643 g: &clean::Generics,
2645 link: AssocItemLink,
2648 let name = meth.name.as_ref().unwrap();
2649 let anchor = format!("#{}.{}", meth.type_(), name);
2650 let href = match link {
2651 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2652 AssocItemLink::Anchor(None) => anchor,
2653 AssocItemLink::GotoSource(did, provided_methods) => {
2654 // We're creating a link from an impl-item to the corresponding
2655 // trait-item and need to map the anchored type accordingly.
2656 let ty = if provided_methods.contains(name) {
2662 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2665 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2666 VisSpace(&meth.visibility),
2667 ConstnessSpace(constness),
2668 UnsafetySpace(unsafety),
2672 let (indent, end_newline) = if parent == ItemType::Trait {
2678 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2679 {generics}{decl}{where_clause}",
2680 VisSpace(&meth.visibility),
2681 ConstnessSpace(constness),
2682 UnsafetySpace(unsafety),
2692 where_clause = WhereClause {
2699 clean::StrippedItem(..) => Ok(()),
2700 clean::TyMethodItem(ref m) => {
2701 method(w, item, m.unsafety, hir::Constness::NotConst,
2702 m.abi, &m.generics, &m.decl, link, parent)
2704 clean::MethodItem(ref m) => {
2705 method(w, item, m.unsafety, m.constness,
2706 m.abi, &m.generics, &m.decl, link, parent)
2708 clean::AssociatedConstItem(ref ty, ref default) => {
2709 assoc_const(w, item, ty, default.as_ref(), link)
2711 clean::AssociatedTypeItem(ref bounds, ref default) => {
2712 assoc_type(w, item, bounds, default.as_ref(), link)
2714 _ => panic!("render_assoc_item called on non-associated-item")
2718 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2719 s: &clean::Struct) -> fmt::Result {
2720 write!(w, "<pre class='rust struct'>")?;
2721 render_attributes(w, it)?;
2729 write!(w, "</pre>")?;
2731 document(w, cx, it)?;
2732 let mut fields = s.fields.iter().filter_map(|f| {
2734 clean::StructFieldItem(ref ty) => Some((f, ty)),
2738 if let doctree::Plain = s.struct_type {
2739 if fields.peek().is_some() {
2740 write!(w, "<h2 id='fields' class='fields small-section-header'>
2741 Fields<a href='#fields' class='anchor'></a></h2>")?;
2742 for (field, ty) in fields {
2743 let id = derive_id(format!("{}.{}",
2744 ItemType::StructField,
2745 field.name.as_ref().unwrap()));
2746 let ns_id = derive_id(format!("{}.{}",
2747 field.name.as_ref().unwrap(),
2748 ItemType::StructField.name_space()));
2749 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2750 <a href=\"#{id}\" class=\"anchor field\"></a>
2751 <span id=\"{ns_id}\" class='invisible'>
2752 <code>{name}: {ty}</code>
2754 item_type = ItemType::StructField,
2757 name = field.name.as_ref().unwrap(),
2759 if let Some(stability_class) = field.stability_class() {
2760 write!(w, "<span class='stab {stab}'></span>",
2761 stab = stability_class)?;
2763 document(w, cx, field)?;
2767 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2770 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2771 s: &clean::Union) -> fmt::Result {
2772 write!(w, "<pre class='rust union'>")?;
2773 render_attributes(w, it)?;
2780 write!(w, "</pre>")?;
2782 document(w, cx, it)?;
2783 let mut fields = s.fields.iter().filter_map(|f| {
2785 clean::StructFieldItem(ref ty) => Some((f, ty)),
2789 if fields.peek().is_some() {
2790 write!(w, "<h2 id='fields' class='fields small-section-header'>
2791 Fields<a href='#fields' class='anchor'></a></h2>")?;
2792 for (field, ty) in fields {
2793 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2795 shortty = ItemType::StructField,
2796 name = field.name.as_ref().unwrap(),
2798 if let Some(stability_class) = field.stability_class() {
2799 write!(w, "<span class='stab {stab}'></span>",
2800 stab = stability_class)?;
2802 document(w, cx, field)?;
2805 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2808 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2809 e: &clean::Enum) -> fmt::Result {
2810 write!(w, "<pre class='rust enum'>")?;
2811 render_attributes(w, it)?;
2812 write!(w, "{}enum {}{}{}",
2813 VisSpace(&it.visibility),
2814 it.name.as_ref().unwrap(),
2816 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2817 if e.variants.is_empty() && !e.variants_stripped {
2818 write!(w, " {{}}")?;
2820 write!(w, " {{\n")?;
2821 for v in &e.variants {
2823 let name = v.name.as_ref().unwrap();
2825 clean::VariantItem(ref var) => {
2827 clean::VariantKind::CLike => write!(w, "{}", name)?,
2828 clean::VariantKind::Tuple(ref tys) => {
2829 write!(w, "{}(", name)?;
2830 for (i, ty) in tys.iter().enumerate() {
2832 write!(w, ", ")?
2834 write!(w, "{}", *ty)?;
2838 clean::VariantKind::Struct(ref s) => {
2854 if e.variants_stripped {
2855 write!(w, " // some variants omitted\n")?;
2859 write!(w, "</pre>")?;
2861 document(w, cx, it)?;
2862 if !e.variants.is_empty() {
2863 write!(w, "<h2 id='variants' class='variants small-section-header'>
2864 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2865 for variant in &e.variants {
2866 let id = derive_id(format!("{}.{}",
2868 variant.name.as_ref().unwrap()));
2869 let ns_id = derive_id(format!("{}.{}",
2870 variant.name.as_ref().unwrap(),
2871 ItemType::Variant.name_space()));
2872 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2873 <a href=\"#{id}\" class=\"anchor field\"></a>\
2874 <span id='{ns_id}' class='invisible'><code>{name}",
2877 name = variant.name.as_ref().unwrap())?;
2878 if let clean::VariantItem(ref var) = variant.inner {
2879 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2881 for (i, ty) in tys.iter().enumerate() {
2883 write!(w, ", ")?;
2885 write!(w, "{}", *ty)?;
2890 write!(w, "</code></span></span>")?;
2891 document(w, cx, variant)?;
2893 use clean::{Variant, VariantKind};
2894 if let clean::VariantItem(Variant {
2895 kind: VariantKind::Struct(ref s)
2896 }) = variant.inner {
2897 let variant_id = derive_id(format!("{}.{}.fields",
2899 variant.name.as_ref().unwrap()));
2900 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2902 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2903 <table>", name = variant.name.as_ref().unwrap())?;
2904 for field in &s.fields {
2905 use clean::StructFieldItem;
2906 if let StructFieldItem(ref ty) = field.inner {
2907 let id = derive_id(format!("variant.{}.field.{}",
2908 variant.name.as_ref().unwrap(),
2909 field.name.as_ref().unwrap()));
2910 let ns_id = derive_id(format!("{}.{}.{}.{}",
2911 variant.name.as_ref().unwrap(),
2912 ItemType::Variant.name_space(),
2913 field.name.as_ref().unwrap(),
2914 ItemType::StructField.name_space()));
2915 write!(w, "<tr><td \
2917 <span id='{ns_id}' class='invisible'>\
2918 <code>{f}: {t}</code></span></td><td>",
2921 f = field.name.as_ref().unwrap(),
2923 document(w, cx, field)?;
2924 write!(w, "</td></tr>")?;
2927 write!(w, "</table></span>")?;
2929 render_stability_since(w, variant, it)?;
2932 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2936 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2937 let name = attr.name();
2940 Some(format!("{}", name))
2941 } else if let Some(v) = attr.value_str() {
2942 Some(format!("{} = {:?}", name, v.as_str()))
2943 } else if let Some(values) = attr.meta_item_list() {
2944 let display: Vec<_> = values.iter().filter_map(|attr| {
2945 attr.meta_item().and_then(|mi| render_attribute(mi))
2948 if display.len() > 0 {
2949 Some(format!("{}({})", name, display.join(", ")))
2958 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2965 "unsafe_destructor_blind_to_params"
2968 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2969 let mut attrs = String::new();
2971 for attr in &it.attrs.other_attrs {
2972 let name = attr.name().unwrap();
2973 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2976 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2977 attrs.push_str(&format!("#[{}]\n", s));
2980 if attrs.len() > 0 {
2981 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2986 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2987 g: Option<&clean::Generics>,
2988 ty: doctree::StructType,
2989 fields: &[clean::Item],
2991 structhead: bool) -> fmt::Result {
2993 VisSpace(&it.visibility),
2994 if structhead {"struct "} else {""},
2995 it.name.as_ref().unwrap())?;
2996 if let Some(g) = g {
3001 if let Some(g) = g {
3002 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3004 let mut has_visible_fields = false;
3006 for field in fields {
3007 if let clean::StructFieldItem(ref ty) = field.inner {
3008 write!(w, "\n{} {}{}: {},",
3010 VisSpace(&field.visibility),
3011 field.name.as_ref().unwrap(),
3013 has_visible_fields = true;
3017 if has_visible_fields {
3018 if it.has_stripped_fields().unwrap() {
3019 write!(w, "\n{} // some fields omitted", tab)?;
3021 write!(w, "\n{}", tab)?;
3022 } else if it.has_stripped_fields().unwrap() {
3023 // If there are no visible fields we can just display
3024 // `{ /* fields omitted */ }` to save space.
3025 write!(w, " /* fields omitted */ ")?;
3031 for (i, field) in fields.iter().enumerate() {
3036 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3039 clean::StructFieldItem(ref ty) => {
3040 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3046 if let Some(g) = g {
3047 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3052 // Needed for PhantomData.
3053 if let Some(g) = g {
3054 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3062 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3063 g: Option<&clean::Generics>,
3064 fields: &[clean::Item],
3066 structhead: bool) -> fmt::Result {
3068 VisSpace(&it.visibility),
3069 if structhead {"union "} else {""},
3070 it.name.as_ref().unwrap())?;
3071 if let Some(g) = g {
3072 write!(w, "{}", g)?;
3073 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3076 write!(w, " {{\n{}", tab)?;
3077 for field in fields {
3078 if let clean::StructFieldItem(ref ty) = field.inner {
3079 write!(w, " {}{}: {},\n{}",
3080 VisSpace(&field.visibility),
3081 field.name.as_ref().unwrap(),
3087 if it.has_stripped_fields().unwrap() {
3088 write!(w, " // some fields omitted\n{}", tab)?;
3094 #[derive(Copy, Clone)]
3095 enum AssocItemLink<'a> {
3096 Anchor(Option<&'a str>),
3097 GotoSource(DefId, &'a FxHashSet<String>),
3100 impl<'a> AssocItemLink<'a> {
3101 fn anchor(&self, id: &'a String) -> Self {
3103 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3104 ref other => *other,
3109 enum AssocItemRender<'a> {
3111 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3114 #[derive(Copy, Clone, PartialEq)]
3117 ForDeref { mut_: bool },
3120 fn render_assoc_items(w: &mut fmt::Formatter,
3122 containing_item: &clean::Item,
3124 what: AssocItemRender) -> fmt::Result {
3126 let v = match c.impls.get(&it) {
3128 None => return Ok(()),
3130 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3131 i.inner_impl().trait_.is_none()
3133 if !non_trait.is_empty() {
3134 let render_mode = match what {
3135 AssocItemRender::All => {
3137 <h2 id='methods' class='small-section-header'>
3138 Methods<a href='#methods' class='anchor'></a>
3143 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3145 <h2 id='deref-methods' class='small-section-header'>
3146 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3149 RenderMode::ForDeref { mut_: deref_mut_ }
3152 for i in &non_trait {
3153 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3154 containing_item.stable_since(), true)?;
3157 if let AssocItemRender::DerefFor { .. } = what {
3160 if !traits.is_empty() {
3161 let deref_impl = traits.iter().find(|t| {
3162 t.inner_impl().trait_.def_id() == c.deref_trait_did
3164 if let Some(impl_) = deref_impl {
3165 let has_deref_mut = traits.iter().find(|t| {
3166 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3168 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3171 let (synthetic, concrete) = traits
3173 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3176 <h2 id='implementations' class='small-section-header'>
3177 Trait Implementations<a href='#implementations' class='anchor'></a>
3179 <div id='implementations-list'>
3181 render_impls(cx, w, concrete, containing_item)?;
3182 write!(w, "</div>")?;
3185 <h2 id='synthetic-implementations' class='small-section-header'>
3186 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3188 <div id='synthetic-implementations-list'>
3190 render_impls(cx, w, synthetic, containing_item)?;
3191 write!(w, "</div>")?;
3196 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3197 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3198 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3199 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3201 clean::TypedefItem(ref t, true) => Some(&t.type_),
3204 }).next().expect("Expected associated type binding");
3205 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3206 deref_mut_: deref_mut };
3207 if let Some(did) = target.def_id() {
3208 render_assoc_items(w, cx, container_item, did, what)
3210 if let Some(prim) = target.primitive_type() {
3211 if let Some(&did) = cache().primitive_locations.get(&prim) {
3212 render_assoc_items(w, cx, container_item, did, what)?;
3219 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3220 let self_type_opt = match item.inner {
3221 clean::MethodItem(ref method) => method.decl.self_type(),
3222 clean::TyMethodItem(ref method) => method.decl.self_type(),
3226 if let Some(self_ty) = self_type_opt {
3227 let (by_mut_ref, by_box, by_value) = match self_ty {
3228 SelfTy::SelfBorrowed(_, mutability) |
3229 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3230 (mutability == Mutability::Mutable, false, false)
3232 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3233 (false, Some(did) == cache().owned_box_did, false)
3235 SelfTy::SelfValue => (false, false, true),
3236 _ => (false, false, false),
3239 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3245 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3246 let mut out = String::new();
3249 clean::FunctionItem(clean::Function { ref decl, .. }) |
3250 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3251 clean::MethodItem(clean::Method { ref decl, .. }) |
3252 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3253 out = spotlight_decl(decl)?;
3261 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3262 let mut out = String::new();
3263 let mut trait_ = String::new();
3265 if let Some(did) = decl.output.def_id() {
3267 if let Some(impls) = c.impls.get(&did) {
3269 let impl_ = i.inner_impl();
3270 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3273 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3274 <code class=\"content\">",
3276 trait_.push_str(&format!("{}", impl_.for_));
3279 //use the "where" class here to make it small
3280 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3281 let t_did = impl_.trait_.def_id().unwrap();
3282 for it in &impl_.items {
3283 if let clean::TypedefItem(ref tydef, _) = it.inner {
3284 out.push_str("<span class=\"where fmt-newline\"> ");
3285 assoc_type(&mut out, it, &vec![],
3287 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3288 out.push_str(";</span>");
3296 if !out.is_empty() {
3297 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3298 <span class='tooltiptext'>Important traits for {}</span></div>\
3299 <div class=\"content hidden\">",
3301 out.push_str("</code></div></div>");
3307 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3308 render_mode: RenderMode, outer_version: Option<&str>,
3309 show_def_docs: bool) -> fmt::Result {
3310 if render_mode == RenderMode::Normal {
3311 let id = derive_id(match i.inner_impl().trait_ {
3312 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3313 None => "impl".to_string(),
3315 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3316 id, i.inner_impl())?;
3317 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3318 write!(w, "</span><span class='out-of-band'>")?;
3319 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3320 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3321 write!(w, "<div class='ghost'></div>")?;
3322 render_stability_since_raw(w, since, outer_version)?;
3323 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3324 l, "goto source code")?;
3326 render_stability_since_raw(w, since, outer_version)?;
3328 write!(w, "</span>")?;
3329 write!(w, "</h3>\n")?;
3330 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3331 write!(w, "<div class='docblock'>{}</div>",
3332 Markdown(&*dox, &i.impl_item.links()))?;
3336 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3337 link: AssocItemLink, render_mode: RenderMode,
3338 is_default_item: bool, outer_version: Option<&str>,
3339 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3340 let item_type = item.type_();
3341 let name = item.name.as_ref().unwrap();
3343 let render_method_item: bool = match render_mode {
3344 RenderMode::Normal => true,
3345 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3349 clean::MethodItem(clean::Method { ref decl, .. }) |
3350 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3351 // Only render when the method is not static or we allow static methods
3352 if render_method_item {
3353 let id = derive_id(format!("{}.{}", item_type, name));
3354 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3355 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3356 write!(w, "{}", spotlight_decl(decl)?)?;
3357 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3358 write!(w, "<code>")?;
3359 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3360 write!(w, "</code>")?;
3361 if let Some(l) = (Item { cx, item }).src_href() {
3362 write!(w, "</span><span class='out-of-band'>")?;
3363 write!(w, "<div class='ghost'></div>")?;
3364 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3365 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3366 l, "goto source code")?;
3368 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3370 write!(w, "</span></h4>\n")?;
3373 clean::TypedefItem(ref tydef, _) => {
3374 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3375 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3376 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3377 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3378 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3379 write!(w, "</code></span></h4>\n")?;
3381 clean::AssociatedConstItem(ref ty, ref default) => {
3382 let id = derive_id(format!("{}.{}", item_type, name));
3383 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3384 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3385 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3386 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3387 write!(w, "</code></span></h4>\n")?;
3389 clean::AssociatedTypeItem(ref bounds, ref default) => {
3390 let id = derive_id(format!("{}.{}", item_type, name));
3391 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3392 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3393 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3394 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3395 write!(w, "</code></span></h4>\n")?;
3397 clean::StrippedItem(..) => return Ok(()),
3398 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3401 if render_method_item || render_mode == RenderMode::Normal {
3402 let prefix = render_assoc_const_value(item);
3404 if !is_default_item {
3405 if let Some(t) = trait_ {
3406 // The trait item may have been stripped so we might not
3407 // find any documentation or stability for it.
3408 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3409 // We need the stability of the item from the trait
3410 // because impls can't have a stability.
3411 document_stability(w, cx, it)?;
3412 if item.doc_value().is_some() {
3413 document_full(w, item, cx, &prefix)?;
3414 } else if show_def_docs {
3415 // In case the item isn't documented,
3416 // provide short documentation from the trait.
3417 document_short(w, it, link, &prefix)?;
3421 document_stability(w, cx, item)?;
3423 document_full(w, item, cx, &prefix)?;
3427 document_stability(w, cx, item)?;
3429 document_short(w, item, link, &prefix)?;
3436 let traits = &cache().traits;
3437 let trait_ = i.trait_did().map(|did| &traits[&did]);
3440 write!(w, "<span class='docblock autohide'>")?;
3443 write!(w, "<div class='impl-items'>")?;
3444 for trait_item in &i.inner_impl().items {
3445 doc_impl_item(w, cx, trait_item, link, render_mode,
3446 false, outer_version, trait_, show_def_docs)?;
3449 fn render_default_items(w: &mut fmt::Formatter,
3453 render_mode: RenderMode,
3454 outer_version: Option<&str>,
3455 show_def_docs: bool) -> fmt::Result {
3456 for trait_item in &t.items {
3457 let n = trait_item.name.clone();
3458 if i.items.iter().find(|m| m.name == n).is_some() {
3461 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3462 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3464 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3465 outer_version, None, show_def_docs)?;
3470 // If we've implemented a trait, then also emit documentation for all
3471 // default items which weren't overridden in the implementation block.
3472 if let Some(t) = trait_ {
3473 render_default_items(w, cx, t, &i.inner_impl(),
3474 render_mode, outer_version, show_def_docs)?;
3476 write!(w, "</div>")?;
3479 write!(w, "</span>")?;
3485 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3486 t: &clean::Typedef) -> fmt::Result {
3487 write!(w, "<pre class='rust typedef'>")?;
3488 render_attributes(w, it)?;
3489 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3490 it.name.as_ref().unwrap(),
3492 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3495 document(w, cx, it)?;
3497 // Render any items associated directly to this alias, as otherwise they
3498 // won't be visible anywhere in the docs. It would be nice to also show
3499 // associated items from the aliased type (see discussion in #32077), but
3500 // we need #14072 to make sense of the generics.
3501 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3504 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3505 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3506 render_attributes(w, it)?;
3509 " {}type {};\n}}</pre>",
3510 VisSpace(&it.visibility),
3511 it.name.as_ref().unwrap(),
3514 document(w, cx, it)?;
3516 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3519 impl<'a> fmt::Display for Sidebar<'a> {
3520 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3523 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3524 let mut should_close = false;
3526 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3527 || it.is_enum() || it.is_mod() || it.is_typedef()
3529 write!(fmt, "<p class='location'>")?;
3531 clean::StructItem(..) => write!(fmt, "Struct ")?,
3532 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3533 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3534 clean::UnionItem(..) => write!(fmt, "Union ")?,
3535 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3536 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3537 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3538 clean::ModuleItem(..) => if it.is_crate() {
3539 write!(fmt, "Crate ")?;
3541 write!(fmt, "Module ")?;
3545 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3546 write!(fmt, "</p>")?;
3549 if let Some(ref version) = cache().crate_version {
3551 "<div class='block version'>\
3558 write!(fmt, "<div class=\"sidebar-elems\">")?;
3559 should_close = true;
3561 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3562 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3563 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3564 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3565 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3566 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3567 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3568 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3573 // The sidebar is designed to display sibling functions, modules and
3574 // other miscellaneous information. since there are lots of sibling
3575 // items (and that causes quadratic growth in large modules),
3576 // we refactor common parts into a shared JavaScript file per module.
3577 // still, we don't move everything into JS because we want to preserve
3578 // as much HTML as possible in order to allow non-JS-enabled browsers
3579 // to navigate the documentation (though slightly inefficiently).
3581 write!(fmt, "<p class='location'>")?;
3582 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3584 write!(fmt, "::<wbr>")?;
3586 write!(fmt, "<a href='{}index.html'>{}</a>",
3587 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3590 write!(fmt, "</p>")?;
3592 // Sidebar refers to the enclosing module, not this module.
3593 let relpath = if it.is_mod() { "../" } else { "" };
3595 "<script>window.sidebarCurrent = {{\
3600 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3601 ty = it.type_().css_class(),
3604 // There is no sidebar-items.js beyond the crate root path
3605 // FIXME maybe dynamic crate loading can be merged here
3607 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3611 // Closes sidebar-elems div.
3612 write!(fmt, "</div>")?;
3619 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3620 i.items.iter().filter_map(|item| {
3622 // Maybe check with clean::Visibility::Public as well?
3623 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3624 if !for_deref || should_render_item(item, false) {
3625 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3632 }).collect::<Vec<_>>()
3635 // The point is to url encode any potential character from a type with genericity.
3636 fn small_url_encode(s: &str) -> String {
3637 s.replace("<", "%3C")
3638 .replace(">", "%3E")
3639 .replace(" ", "%20")
3640 .replace("?", "%3F")
3641 .replace("'", "%27")
3642 .replace("&", "%26")
3643 .replace(",", "%2C")
3644 .replace(":", "%3A")
3645 .replace(";", "%3B")
3646 .replace("[", "%5B")
3647 .replace("]", "%5D")
3648 .replace("\"", "%22")
3651 fn sidebar_assoc_items(it: &clean::Item) -> String {
3652 let mut out = String::new();
3654 if let Some(v) = c.impls.get(&it.def_id) {
3656 .filter(|i| i.inner_impl().trait_.is_none())
3657 .flat_map(|i| get_methods(i.inner_impl(), false))
3658 .collect::<String>();
3659 if !ret.is_empty() {
3660 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3661 </a><div class=\"sidebar-links\">{}</div>", ret));
3664 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3665 if let Some(impl_) = v.iter()
3666 .filter(|i| i.inner_impl().trait_.is_some())
3667 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3668 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3670 clean::TypedefItem(ref t, true) => Some(&t.type_),
3674 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3675 c.primitive_locations.get(&prim).cloned()
3676 })).and_then(|did| c.impls.get(&did));
3677 if let Some(impls) = inner_impl {
3678 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3679 out.push_str(&format!("Methods from {}<Target={}>",
3680 Escape(&format!("{:#}",
3681 impl_.inner_impl().trait_.as_ref().unwrap())),
3682 Escape(&format!("{:#}", target))));
3683 out.push_str("</a>");
3684 let ret = impls.iter()
3685 .filter(|i| i.inner_impl().trait_.is_none())
3686 .flat_map(|i| get_methods(i.inner_impl(), true))
3687 .collect::<String>();
3688 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3692 let format_impls = |impls: Vec<&Impl>| {
3693 let mut links = HashSet::new();
3696 let is_negative_impl = is_negative_impl(i.inner_impl());
3697 if let Some(ref i) = i.inner_impl().trait_ {
3698 let i_display = format!("{:#}", i);
3699 let out = Escape(&i_display);
3700 let encoded = small_url_encode(&format!("{:#}", i));
3701 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3703 if is_negative_impl { "!" } else { "" },
3705 if links.insert(generated.clone()) {
3714 .collect::<String>()
3717 let (synthetic, concrete) = v
3719 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3721 let concrete_format = format_impls(concrete);
3722 let synthetic_format = format_impls(synthetic);
3724 if !concrete_format.is_empty() {
3725 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3726 Trait Implementations</a>");
3727 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3730 if !synthetic_format.is_empty() {
3731 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3732 Auto Trait Implementations</a>");
3733 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3741 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3742 s: &clean::Struct) -> fmt::Result {
3743 let mut sidebar = String::new();
3744 let fields = get_struct_fields_name(&s.fields);
3746 if !fields.is_empty() {
3747 if let doctree::Plain = s.struct_type {
3748 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3749 <div class=\"sidebar-links\">{}</div>", fields));
3753 sidebar.push_str(&sidebar_assoc_items(it));
3755 if !sidebar.is_empty() {
3756 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3761 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3763 clean::ItemEnum::ImplItem(ref i) => {
3764 if let Some(ref trait_) = i.trait_ {
3765 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3774 fn is_negative_impl(i: &clean::Impl) -> bool {
3775 i.polarity == Some(clean::ImplPolarity::Negative)
3778 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3779 t: &clean::Trait) -> fmt::Result {
3780 let mut sidebar = String::new();
3786 Some(ref name) if m.is_associated_type() => {
3787 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3793 .collect::<String>();
3794 let consts = t.items
3798 Some(ref name) if m.is_associated_const() => {
3799 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3805 .collect::<String>();
3806 let required = t.items
3810 Some(ref name) if m.is_ty_method() => {
3811 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3817 .collect::<String>();
3818 let provided = t.items
3822 Some(ref name) if m.is_method() => {
3823 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3828 .collect::<String>();
3830 if !types.is_empty() {
3831 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3832 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3835 if !consts.is_empty() {
3836 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3837 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3840 if !required.is_empty() {
3841 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3842 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3845 if !provided.is_empty() {
3846 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3847 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3853 if let Some(implementors) = c.implementors.get(&it.def_id) {
3854 let res = implementors.iter()
3855 .filter(|i| i.inner_impl().for_.def_id()
3856 .map_or(false, |d| !c.paths.contains_key(&d)))
3858 match extract_for_impl_name(&i.impl_item) {
3859 Some((ref name, ref url)) => {
3860 Some(format!("<a href=\"#impl-{}\">{}</a>",
3861 small_url_encode(url),
3867 .collect::<String>();
3868 if !res.is_empty() {
3869 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3870 Implementations on Foreign Types</a><div \
3871 class=\"sidebar-links\">{}</div>",
3876 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3878 sidebar.push_str("<a class=\"sidebar-title\" \
3879 href=\"#synthetic-implementors\">Auto Implementors</a>");
3882 sidebar.push_str(&sidebar_assoc_items(it));
3884 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3887 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3888 _p: &clean::PrimitiveType) -> fmt::Result {
3889 let sidebar = sidebar_assoc_items(it);
3891 if !sidebar.is_empty() {
3892 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3897 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3898 _t: &clean::Typedef) -> fmt::Result {
3899 let sidebar = sidebar_assoc_items(it);
3901 if !sidebar.is_empty() {
3902 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3907 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3909 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3914 .filter_map(|f| match f.name {
3915 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3916 {name}</a>", name=name)),
3922 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3923 u: &clean::Union) -> fmt::Result {
3924 let mut sidebar = String::new();
3925 let fields = get_struct_fields_name(&u.fields);
3927 if !fields.is_empty() {
3928 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3929 <div class=\"sidebar-links\">{}</div>", fields));
3932 sidebar.push_str(&sidebar_assoc_items(it));
3934 if !sidebar.is_empty() {
3935 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3940 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3941 e: &clean::Enum) -> fmt::Result {
3942 let mut sidebar = String::new();
3944 let variants = e.variants.iter()
3945 .filter_map(|v| match v.name {
3946 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3947 </a>", name = name)),
3950 .collect::<String>();
3951 if !variants.is_empty() {
3952 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3953 <div class=\"sidebar-links\">{}</div>", variants));
3956 sidebar.push_str(&sidebar_assoc_items(it));
3958 if !sidebar.is_empty() {
3959 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3964 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3965 items: &[clean::Item]) -> fmt::Result {
3966 let mut sidebar = String::new();
3968 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3969 it.type_() == ItemType::Import) {
3970 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3972 name = "Re-exports"));
3975 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3976 // to print its headings
3977 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3978 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3979 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3980 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3981 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3982 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3983 let (short, name) = match myty {
3984 ItemType::ExternCrate |
3985 ItemType::Import => ("reexports", "Re-exports"),
3986 ItemType::Module => ("modules", "Modules"),
3987 ItemType::Struct => ("structs", "Structs"),
3988 ItemType::Union => ("unions", "Unions"),
3989 ItemType::Enum => ("enums", "Enums"),
3990 ItemType::Function => ("functions", "Functions"),
3991 ItemType::Typedef => ("types", "Type Definitions"),
3992 ItemType::Static => ("statics", "Statics"),
3993 ItemType::Constant => ("constants", "Constants"),
3994 ItemType::Trait => ("traits", "Traits"),
3995 ItemType::Impl => ("impls", "Implementations"),
3996 ItemType::TyMethod => ("tymethods", "Type Methods"),
3997 ItemType::Method => ("methods", "Methods"),
3998 ItemType::StructField => ("fields", "Struct Fields"),
3999 ItemType::Variant => ("variants", "Variants"),
4000 ItemType::Macro => ("macros", "Macros"),
4001 ItemType::Primitive => ("primitives", "Primitive Types"),
4002 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4003 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4004 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4006 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4012 if !sidebar.is_empty() {
4013 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4018 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4019 let sidebar = sidebar_assoc_items(it);
4020 if !sidebar.is_empty() {
4021 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4026 impl<'a> fmt::Display for Source<'a> {
4027 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4028 let Source(s) = *self;
4029 let lines = s.lines().count();
4031 let mut tmp = lines;
4036 write!(fmt, "<pre class=\"line-numbers\">")?;
4037 for i in 1..lines + 1 {
4038 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4040 write!(fmt, "</pre>")?;
4042 highlight::render_with_highlighting(s, None, None, None, None))?;
4047 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4048 t: &clean::Macro) -> fmt::Result {
4049 w.write_str(&highlight::render_with_highlighting(&t.source,
4057 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4059 _p: &clean::PrimitiveType) -> fmt::Result {
4060 document(w, cx, it)?;
4061 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4064 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4066 fn make_item_keywords(it: &clean::Item) -> String {
4067 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4070 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4071 let decl = match item.inner {
4072 clean::FunctionItem(ref f) => &f.decl,
4073 clean::MethodItem(ref m) => &m.decl,
4074 clean::TyMethodItem(ref m) => &m.decl,
4078 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4079 let output = match decl.output {
4080 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4084 Some(IndexItemFunctionType { inputs: inputs, output: output })
4087 fn get_index_type(clean_type: &clean::Type) -> Type {
4089 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4090 generics: get_generics(clean_type),
4095 /// Returns a list of all paths used in the type.
4096 /// This is used to help deduplicate imported impls
4097 /// for reexported types. If any of the contained
4098 /// types are re-exported, we don't use the corresponding
4099 /// entry from the js file, as inlining will have already
4100 /// picked up the impl
4101 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4102 let mut out = Vec::new();
4103 let mut visited = FxHashSet();
4104 let mut work = VecDeque::new();
4105 let cache = cache();
4107 work.push_back(first_ty);
4109 while let Some(ty) = work.pop_front() {
4110 if !visited.insert(ty.clone()) {
4115 clean::Type::ResolvedPath { did, .. } => {
4116 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4117 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4121 out.push(path.join("::"));
4127 clean::Type::Tuple(tys) => {
4128 work.extend(tys.into_iter());
4130 clean::Type::Slice(ty) => {
4131 work.push_back(*ty);
4133 clean::Type::Array(ty, _) => {
4134 work.push_back(*ty);
4136 clean::Type::Unique(ty) => {
4137 work.push_back(*ty);
4139 clean::Type::RawPointer(_, ty) => {
4140 work.push_back(*ty);
4142 clean::Type::BorrowedRef { type_, .. } => {
4143 work.push_back(*type_);
4145 clean::Type::QPath { self_type, trait_, .. } => {
4146 work.push_back(*self_type);
4147 work.push_back(*trait_);
4155 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4157 clean::ResolvedPath { ref path, .. } => {
4158 let segments = &path.segments;
4159 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4160 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4161 clean_type, accept_generic
4163 Some(path_segment.name.clone())
4165 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4166 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4167 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4168 // FIXME: add all from clean::Type.
4173 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4174 clean_type.generics()
4176 let r = types.iter()
4177 .filter_map(|t| get_index_type_name(t, false))
4178 .map(|s| s.to_ascii_lowercase())
4179 .collect::<Vec<_>>();
4188 pub fn cache() -> Arc<Cache> {
4189 CACHE_KEY.with(|c| c.borrow().clone())
4194 fn test_unique_id() {
4195 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4196 "method.into_iter", "foo", "main", "search", "methods",
4197 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4198 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4199 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4200 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4203 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4204 assert_eq!(&actual[..], expected);
4213 fn test_name_key() {
4214 assert_eq!(name_key("0"), ("", 0, 1));
4215 assert_eq!(name_key("123"), ("", 123, 0));
4216 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4217 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4218 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4219 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4220 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4221 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4226 fn test_name_sorting() {
4227 let names = ["Apple",
4229 "Fruit", "Fruit0", "Fruit00",
4230 "Fruit1", "Fruit01",
4231 "Fruit2", "Fruit02",
4235 let mut sorted = names.to_owned();
4236 sorted.sort_by_key(|&s| name_key(s));
4237 assert_eq!(names, sorted);