1 //! Rustdoc's HTML rendering module.
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
26 pub use self::ExternalLocation::*;
29 use std::cell::RefCell;
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
34 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
36 use std::fs::{self, File, OpenOptions};
37 use std::io::prelude::*;
38 use std::io::{self, BufWriter, BufReader};
40 use std::path::{PathBuf, Path, Component};
46 use serialize::json::{ToJson, Json, as_json};
48 use syntax::ext::base::MacroKind;
49 use syntax::source_map::FileName;
50 use syntax::feature_gate::UnstableFeatures;
51 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
52 use rustc::middle::privacy::AccessLevels;
53 use rustc::middle::stability;
55 use rustc::util::nodemap::{FxHashMap, FxHashSet};
56 use rustc_data_structures::flock;
58 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
59 use crate::config::RenderOptions;
61 use crate::fold::DocFolder;
62 use crate::html::escape::Escape;
63 use crate::html::format::{AsyncSpace, ConstnessSpace};
64 use crate::html::format::{GenericBounds, WhereClause, href, AbiSpace, DefaultSpace};
65 use crate::html::format::{VisSpace, Function, UnsafetySpace, MutableSpace};
66 use crate::html::format::fmt_impl_for_trait_page;
67 use crate::html::item_type::ItemType;
68 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
69 use crate::html::{highlight, layout, static_files};
73 /// A pair of name and its optional document.
74 pub type NameDoc = (String, Option<String>);
76 pub struct SlashChecker<'a>(pub &'a str);
78 impl<'a> Display for SlashChecker<'a> {
79 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
80 if !self.0.ends_with("/") && !self.0.is_empty() {
81 write!(f, "{}/", self.0)
83 write!(f, "{}", self.0)
88 /// Major driving force in all rustdoc rendering. This contains information
89 /// about where in the tree-like hierarchy rendering is occurring and controls
90 /// how the current page is being rendered.
92 /// It is intended that this context is a lightweight object which can be fairly
93 /// easily cloned because it is cloned per work-job (about once per item in the
97 /// Current hierarchy of components leading down to what's currently being
99 pub current: Vec<String>,
100 /// The current destination folder of where HTML artifacts should be placed.
101 /// This changes as the context descends into the module hierarchy.
103 /// A flag, which when `true`, will render pages which redirect to the
104 /// real location of an item. This is used to allow external links to
105 /// publicly reused items to redirect to the right location.
106 pub render_redirect_pages: bool,
107 pub codes: ErrorCodes,
108 /// The map used to ensure all generated 'id=' attributes are unique.
109 id_map: Rc<RefCell<IdMap>>,
110 pub shared: Arc<SharedContext>,
113 struct SharedContext {
114 /// The path to the crate root source minus the file name.
115 /// Used for simplifying paths to the highlighted source code files.
116 pub src_root: PathBuf,
117 /// This describes the layout of each page, and is not modified after
118 /// creation of the context (contains info like the favicon and added html).
119 pub layout: layout::Layout,
120 /// This flag indicates whether `[src]` links should be generated or not. If
121 /// the source files are present in the html rendering, then this will be
123 pub include_sources: bool,
124 /// The local file sources we've emitted and their respective url-paths.
125 pub local_sources: FxHashMap<PathBuf, String>,
126 /// All the passes that were run on this crate.
127 pub passes: FxHashSet<String>,
128 /// The base-URL of the issue tracker for when an item has been tagged with
130 pub issue_tracker_base_url: Option<String>,
131 /// The given user css file which allow to customize the generated
132 /// documentation theme.
133 pub css_file_extension: Option<PathBuf>,
134 /// The directories that have already been created in this doc run. Used to reduce the number
135 /// of spurious `create_dir_all` calls.
136 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
137 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
138 /// should be ordered alphabetically or in order of appearance (in the source code).
139 pub sort_modules_alphabetically: bool,
140 /// Additional themes to be added to the generated docs.
141 pub themes: Vec<PathBuf>,
142 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
144 pub resource_suffix: String,
145 /// Optional path string to be used to load static files on output pages. If not set, uses
146 /// combinations of `../` to reach the documentation root.
147 pub static_root_path: Option<String>,
148 /// If false, the `select` element to have search filtering by crates on rendered docs
149 /// won't be generated.
150 pub generate_search_filter: bool,
151 /// Option disabled by default to generate files used by RLS and some other tools.
152 pub generate_redirect_pages: bool,
156 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
157 let mut dirs = self.created_dirs.borrow_mut();
158 if !dirs.contains(dst) {
159 fs::create_dir_all(dst)?;
160 dirs.insert(dst.to_path_buf());
168 /// Returns `true` if the `collapse-docs` pass was run on this crate.
169 pub fn was_collapsed(&self) -> bool {
170 self.passes.contains("collapse-docs")
173 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
174 /// `collapsed_doc_value` of the given item.
175 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
176 if self.was_collapsed() {
177 item.collapsed_doc_value().map(|s| s.into())
179 item.doc_value().map(|s| s.into())
184 /// Indicates where an external crate can be found.
185 pub enum ExternalLocation {
186 /// Remote URL root of the external crate
188 /// This external crate can be found in the local doc/ folder
190 /// The external crate could not be found.
194 /// Metadata about implementations for a type or trait.
195 #[derive(Clone, Debug)]
197 pub impl_item: clean::Item,
201 fn inner_impl(&self) -> &clean::Impl {
202 match self.impl_item.inner {
203 clean::ImplItem(ref impl_) => impl_,
204 _ => panic!("non-impl item found in impl")
208 fn trait_did(&self) -> Option<DefId> {
209 self.inner_impl().trait_.def_id()
216 pub error: io::Error,
219 impl error::Error for Error {
220 fn description(&self) -> &str {
221 self.error.description()
225 impl Display for Error {
226 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
227 write!(f, "\"{}\": {}", self.file.display(), self.error)
232 pub fn new(e: io::Error, file: &Path) -> Error {
234 file: file.to_path_buf(),
240 macro_rules! try_none {
241 ($e:expr, $file:expr) => ({
245 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
251 macro_rules! try_err {
252 ($e:expr, $file:expr) => ({
255 Err(e) => return Err(Error::new(e, $file)),
260 /// This cache is used to store information about the `clean::Crate` being
261 /// rendered in order to provide more useful documentation. This contains
262 /// information like all implementors of a trait, all traits a type implements,
263 /// documentation for all known traits, etc.
265 /// This structure purposefully does not implement `Clone` because it's intended
266 /// to be a fairly large and expensive structure to clone. Instead this adheres
267 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
268 /// rendering threads.
271 /// Mapping of typaram ids to the name of the type parameter. This is used
272 /// when pretty-printing a type (so pretty-printing doesn't have to
273 /// painfully maintain a context like this)
274 pub param_names: FxHashMap<DefId, String>,
276 /// Maps a type ID to all known implementations for that type. This is only
277 /// recognized for intra-crate `ResolvedPath` types, and is used to print
278 /// out extra documentation on the page of an enum/struct.
280 /// The values of the map are a list of implementations and documentation
281 /// found on that implementation.
282 pub impls: FxHashMap<DefId, Vec<Impl>>,
284 /// Maintains a mapping of local crate `NodeId`s to the fully qualified name
285 /// and "short type description" of that node. This is used when generating
286 /// URLs when a type is being linked to. External paths are not located in
287 /// this map because the `External` type itself has all the information
289 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
291 /// Similar to `paths`, but only holds external paths. This is only used for
292 /// generating explicit hyperlinks to other crates.
293 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
295 /// Maps local `DefId`s of exported types to fully qualified paths.
296 /// Unlike 'paths', this mapping ignores any renames that occur
297 /// due to 'use' statements.
299 /// This map is used when writing out the special 'implementors'
300 /// javascript file. By using the exact path that the type
301 /// is declared with, we ensure that each path will be identical
302 /// to the path used if the corresponding type is inlined. By
303 /// doing this, we can detect duplicate impls on a trait page, and only display
304 /// the impl for the inlined type.
305 pub exact_paths: FxHashMap<DefId, Vec<String>>,
307 /// This map contains information about all known traits of this crate.
308 /// Implementations of a crate should inherit the documentation of the
309 /// parent trait if no extra documentation is specified, and default methods
310 /// should show up in documentation about trait implementations.
311 pub traits: FxHashMap<DefId, clean::Trait>,
313 /// When rendering traits, it's often useful to be able to list all
314 /// implementors of the trait, and this mapping is exactly, that: a mapping
315 /// of trait ids to the list of known implementors of the trait
316 pub implementors: FxHashMap<DefId, Vec<Impl>>,
318 /// Cache of where external crate documentation can be found.
319 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
321 /// Cache of where documentation for primitives can be found.
322 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
324 // Note that external items for which `doc(hidden)` applies to are shown as
325 // non-reachable while local items aren't. This is because we're reusing
326 // the access levels from the privacy check pass.
327 pub access_levels: AccessLevels<DefId>,
329 /// The version of the crate being documented, if given from the `--crate-version` flag.
330 pub crate_version: Option<String>,
332 // Private fields only used when initially crawling a crate to build a cache
335 parent_stack: Vec<DefId>,
336 parent_is_trait_impl: bool,
337 search_index: Vec<IndexItem>,
339 deref_trait_did: Option<DefId>,
340 deref_mut_trait_did: Option<DefId>,
341 owned_box_did: Option<DefId>,
342 masked_crates: FxHashSet<CrateNum>,
344 // In rare case where a structure is defined in one module but implemented
345 // in another, if the implementing module is parsed before defining module,
346 // then the fully qualified name of the structure isn't presented in `paths`
347 // yet when its implementation methods are being indexed. Caches such methods
348 // and their parent id here and indexes them at the end of crate parsing.
349 orphan_impl_items: Vec<(DefId, clean::Item)>,
351 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
352 // even though the trait itself is not exported. This can happen if a trait
353 // was defined in function/expression scope, since the impl will be picked
354 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
355 // crawl. In order to prevent crashes when looking for spotlight traits or
356 // when gathering trait documentation on a type, hold impls here while
357 // folding and add them to the cache later on if we find the trait.
358 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
360 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
361 /// we need the alias element to have an array of items.
362 aliases: FxHashMap<String, Vec<IndexItem>>,
365 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
366 /// Later on moved into `CACHE_KEY`.
368 pub struct RenderInfo {
369 pub inlined: FxHashSet<DefId>,
370 pub external_paths: crate::core::ExternalPaths,
371 pub external_param_names: FxHashMap<DefId, String>,
372 pub exact_paths: FxHashMap<DefId, Vec<String>>,
373 pub access_levels: AccessLevels<DefId>,
374 pub deref_trait_did: Option<DefId>,
375 pub deref_mut_trait_did: Option<DefId>,
376 pub owned_box_did: Option<DefId>,
379 /// Helper struct to render all source code to HTML pages
380 struct SourceCollector<'a> {
381 scx: &'a mut SharedContext,
383 /// Root destination to place all HTML output into
387 /// Wrapper struct to render the source code of a file. This will do things like
388 /// adding line numbers to the left-hand side.
389 struct Source<'a>(&'a str);
391 // Helper structs for rendering items/sidebars and carrying along contextual
394 #[derive(Copy, Clone)]
397 item: &'a clean::Item,
400 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
402 /// Struct representing one entry in the JS search index. These are all emitted
403 /// by hand to a large JS file at the end of cache-creation.
410 parent: Option<DefId>,
411 parent_idx: Option<usize>,
412 search_type: Option<IndexItemFunctionType>,
415 impl ToJson for IndexItem {
416 fn to_json(&self) -> Json {
417 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
419 let mut data = Vec::with_capacity(6);
420 data.push((self.ty as usize).to_json());
421 data.push(self.name.to_json());
422 data.push(self.path.to_json());
423 data.push(self.desc.to_json());
424 data.push(self.parent_idx.to_json());
425 data.push(self.search_type.to_json());
431 /// A type used for the search index.
434 name: Option<String>,
435 generics: Option<Vec<String>>,
438 impl ToJson for Type {
439 fn to_json(&self) -> Json {
442 let mut data = Vec::with_capacity(2);
443 data.push(name.to_json());
444 if let Some(ref generics) = self.generics {
445 data.push(generics.to_json());
454 /// Full type of functions/methods in the search index.
456 struct IndexItemFunctionType {
458 output: Option<Type>,
461 impl ToJson for IndexItemFunctionType {
462 fn to_json(&self) -> Json {
463 // If we couldn't figure out a type, just write `null`.
464 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
467 let mut data = Vec::with_capacity(2);
468 data.push(self.inputs.to_json());
469 if let Some(ref output) = self.output {
470 data.push(output.to_json());
477 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
478 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
480 pub fn initial_ids() -> Vec<String> {
492 "synthetic-implementors",
494 "synthetic-implementors-list",
498 ].into_iter().map(|id| (String::from(*id))).collect()
501 /// Generates the documentation for `crate` into the directory `dst`
502 pub fn run(mut krate: clean::Crate,
503 options: RenderOptions,
504 passes: FxHashSet<String>,
505 renderinfo: RenderInfo,
506 diag: &errors::Handler) -> Result<(), Error> {
507 // need to save a copy of the options for rendering the index page
508 let md_opts = options.clone();
514 sort_modules_alphabetically,
517 extern_html_root_urls,
520 generate_search_filter,
521 generate_redirect_pages,
525 let src_root = match krate.src {
526 FileName::Real(ref p) => match p.parent() {
527 Some(p) => p.to_path_buf(),
528 None => PathBuf::new(),
532 let mut scx = SharedContext {
535 include_sources: true,
536 local_sources: Default::default(),
537 issue_tracker_base_url: None,
538 layout: layout::Layout {
540 favicon: String::new(),
542 krate: krate.name.clone(),
544 css_file_extension: extension_css,
545 created_dirs: Default::default(),
546 sort_modules_alphabetically,
550 generate_search_filter,
551 generate_redirect_pages,
554 // If user passed in `--playground-url` arg, we fill in crate name here
555 if let Some(url) = playground_url {
556 markdown::PLAYGROUND.with(|slot| {
557 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
561 // Crawl the crate attributes looking for attributes which control how we're
562 // going to emit HTML
563 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
564 for attr in attrs.lists("doc") {
565 match (attr.ident_str(), attr.value_str()) {
566 (Some("html_favicon_url"), Some(s)) => {
567 scx.layout.favicon = s.to_string();
569 (Some("html_logo_url"), Some(s)) => {
570 scx.layout.logo = s.to_string();
572 (Some("html_playground_url"), Some(s)) => {
573 markdown::PLAYGROUND.with(|slot| {
574 let name = krate.name.clone();
575 *slot.borrow_mut() = Some((Some(name), s.to_string()));
578 (Some("issue_tracker_base_url"), Some(s)) => {
579 scx.issue_tracker_base_url = Some(s.to_string());
581 (Some("html_no_source"), None) if attr.is_word() => {
582 scx.include_sources = false;
589 try_err!(fs::create_dir_all(&dst), &dst);
590 krate = render_sources(&dst, &mut scx, krate)?;
594 render_redirect_pages: false,
595 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
596 id_map: Rc::new(RefCell::new(id_map)),
597 shared: Arc::new(scx),
600 // Crawl the crate to build various caches used for the output
604 external_param_names,
612 let external_paths = external_paths.into_iter()
613 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
616 let mut cache = Cache {
617 impls: Default::default(),
620 paths: Default::default(),
621 implementors: Default::default(),
623 parent_stack: Vec::new(),
624 search_index: Vec::new(),
625 parent_is_trait_impl: false,
626 extern_locations: Default::default(),
627 primitive_locations: Default::default(),
630 crate_version: krate.version.take(),
631 orphan_impl_items: Vec::new(),
632 orphan_trait_impls: Vec::new(),
633 traits: krate.external_traits.lock().replace(Default::default()),
637 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
638 param_names: external_param_names,
639 aliases: Default::default(),
642 // Cache where all our extern crates are located
643 for &(n, ref e) in &krate.externs {
644 let src_root = match e.src {
645 FileName::Real(ref p) => match p.parent() {
646 Some(p) => p.to_path_buf(),
647 None => PathBuf::new(),
651 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
652 cache.extern_locations.insert(n, (e.name.clone(), src_root,
653 extern_location(e, extern_url, &cx.dst)));
655 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
656 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
659 // Cache where all known primitives have their documentation located.
661 // Favor linking to as local extern as possible, so iterate all crates in
662 // reverse topological order.
663 for &(_, ref e) in krate.externs.iter().rev() {
664 for &(def_id, prim, _) in &e.primitives {
665 cache.primitive_locations.insert(prim, def_id);
668 for &(def_id, prim, _) in &krate.primitives {
669 cache.primitive_locations.insert(prim, def_id);
672 cache.stack.push(krate.name.clone());
673 krate = cache.fold_crate(krate);
675 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
676 if cache.traits.contains_key(&trait_did) {
678 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
683 // Build our search index
684 let index = build_index(&krate, &mut cache);
686 // Freeze the cache now that the index has been built. Put an Arc into TLS
687 // for future parallelization opportunities
688 let cache = Arc::new(cache);
689 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
690 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
692 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
694 // And finally render the whole crate's documentation
698 /// Builds the search index from the collected metadata
699 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
700 let mut nodeid_to_pathid = FxHashMap::default();
701 let mut crate_items = Vec::with_capacity(cache.search_index.len());
702 let mut crate_paths = Vec::<Json>::new();
704 let Cache { ref mut search_index,
705 ref orphan_impl_items,
706 ref mut paths, .. } = *cache;
708 // Attach all orphan items to the type's definition if the type
709 // has since been learned.
710 for &(did, ref item) in orphan_impl_items {
711 if let Some(&(ref fqp, _)) = paths.get(&did) {
712 search_index.push(IndexItem {
714 name: item.name.clone().unwrap(),
715 path: fqp[..fqp.len() - 1].join("::"),
716 desc: plain_summary_line_short(item.doc_value()),
719 search_type: get_index_search_type(&item),
724 // Reduce `NodeId` in paths into smaller sequential numbers,
725 // and prune the paths that do not appear in the index.
726 let mut lastpath = String::new();
727 let mut lastpathid = 0usize;
729 for item in search_index {
730 item.parent_idx = item.parent.map(|nodeid| {
731 if nodeid_to_pathid.contains_key(&nodeid) {
732 *nodeid_to_pathid.get(&nodeid).unwrap()
734 let pathid = lastpathid;
735 nodeid_to_pathid.insert(nodeid, pathid);
738 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
739 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
744 // Omit the parent path if it is same to that of the prior item.
745 if lastpath == item.path {
748 lastpath = item.path.clone();
750 crate_items.push(item.to_json());
753 let crate_doc = krate.module.as_ref().map(|module| {
754 plain_summary_line_short(module.doc_value())
755 }).unwrap_or(String::new());
757 let mut crate_data = BTreeMap::new();
758 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
759 crate_data.insert("i".to_owned(), Json::Array(crate_items));
760 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
762 // Collect the index into a string
763 format!("searchIndex[{}] = {};",
764 as_json(&krate.name),
765 Json::Object(crate_data))
770 krate: &clean::Crate,
772 search_index: String,
773 options: &RenderOptions,
774 diag: &errors::Handler,
775 ) -> Result<(), Error> {
776 // Write out the shared files. Note that these are shared among all rustdoc
777 // docs placed in the output directory, so this needs to be a synchronized
778 // operation with respect to all other rustdocs running around.
779 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
781 // Add all the static files. These may already exist, but we just
782 // overwrite them anyway to make sure that they're fresh and up-to-date.
784 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
785 static_files::RUSTDOC_CSS,
786 options.enable_minification)?;
787 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
788 static_files::SETTINGS_CSS,
789 options.enable_minification)?;
790 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
791 static_files::NOSCRIPT_CSS,
792 options.enable_minification)?;
794 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
795 // then we'll run over the "official" styles.
796 let mut themes: FxHashSet<String> = FxHashSet::default();
798 for entry in &cx.shared.themes {
799 let content = try_err!(fs::read(&entry), &entry);
800 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
801 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
802 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
803 content.as_slice())?;
804 themes.insert(theme.to_owned());
807 if (*cx.shared).layout.logo.is_empty() {
808 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
809 static_files::RUST_LOGO)?;
811 if (*cx.shared).layout.favicon.is_empty() {
812 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
813 static_files::RUST_FAVICON)?;
815 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
816 static_files::BRUSH_SVG)?;
817 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
818 static_files::WHEEL_SVG)?;
819 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
820 static_files::DOWN_ARROW_SVG)?;
821 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
822 static_files::themes::LIGHT,
823 options.enable_minification)?;
824 themes.insert("light".to_owned());
825 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
826 static_files::themes::DARK,
827 options.enable_minification)?;
828 themes.insert("dark".to_owned());
830 let mut themes: Vec<&String> = themes.iter().collect();
832 // To avoid theme switch latencies as much as possible, we put everything theme related
833 // at the beginning of the html files into another js file.
834 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
836 r#"var themes = document.getElementById("theme-choices");
837 var themePicker = document.getElementById("theme-picker");
839 function switchThemeButtonState() {{
840 if (themes.style.display === "block") {{
841 themes.style.display = "none";
842 themePicker.style.borderBottomRightRadius = "3px";
843 themePicker.style.borderBottomLeftRadius = "3px";
845 themes.style.display = "block";
846 themePicker.style.borderBottomRightRadius = "0";
847 themePicker.style.borderBottomLeftRadius = "0";
851 function handleThemeButtonsBlur(e) {{
852 var active = document.activeElement;
853 var related = e.relatedTarget;
855 if (active.id !== "themePicker" &&
856 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
858 (related.id !== "themePicker" &&
859 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
860 switchThemeButtonState();
864 themePicker.onclick = switchThemeButtonState;
865 themePicker.onblur = handleThemeButtonsBlur;
866 [{}].forEach(function(item) {{
867 var but = document.createElement('button');
868 but.innerHTML = item;
869 but.onclick = function(el) {{
870 switchTheme(currentTheme, mainTheme, item);
872 but.onblur = handleThemeButtonsBlur;
873 themes.appendChild(but);
876 .map(|s| format!("\"{}\"", s))
877 .collect::<Vec<String>>()
878 .join(",")).as_bytes(),
881 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
882 static_files::MAIN_JS,
883 options.enable_minification)?;
884 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
885 static_files::SETTINGS_JS,
886 options.enable_minification)?;
887 if cx.shared.include_sources {
888 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
889 static_files::sidebar::SOURCE_SCRIPT,
890 options.enable_minification)?;
894 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
895 &format!("var resourcesSuffix = \"{}\";{}",
896 cx.shared.resource_suffix,
897 static_files::STORAGE_JS),
898 options.enable_minification)?;
901 if let Some(ref css) = cx.shared.css_file_extension {
902 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
903 if !options.enable_minification {
904 try_err!(fs::copy(css, out), css);
906 let buffer = try_err!(fs::read_to_string(css), css);
907 write_minify(out, &buffer, options.enable_minification)?;
910 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
911 static_files::NORMALIZE_CSS,
912 options.enable_minification)?;
913 write(cx.dst.join("FiraSans-Regular.woff"),
914 static_files::fira_sans::REGULAR)?;
915 write(cx.dst.join("FiraSans-Medium.woff"),
916 static_files::fira_sans::MEDIUM)?;
917 write(cx.dst.join("FiraSans-LICENSE.txt"),
918 static_files::fira_sans::LICENSE)?;
919 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
920 static_files::source_serif_pro::REGULAR)?;
921 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
922 static_files::source_serif_pro::BOLD)?;
923 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
924 static_files::source_serif_pro::ITALIC)?;
925 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
926 static_files::source_serif_pro::LICENSE)?;
927 write(cx.dst.join("SourceCodePro-Regular.woff"),
928 static_files::source_code_pro::REGULAR)?;
929 write(cx.dst.join("SourceCodePro-Semibold.woff"),
930 static_files::source_code_pro::SEMIBOLD)?;
931 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
932 static_files::source_code_pro::LICENSE)?;
933 write(cx.dst.join("LICENSE-MIT.txt"),
934 static_files::LICENSE_MIT)?;
935 write(cx.dst.join("LICENSE-APACHE.txt"),
936 static_files::LICENSE_APACHE)?;
937 write(cx.dst.join("COPYRIGHT.txt"),
938 static_files::COPYRIGHT)?;
944 for_search_index: bool,
945 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
948 let mut ret = Vec::new();
949 let mut krates = Vec::new();
950 let mut variables = Vec::new();
952 let mut krate = krate.to_owned();
955 for line in BufReader::new(File::open(path)?).lines() {
957 if for_search_index && line.starts_with("var R") {
958 variables.push(line.clone());
959 // We need to check if the crate name has been put into a variable as well.
960 let tokens = js::simple_minify(&line).apply(js::clean_tokens);
962 while pos < tokens.len() {
963 if let Some((var_pos, Some(value_pos))) =
964 js::get_variable_name_and_value_positions(&tokens, pos) {
965 if let Some(s) = tokens.0[value_pos].get_string() {
966 if &s[1..s.len() - 1] == krate {
967 if let Some(var) = tokens[var_pos].get_other() {
968 krate = var.to_owned();
978 if !line.starts_with(key) {
981 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
984 ret.push(line.to_string());
985 krates.push(line[key.len() + 2..].split('"')
987 .map(|s| s.to_owned())
988 .unwrap_or_else(|| String::new()));
991 Ok((ret, krates, variables))
994 fn show_item(item: &IndexItem, krate: &str) -> String {
995 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
996 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
997 if let Some(p) = item.parent_idx {
998 format!(",'parent':{}", p)
1004 let dst = cx.dst.join("aliases.js");
1006 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
1007 let mut w = try_err!(File::create(&dst), &dst);
1008 let mut output = String::with_capacity(100);
1009 for (alias, items) in &cache.aliases {
1010 if items.is_empty() {
1013 output.push_str(&format!("\"{}\":[{}],",
1016 .map(|v| show_item(v, &krate.name))
1017 .collect::<Vec<_>>()
1020 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1022 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1023 for aliases in &all_aliases {
1024 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1028 use std::ffi::OsString;
1033 children: FxHashMap<OsString, Hierarchy>,
1034 elems: FxHashSet<OsString>,
1038 fn new(elem: OsString) -> Hierarchy {
1041 children: FxHashMap::default(),
1042 elems: FxHashSet::default(),
1046 fn to_json_string(&self) -> String {
1047 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1048 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1049 let mut files = self.elems.iter()
1050 .map(|s| format!("\"{}\"",
1052 .expect("invalid osstring conversion")))
1053 .collect::<Vec<_>>();
1054 files.sort_unstable_by(|a, b| a.cmp(b));
1055 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1056 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1057 name=self.elem.to_str().expect("invalid osstring conversion"),
1058 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1059 files=files.join(","))
1063 if cx.shared.include_sources {
1064 use std::path::Component;
1066 let mut hierarchy = Hierarchy::new(OsString::new());
1067 for source in cx.shared.local_sources.iter()
1068 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1070 let mut h = &mut hierarchy;
1071 let mut elems = source.components()
1074 Component::Normal(s) => Some(s.to_owned()),
1080 let cur_elem = elems.next().expect("empty file path");
1081 if elems.peek().is_none() {
1082 h.elems.insert(cur_elem);
1085 let e = cur_elem.clone();
1086 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1087 h = h.children.get_mut(&cur_elem).expect("not found child");
1092 let dst = cx.dst.join("source-files.js");
1093 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1096 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1098 hierarchy.to_json_string()));
1100 let mut w = try_err!(File::create(&dst), &dst);
1101 try_err!(writeln!(&mut w,
1102 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1103 all_sources.join("\n")),
1107 // Update the search index
1108 let dst = cx.dst.join("search-index.js");
1109 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1113 all_indexes.push(search_index);
1115 // Sort the indexes by crate so the file will be generated identically even
1116 // with rustdoc running in parallel.
1118 let mut w = try_err!(File::create(&dst), &dst);
1119 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1120 try_err!(write_minify_replacer(&mut w,
1121 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1122 options.enable_minification),
1124 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1126 if options.enable_index_page {
1127 if let Some(index_page) = options.index_page.clone() {
1128 let mut md_opts = options.clone();
1129 md_opts.output = cx.dst.clone();
1130 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1132 crate::markdown::render(index_page, md_opts, diag);
1134 let dst = cx.dst.join("index.html");
1135 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1136 let page = layout::Page {
1137 title: "Index of crates",
1140 static_root_path: cx.shared.static_root_path.deref(),
1141 description: "List of crates",
1142 keywords: BASIC_KEYWORDS,
1143 resource_suffix: &cx.shared.resource_suffix,
1145 static_extra_scripts: &[],
1147 krates.push(krate.name.clone());
1151 let content = format!(
1153 <span class='in-band'>List of all crates</span>\
1154 </h1><ul class='mod'>{}</ul>",
1158 format!("<li><a href=\"{}index.html\">{}</li>",
1161 .collect::<String>());
1162 try_err!(layout::render(&mut w, &cx.shared.layout,
1163 &page, &(""), &content,
1164 cx.shared.css_file_extension.is_some(),
1166 cx.shared.generate_search_filter), &dst);
1167 try_err!(w.flush(), &dst);
1171 // Update the list of all implementors for traits
1172 let dst = cx.dst.join("implementors");
1173 for (&did, imps) in &cache.implementors {
1174 // Private modules can leak through to this phase of rustdoc, which
1175 // could contain implementations for otherwise private types. In some
1176 // rare cases we could find an implementation for an item which wasn't
1177 // indexed, so we just skip this step in that case.
1179 // FIXME: this is a vague explanation for why this can't be a `get`, in
1180 // theory it should be...
1181 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1183 None => match cache.external_paths.get(&did) {
1189 let mut have_impls = false;
1190 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1192 // If the trait and implementation are in the same crate, then
1193 // there's no need to emit information about it (there's inlining
1194 // going on). If they're in different crates then the crate defining
1195 // the trait will be interested in our implementation.
1196 if imp.impl_item.def_id.krate == did.krate { continue }
1197 // If the implementation is from another crate then that crate
1199 if !imp.impl_item.def_id.is_local() { continue }
1201 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1202 as_json(&imp.inner_impl().to_string()),
1203 imp.inner_impl().synthetic,
1204 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1206 implementors.push_str("];");
1208 // Only create a js file if we have impls to add to it. If the trait is
1209 // documented locally though we always create the file to avoid dead
1211 if !have_impls && !cache.paths.contains_key(&did) {
1215 let mut mydst = dst.clone();
1216 for part in &remote_path[..remote_path.len() - 1] {
1219 try_err!(fs::create_dir_all(&mydst), &mydst);
1220 mydst.push(&format!("{}.{}.js",
1221 remote_item_type.css_class(),
1222 remote_path[remote_path.len() - 1]));
1224 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1227 all_implementors.push(implementors);
1228 // Sort the implementors by crate so the file will be generated
1229 // identically even with rustdoc running in parallel.
1230 all_implementors.sort();
1232 let mut f = try_err!(File::create(&mydst), &mydst);
1233 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1234 for implementor in &all_implementors {
1235 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1237 try_err!(writeln!(&mut f, "{}", r"
1238 if (window.register_implementors) {
1239 window.register_implementors(implementors);
1241 window.pending_implementors = implementors;
1244 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1249 fn render_sources(dst: &Path, scx: &mut SharedContext,
1250 krate: clean::Crate) -> Result<clean::Crate, Error> {
1251 info!("emitting source files");
1252 let dst = dst.join("src").join(&krate.name);
1253 try_err!(fs::create_dir_all(&dst), &dst);
1254 let mut folder = SourceCollector {
1258 Ok(folder.fold_crate(krate))
1261 /// Writes the entire contents of a string to a destination, not attempting to
1262 /// catch any errors.
1263 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1264 Ok(try_err!(fs::write(&dst, contents), &dst))
1267 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1268 if enable_minification {
1269 if dst.extension() == Some(&OsStr::new("css")) {
1270 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1271 write(dst, res.as_bytes())
1273 write(dst, minifier::js::minify(contents).as_bytes())
1276 write(dst, contents.as_bytes())
1280 fn write_minify_replacer<W: Write>(
1283 enable_minification: bool,
1284 ) -> io::Result<()> {
1285 use minifier::js::{Keyword, ReservedChar, Token};
1287 if enable_minification {
1289 minifier::js::simple_minify(contents)
1291 // We keep backlines.
1292 minifier::js::clean_tokens_except(f, |c| {
1293 c.get_char() != Some(ReservedChar::Backline)
1297 minifier::js::replace_token_with(f, |t| {
1299 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1300 Token::String(s) => {
1301 let s = &s[1..s.len() -1]; // The quotes are included
1303 Some(Token::Other("E"))
1304 } else if s == "t" {
1305 Some(Token::Other("T"))
1306 } else if s == "u" {
1307 Some(Token::Other("U"))
1317 // We add a backline after the newly created variables.
1318 minifier::js::aggregate_strings_into_array_with_separation(
1321 Token::Char(ReservedChar::Backline),
1326 writeln!(dst, "{}", contents)
1330 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1331 /// things like ".." to components which preserve the "top down" hierarchy of a
1332 /// static HTML tree. Each component in the cleaned path will be passed as an
1333 /// argument to `f`. The very last component of the path (ie the file name) will
1334 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1335 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1338 // make it relative, if possible
1339 let p = p.strip_prefix(src_root).unwrap_or(p);
1341 let mut iter = p.components().peekable();
1343 while let Some(c) = iter.next() {
1344 if !keep_filename && iter.peek().is_none() {
1349 Component::ParentDir => f("up".as_ref()),
1350 Component::Normal(c) => f(c),
1356 /// Attempts to find where an external crate is located, given that we're
1357 /// rendering in to the specified source destination.
1358 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1361 // See if there's documentation generated into the local directory
1362 let local_location = dst.join(&e.name);
1363 if local_location.is_dir() {
1367 if let Some(url) = extern_url {
1368 let mut url = url.to_string();
1369 if !url.ends_with("/") {
1375 // Failing that, see if there's an attribute specifying where to find this
1377 e.attrs.lists("doc")
1378 .filter(|a| a.check_name("html_root_url"))
1379 .filter_map(|a| a.value_str())
1381 let mut url = url.to_string();
1382 if !url.ends_with("/") {
1386 }).next().unwrap_or(Unknown) // Well, at least we tried.
1389 impl<'a> DocFolder for SourceCollector<'a> {
1390 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1391 // If we're including source files, and we haven't seen this file yet,
1392 // then we need to render it out to the filesystem.
1393 if self.scx.include_sources
1394 // skip all invalid or macro spans
1395 && item.source.filename.is_real()
1396 // skip non-local items
1397 && item.def_id.is_local() {
1399 // If it turns out that we couldn't read this file, then we probably
1400 // can't read any of the files (generating html output from json or
1401 // something like that), so just don't include sources for the
1402 // entire crate. The other option is maintaining this mapping on a
1403 // per-file basis, but that's probably not worth it...
1405 .include_sources = match self.emit_source(&item.source.filename) {
1408 println!("warning: source code was requested to be rendered, \
1409 but processing `{}` had an error: {}",
1410 item.source.filename, e);
1411 println!(" skipping rendering of source code");
1416 self.fold_item_recur(item)
1420 impl<'a> SourceCollector<'a> {
1421 /// Renders the given filename into its corresponding HTML source file.
1422 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1423 let p = match *filename {
1424 FileName::Real(ref file) => file,
1427 if self.scx.local_sources.contains_key(&**p) {
1428 // We've already emitted this source
1432 let contents = fs::read_to_string(&p)?;
1434 // Remove the utf-8 BOM if any
1435 let contents = if contents.starts_with("\u{feff}") {
1441 // Create the intermediate directories
1442 let mut cur = self.dst.clone();
1443 let mut root_path = String::from("../../");
1444 let mut href = String::new();
1445 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1446 cur.push(component);
1447 fs::create_dir_all(&cur).unwrap();
1448 root_path.push_str("../");
1449 href.push_str(&component.to_string_lossy());
1452 let mut fname = p.file_name()
1453 .expect("source has no filename")
1455 fname.push(".html");
1457 href.push_str(&fname.to_string_lossy());
1459 let mut w = BufWriter::new(File::create(&cur)?);
1460 let title = format!("{} -- source", cur.file_name().unwrap()
1461 .to_string_lossy());
1462 let desc = format!("Source to the Rust file `{}`.", filename);
1463 let page = layout::Page {
1465 css_class: "source",
1466 root_path: &root_path,
1467 static_root_path: self.scx.static_root_path.deref(),
1469 keywords: BASIC_KEYWORDS,
1470 resource_suffix: &self.scx.resource_suffix,
1471 extra_scripts: &["source-files"],
1472 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1474 layout::render(&mut w, &self.scx.layout,
1475 &page, &(""), &Source(contents),
1476 self.scx.css_file_extension.is_some(),
1478 self.scx.generate_search_filter)?;
1480 self.scx.local_sources.insert(p.clone(), href);
1485 impl DocFolder for Cache {
1486 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1487 if item.def_id.is_local() {
1488 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1491 // If this is a stripped module,
1492 // we don't want it or its children in the search index.
1493 let orig_stripped_mod = match item.inner {
1494 clean::StrippedItem(box clean::ModuleItem(..)) => {
1495 mem::replace(&mut self.stripped_mod, true)
1497 _ => self.stripped_mod,
1500 // If the impl is from a masked crate or references something from a
1501 // masked crate then remove it completely.
1502 if let clean::ImplItem(ref i) = item.inner {
1503 if self.masked_crates.contains(&item.def_id.krate) ||
1504 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1505 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1510 // Register any generics to their corresponding string. This is used
1511 // when pretty-printing types.
1512 if let Some(generics) = item.inner.generics() {
1513 self.generics(generics);
1516 // Propagate a trait method's documentation to all implementors of the
1518 if let clean::TraitItem(ref t) = item.inner {
1519 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1522 // Collect all the implementors of traits.
1523 if let clean::ImplItem(ref i) = item.inner {
1524 if let Some(did) = i.trait_.def_id() {
1525 if i.blanket_impl.is_none() {
1526 self.implementors.entry(did).or_default().push(Impl {
1527 impl_item: item.clone(),
1533 // Index this method for searching later on.
1534 if let Some(ref s) = item.name {
1535 let (parent, is_inherent_impl_item) = match item.inner {
1536 clean::StrippedItem(..) => ((None, None), false),
1537 clean::AssociatedConstItem(..) |
1538 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1539 // skip associated items in trait impls
1540 ((None, None), false)
1542 clean::AssociatedTypeItem(..) |
1543 clean::TyMethodItem(..) |
1544 clean::StructFieldItem(..) |
1545 clean::VariantItem(..) => {
1546 ((Some(*self.parent_stack.last().unwrap()),
1547 Some(&self.stack[..self.stack.len() - 1])),
1550 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1551 if self.parent_stack.is_empty() {
1552 ((None, None), false)
1554 let last = self.parent_stack.last().unwrap();
1556 let path = match self.paths.get(&did) {
1557 // The current stack not necessarily has correlation
1558 // for where the type was defined. On the other
1559 // hand, `paths` always has the right
1560 // information if present.
1561 Some(&(ref fqp, ItemType::Trait)) |
1562 Some(&(ref fqp, ItemType::Struct)) |
1563 Some(&(ref fqp, ItemType::Union)) |
1564 Some(&(ref fqp, ItemType::Enum)) =>
1565 Some(&fqp[..fqp.len() - 1]),
1566 Some(..) => Some(&*self.stack),
1569 ((Some(*last), path), true)
1572 _ => ((None, Some(&*self.stack)), false)
1576 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1577 debug_assert!(!item.is_stripped());
1579 // A crate has a module at its root, containing all items,
1580 // which should not be indexed. The crate-item itself is
1581 // inserted later on when serializing the search-index.
1582 if item.def_id.index != CRATE_DEF_INDEX {
1583 self.search_index.push(IndexItem {
1585 name: s.to_string(),
1586 path: path.join("::"),
1587 desc: plain_summary_line_short(item.doc_value()),
1590 search_type: get_index_search_type(&item),
1594 (Some(parent), None) if is_inherent_impl_item => {
1595 // We have a parent, but we don't know where they're
1596 // defined yet. Wait for later to index this item.
1597 self.orphan_impl_items.push((parent, item.clone()));
1603 // Keep track of the fully qualified path for this item.
1604 let pushed = match item.name {
1605 Some(ref n) if !n.is_empty() => {
1606 self.stack.push(n.to_string());
1613 clean::StructItem(..) | clean::EnumItem(..) |
1614 clean::TypedefItem(..) | clean::TraitItem(..) |
1615 clean::FunctionItem(..) | clean::ModuleItem(..) |
1616 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1617 clean::ConstantItem(..) | clean::StaticItem(..) |
1618 clean::UnionItem(..) | clean::ForeignTypeItem |
1619 clean::MacroItem(..) | clean::ProcMacroItem(..)
1620 if !self.stripped_mod => {
1621 // Re-exported items mean that the same id can show up twice
1622 // in the rustdoc ast that we're looking at. We know,
1623 // however, that a re-exported item doesn't show up in the
1624 // `public_items` map, so we can skip inserting into the
1625 // paths map if there was already an entry present and we're
1626 // not a public item.
1627 if !self.paths.contains_key(&item.def_id) ||
1628 self.access_levels.is_public(item.def_id)
1630 self.paths.insert(item.def_id,
1631 (self.stack.clone(), item.type_()));
1633 self.add_aliases(&item);
1635 // Link variants to their parent enum because pages aren't emitted
1636 // for each variant.
1637 clean::VariantItem(..) if !self.stripped_mod => {
1638 let mut stack = self.stack.clone();
1640 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1643 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1644 self.add_aliases(&item);
1645 self.paths.insert(item.def_id, (self.stack.clone(),
1652 // Maintain the parent stack
1653 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1654 let parent_pushed = match item.inner {
1655 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1656 clean::StructItem(..) | clean::UnionItem(..) => {
1657 self.parent_stack.push(item.def_id);
1658 self.parent_is_trait_impl = false;
1661 clean::ImplItem(ref i) => {
1662 self.parent_is_trait_impl = i.trait_.is_some();
1664 clean::ResolvedPath{ did, .. } => {
1665 self.parent_stack.push(did);
1669 let prim_did = t.primitive_type().and_then(|t| {
1670 self.primitive_locations.get(&t).cloned()
1674 self.parent_stack.push(did);
1685 // Once we've recursively found all the generics, hoard off all the
1686 // implementations elsewhere.
1687 let ret = self.fold_item_recur(item).and_then(|item| {
1688 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1689 // Figure out the id of this impl. This may map to a
1690 // primitive rather than always to a struct/enum.
1691 // Note: matching twice to restrict the lifetime of the `i` borrow.
1692 let mut dids = FxHashSet::default();
1693 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1695 clean::ResolvedPath { did, .. } |
1696 clean::BorrowedRef {
1697 type_: box clean::ResolvedPath { did, .. }, ..
1702 let did = t.primitive_type().and_then(|t| {
1703 self.primitive_locations.get(&t).cloned()
1706 if let Some(did) = did {
1712 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1713 for bound in generics {
1714 if let Some(did) = bound.def_id() {
1722 let impl_item = Impl {
1725 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1727 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1730 let trait_did = impl_item.trait_did().unwrap();
1731 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1739 if pushed { self.stack.pop().unwrap(); }
1740 if parent_pushed { self.parent_stack.pop().unwrap(); }
1741 self.stripped_mod = orig_stripped_mod;
1742 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1748 fn generics(&mut self, generics: &clean::Generics) {
1749 for param in &generics.params {
1751 clean::GenericParamDefKind::Lifetime => {}
1752 clean::GenericParamDefKind::Type { did, .. } |
1753 clean::GenericParamDefKind::Const { did, .. } => {
1754 self.param_names.insert(did, param.name.clone());
1760 fn add_aliases(&mut self, item: &clean::Item) {
1761 if item.def_id.index == CRATE_DEF_INDEX {
1764 if let Some(ref item_name) = item.name {
1765 let path = self.paths.get(&item.def_id)
1766 .map(|p| p.0[..p.0.len() - 1].join("::"))
1767 .unwrap_or("std".to_owned());
1768 for alias in item.attrs.lists("doc")
1769 .filter(|a| a.check_name("alias"))
1770 .filter_map(|a| a.value_str()
1771 .map(|s| s.to_string().replace("\"", "")))
1772 .filter(|v| !v.is_empty())
1773 .collect::<FxHashSet<_>>()
1775 self.aliases.entry(alias)
1776 .or_insert(Vec::with_capacity(1))
1779 name: item_name.to_string(),
1781 desc: plain_summary_line_short(item.doc_value()),
1784 search_type: get_index_search_type(&item),
1791 #[derive(Debug, Eq, PartialEq, Hash)]
1798 fn new(mut url: String, name: String) -> ItemEntry {
1799 while url.starts_with('/') {
1809 impl fmt::Display for ItemEntry {
1810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1811 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1815 impl PartialOrd for ItemEntry {
1816 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1817 Some(self.cmp(other))
1821 impl Ord for ItemEntry {
1822 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1823 self.name.cmp(&other.name)
1829 structs: FxHashSet<ItemEntry>,
1830 enums: FxHashSet<ItemEntry>,
1831 unions: FxHashSet<ItemEntry>,
1832 primitives: FxHashSet<ItemEntry>,
1833 traits: FxHashSet<ItemEntry>,
1834 macros: FxHashSet<ItemEntry>,
1835 functions: FxHashSet<ItemEntry>,
1836 typedefs: FxHashSet<ItemEntry>,
1837 existentials: FxHashSet<ItemEntry>,
1838 statics: FxHashSet<ItemEntry>,
1839 constants: FxHashSet<ItemEntry>,
1840 keywords: FxHashSet<ItemEntry>,
1841 attributes: FxHashSet<ItemEntry>,
1842 derives: FxHashSet<ItemEntry>,
1843 trait_aliases: FxHashSet<ItemEntry>,
1847 fn new() -> AllTypes {
1848 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1850 structs: new_set(100),
1851 enums: new_set(100),
1852 unions: new_set(100),
1853 primitives: new_set(26),
1854 traits: new_set(100),
1855 macros: new_set(100),
1856 functions: new_set(100),
1857 typedefs: new_set(100),
1858 existentials: new_set(100),
1859 statics: new_set(100),
1860 constants: new_set(100),
1861 keywords: new_set(100),
1862 attributes: new_set(100),
1863 derives: new_set(100),
1864 trait_aliases: new_set(100),
1868 fn append(&mut self, item_name: String, item_type: &ItemType) {
1869 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1870 if let Some(name) = url.pop() {
1871 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1873 let name = url.join("::");
1875 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1876 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1877 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1878 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1879 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1880 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1881 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1882 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1883 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1884 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1885 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1886 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1887 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1888 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1895 fn print_entries(f: &mut fmt::Formatter<'_>, e: &FxHashSet<ItemEntry>, title: &str,
1896 class: &str) -> fmt::Result {
1898 let mut e: Vec<&ItemEntry> = e.iter().collect();
1900 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1904 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1909 impl fmt::Display for AllTypes {
1910 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1913 <span class='out-of-band'>\
1914 <span id='render-detail'>\
1915 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1916 [<span class='inner'>−</span>]\
1920 <span class='in-band'>List of all items</span>\
1922 print_entries(f, &self.structs, "Structs", "structs")?;
1923 print_entries(f, &self.enums, "Enums", "enums")?;
1924 print_entries(f, &self.unions, "Unions", "unions")?;
1925 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1926 print_entries(f, &self.traits, "Traits", "traits")?;
1927 print_entries(f, &self.macros, "Macros", "macros")?;
1928 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1929 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1930 print_entries(f, &self.functions, "Functions", "functions")?;
1931 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1932 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1933 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1934 print_entries(f, &self.statics, "Statics", "statics")?;
1935 print_entries(f, &self.constants, "Constants", "constants")
1940 struct Settings<'a> {
1941 // (id, explanation, default value)
1942 settings: Vec<(&'static str, &'static str, bool)>,
1947 impl<'a> Settings<'a> {
1948 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1951 ("item-declarations", "Auto-hide item declarations.", true),
1952 ("item-attributes", "Auto-hide item attributes.", true),
1953 ("trait-implementations", "Auto-hide trait implementations documentation",
1955 ("method-docs", "Auto-hide item methods' documentation", false),
1956 ("go-to-only-result", "Directly go to item in search if there is only one result",
1958 ("line-numbers", "Show line numbers on code examples", false),
1966 impl<'a> fmt::Display for Settings<'a> {
1967 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1970 <span class='in-band'>Rustdoc settings</span>\
1972 <div class='settings'>{}</div>\
1973 <script src='{}settings{}.js'></script>",
1974 self.settings.iter()
1975 .map(|(id, text, enabled)| {
1976 format!("<div class='setting-line'>\
1977 <label class='toggle'>\
1978 <input type='checkbox' id='{}' {}>\
1979 <span class='slider'></span>\
1982 </div>", id, if *enabled { " checked" } else { "" }, text)
1984 .collect::<String>(),
1991 fn derive_id(&self, id: String) -> String {
1992 let mut map = self.id_map.borrow_mut();
1996 /// String representation of how to get back to the root path of the 'doc/'
1997 /// folder in terms of a relative URL.
1998 fn root_path(&self) -> String {
1999 "../".repeat(self.current.len())
2002 /// Recurse in the directory structure and change the "root path" to make
2003 /// sure it always points to the top (relatively).
2004 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2005 F: FnOnce(&mut Context) -> T,
2008 panic!("Unexpected empty destination: {:?}", self.current);
2010 let prev = self.dst.clone();
2012 self.current.push(s);
2014 info!("Recursing into {}", self.dst.display());
2018 info!("Recursed; leaving {}", self.dst.display());
2020 // Go back to where we were at
2022 self.current.pop().unwrap();
2027 /// Main method for rendering a crate.
2029 /// This currently isn't parallelized, but it'd be pretty easy to add
2030 /// parallelization to this function.
2031 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2032 let mut item = match krate.module.take() {
2034 None => return Ok(()),
2036 let final_file = self.dst.join(&krate.name)
2038 let settings_file = self.dst.join("settings.html");
2040 let crate_name = krate.name.clone();
2041 item.name = Some(krate.name);
2043 let mut all = AllTypes::new();
2046 // Render the crate documentation
2047 let mut work = vec![(self.clone(), item)];
2049 while let Some((mut cx, item)) = work.pop() {
2050 cx.item(item, &mut all, |cx, item| {
2051 work.push((cx.clone(), item))
2056 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2057 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2058 if !root_path.ends_with('/') {
2059 root_path.push('/');
2061 let mut page = layout::Page {
2062 title: "List of all items in this crate",
2065 static_root_path: self.shared.static_root_path.deref(),
2066 description: "List of all items in this crate",
2067 keywords: BASIC_KEYWORDS,
2068 resource_suffix: &self.shared.resource_suffix,
2070 static_extra_scripts: &[],
2072 let sidebar = if let Some(ref version) = cache().crate_version {
2073 format!("<p class='location'>Crate {}</p>\
2074 <div class='block version'>\
2077 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2078 crate_name, version)
2082 try_err!(layout::render(&mut w, &self.shared.layout,
2083 &page, &sidebar, &all,
2084 self.shared.css_file_extension.is_some(),
2085 &self.shared.themes,
2086 self.shared.generate_search_filter),
2089 // Generating settings page.
2090 let settings = Settings::new("./", &self.shared.resource_suffix);
2091 page.title = "Rustdoc settings";
2092 page.description = "Settings of Rustdoc";
2093 page.root_path = "./";
2095 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2096 let mut themes = self.shared.themes.clone();
2097 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2098 themes.push(PathBuf::from("settings.css"));
2099 let layout = self.shared.layout.clone();
2100 try_err!(layout::render(&mut w, &layout,
2101 &page, &sidebar, &settings,
2102 self.shared.css_file_extension.is_some(),
2104 self.shared.generate_search_filter),
2110 fn render_item(&self,
2111 writer: &mut dyn io::Write,
2115 // A little unfortunate that this is done like this, but it sure
2116 // does make formatting *a lot* nicer.
2117 CURRENT_LOCATION_KEY.with(|slot| {
2118 *slot.borrow_mut() = self.current.clone();
2121 let mut title = if it.is_primitive() || it.is_keyword() {
2122 // No need to include the namespace for primitive types and keywords
2125 self.current.join("::")
2128 if !title.is_empty() {
2129 title.push_str("::");
2131 title.push_str(it.name.as_ref().unwrap());
2133 title.push_str(" - Rust");
2134 let tyname = it.type_().css_class();
2135 let desc = if it.is_crate() {
2136 format!("API documentation for the Rust `{}` crate.",
2137 self.shared.layout.krate)
2139 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2140 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2142 let keywords = make_item_keywords(it);
2143 let page = layout::Page {
2145 root_path: &self.root_path(),
2146 static_root_path: self.shared.static_root_path.deref(),
2149 keywords: &keywords,
2150 resource_suffix: &self.shared.resource_suffix,
2152 static_extra_scripts: &[],
2156 self.id_map.borrow_mut().reset();
2157 self.id_map.borrow_mut().populate(initial_ids());
2160 if !self.render_redirect_pages {
2161 layout::render(writer, &self.shared.layout, &page,
2162 &Sidebar{ cx: self, item: it },
2163 &Item{ cx: self, item: it },
2164 self.shared.css_file_extension.is_some(),
2165 &self.shared.themes,
2166 self.shared.generate_search_filter)?;
2168 let mut url = self.root_path();
2169 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2170 for name in &names[..names.len() - 1] {
2174 url.push_str(&item_path(ty, names.last().unwrap()));
2175 layout::redirect(writer, &url)?;
2181 /// Non-parallelized version of rendering an item. This will take the input
2182 /// item, render its contents, and then invoke the specified closure with
2183 /// all sub-items which need to be rendered.
2185 /// The rendering driver uses this closure to queue up more work.
2186 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2187 where F: FnMut(&mut Context, clean::Item),
2189 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2190 // if they contain impls for public types. These modules can also
2191 // contain items such as publicly re-exported structures.
2193 // External crates will provide links to these structures, so
2194 // these modules are recursed into, but not rendered normally
2195 // (a flag on the context).
2196 if !self.render_redirect_pages {
2197 self.render_redirect_pages = item.is_stripped();
2201 // modules are special because they add a namespace. We also need to
2202 // recurse into the items of the module as well.
2203 let name = item.name.as_ref().unwrap().to_string();
2204 let mut item = Some(item);
2205 self.recurse(name, |this| {
2206 let item = item.take().unwrap();
2208 let mut buf = Vec::new();
2209 this.render_item(&mut buf, &item, false).unwrap();
2210 // buf will be empty if the module is stripped and there is no redirect for it
2211 if !buf.is_empty() {
2212 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2213 let joint_dst = this.dst.join("index.html");
2214 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2217 let m = match item.inner {
2218 clean::StrippedItem(box clean::ModuleItem(m)) |
2219 clean::ModuleItem(m) => m,
2223 // Render sidebar-items.js used throughout this module.
2224 if !this.render_redirect_pages {
2225 let items = this.build_sidebar_items(&m);
2226 let js_dst = this.dst.join("sidebar-items.js");
2227 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2228 try_err!(write!(&mut js_out, "initSidebarItems({});",
2229 as_json(&items)), &js_dst);
2232 for item in m.items {
2238 } else if item.name.is_some() {
2239 let mut buf = Vec::new();
2240 self.render_item(&mut buf, &item, true).unwrap();
2241 // buf will be empty if the item is stripped and there is no redirect for it
2242 if !buf.is_empty() {
2243 let name = item.name.as_ref().unwrap();
2244 let item_type = item.type_();
2245 let file_name = &item_path(item_type, name);
2246 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2247 let joint_dst = self.dst.join(file_name);
2248 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2250 if !self.render_redirect_pages {
2251 all.append(full_path(self, &item), &item_type);
2253 if self.shared.generate_redirect_pages {
2254 // Redirect from a sane URL using the namespace to Rustdoc's
2255 // URL for the page.
2256 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2257 let redir_dst = self.dst.join(redir_name);
2258 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2261 let mut redirect_out = BufWriter::new(redirect_out);
2262 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2265 // If the item is a macro, redirect from the old macro URL (with !)
2266 // to the new one (without).
2267 if item_type == ItemType::Macro {
2268 let redir_name = format!("{}.{}!.html", item_type, name);
2269 let redir_dst = self.dst.join(redir_name);
2270 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2271 let mut redirect_out = BufWriter::new(redirect_out);
2272 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2279 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2280 // BTreeMap instead of HashMap to get a sorted output
2281 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2282 for item in &m.items {
2283 if item.is_stripped() { continue }
2285 let short = item.type_().css_class();
2286 let myname = match item.name {
2288 Some(ref s) => s.to_string(),
2290 let short = short.to_string();
2291 map.entry(short).or_default()
2292 .push((myname, Some(plain_summary_line(item.doc_value()))));
2295 if self.shared.sort_modules_alphabetically {
2296 for (_, items) in &mut map {
2305 /// Generates a url appropriate for an `href` attribute back to the source of
2308 /// The url generated, when clicked, will redirect the browser back to the
2309 /// original source code.
2311 /// If `None` is returned, then a source link couldn't be generated. This
2312 /// may happen, for example, with externally inlined items where the source
2313 /// of their crate documentation isn't known.
2314 fn src_href(&self) -> Option<String> {
2315 let mut root = self.cx.root_path();
2317 let cache = cache();
2318 let mut path = String::new();
2320 // We can safely ignore macros from other libraries
2321 let file = match self.item.source.filename {
2322 FileName::Real(ref path) => path,
2326 let (krate, path) = if self.item.def_id.is_local() {
2327 if let Some(path) = self.cx.shared.local_sources.get(file) {
2328 (&self.cx.shared.layout.krate, path)
2333 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2334 (ref name, ref src, Local) => (name, src),
2335 (ref name, ref src, Remote(ref s)) => {
2336 root = s.to_string();
2339 (_, _, Unknown) => return None,
2342 clean_srcpath(&src_root, file, false, |component| {
2343 path.push_str(&component.to_string_lossy());
2346 let mut fname = file.file_name().expect("source has no filename")
2348 fname.push(".html");
2349 path.push_str(&fname.to_string_lossy());
2353 let lines = if self.item.source.loline == self.item.source.hiline {
2354 self.item.source.loline.to_string()
2356 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2358 Some(format!("{root}src/{krate}/{path}#{lines}",
2359 root = Escape(&root),
2366 fn wrap_into_docblock<F>(w: &mut fmt::Formatter<'_>,
2367 f: F) -> fmt::Result
2368 where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result {
2369 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2374 impl<'a> fmt::Display for Item<'a> {
2375 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2376 debug_assert!(!self.item.is_stripped());
2377 // Write the breadcrumb trail header for the top
2378 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2379 if let Some(version) = self.item.stable_since() {
2380 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2384 "<span id='render-detail'>\
2385 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2386 title=\"collapse all docs\">\
2387 [<span class='inner'>−</span>]\
2393 // When this item is part of a `pub use` in a downstream crate, the
2394 // [src] link in the downstream documentation will actually come back to
2395 // this page, and this link will be auto-clicked. The `id` attribute is
2396 // used to find the link to auto-click.
2397 if self.cx.shared.include_sources && !self.item.is_primitive() {
2398 if let Some(l) = self.src_href() {
2399 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2400 l, "goto source code")?;
2404 write!(fmt, "</span>")?; // out-of-band
2405 write!(fmt, "<span class='in-band'>")?;
2406 match self.item.inner {
2407 clean::ModuleItem(ref m) => if m.is_crate {
2408 write!(fmt, "Crate ")?;
2410 write!(fmt, "Module ")?;
2412 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2413 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2414 clean::StructItem(..) => write!(fmt, "Struct ")?,
2415 clean::UnionItem(..) => write!(fmt, "Union ")?,
2416 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2417 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2418 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2419 clean::ProcMacroItem(ref mac) => match mac.kind {
2420 MacroKind::Bang => write!(fmt, "Macro ")?,
2421 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2422 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2423 MacroKind::ProcMacroStub => unreachable!(),
2425 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2426 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2427 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2428 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2429 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2430 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2431 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2433 // We don't generate pages for any other type.
2437 if !self.item.is_primitive() && !self.item.is_keyword() {
2438 let cur = &self.cx.current;
2439 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2440 for (i, component) in cur.iter().enumerate().take(amt) {
2441 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2442 "../".repeat(cur.len() - i - 1),
2446 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2447 self.item.type_(), self.item.name.as_ref().unwrap())?;
2449 write!(fmt, "</span></h1>")?; // in-band
2451 match self.item.inner {
2452 clean::ModuleItem(ref m) =>
2453 item_module(fmt, self.cx, self.item, &m.items),
2454 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2455 item_function(fmt, self.cx, self.item, f),
2456 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2457 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2458 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2459 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2460 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2461 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2462 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2463 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2464 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2465 item_static(fmt, self.cx, self.item, i),
2466 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2467 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2468 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2469 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2470 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2472 // We don't generate pages for any other type.
2479 fn item_path(ty: ItemType, name: &str) -> String {
2481 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2482 _ => format!("{}.{}.html", ty.css_class(), name),
2486 fn full_path(cx: &Context, item: &clean::Item) -> String {
2487 let mut s = cx.current.join("::");
2489 s.push_str(item.name.as_ref().unwrap());
2493 fn shorter<'a>(s: Option<&'a str>) -> String {
2495 Some(s) => s.lines()
2496 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2498 (*line).chars().any(|chr|{
2499 !chr.is_whitespace()
2501 }).collect::<Vec<_>>().join("\n"),
2502 None => String::new()
2507 fn plain_summary_line(s: Option<&str>) -> String {
2508 let line = shorter(s).replace("\n", " ");
2509 markdown::plain_summary_line_full(&line[..], false)
2513 fn plain_summary_line_short(s: Option<&str>) -> String {
2514 let line = shorter(s).replace("\n", " ");
2515 markdown::plain_summary_line_full(&line[..], true)
2518 fn document(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item) -> fmt::Result {
2519 if let Some(ref name) = item.name {
2520 info!("Documenting {}", name);
2522 document_stability(w, cx, item, false)?;
2523 document_full(w, item, cx, "", false)?;
2527 /// Render md_text as markdown.
2528 fn render_markdown(w: &mut fmt::Formatter<'_>,
2531 links: Vec<(String, String)>,
2535 let mut ids = cx.id_map.borrow_mut();
2536 write!(w, "<div class='docblock{}'>{}{}</div>",
2537 if is_hidden { " hidden" } else { "" },
2539 Markdown(md_text, &links, RefCell::new(&mut ids),
2544 w: &mut fmt::Formatter<'_>,
2547 link: AssocItemLink<'_>,
2548 prefix: &str, is_hidden: bool
2550 if let Some(s) = item.doc_value() {
2551 let markdown = if s.contains('\n') {
2552 format!("{} [Read more]({})",
2553 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2555 plain_summary_line(Some(s))
2557 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2558 } else if !prefix.is_empty() {
2559 write!(w, "<div class='docblock{}'>{}</div>",
2560 if is_hidden { " hidden" } else { "" },
2566 fn document_full(w: &mut fmt::Formatter<'_>, item: &clean::Item,
2567 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2568 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2569 debug!("Doc block: =====\n{}\n=====", s);
2570 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2571 } else if !prefix.is_empty() {
2572 write!(w, "<div class='docblock{}'>{}</div>",
2573 if is_hidden { " hidden" } else { "" },
2579 fn document_stability(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
2580 is_hidden: bool) -> fmt::Result {
2581 let stabilities = short_stability(item, cx);
2582 if !stabilities.is_empty() {
2583 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2584 for stability in stabilities {
2585 write!(w, "{}", stability)?;
2587 write!(w, "</div>")?;
2592 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2593 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2596 fn document_non_exhaustive(w: &mut fmt::Formatter<'_>, item: &clean::Item) -> fmt::Result {
2597 if item.is_non_exhaustive() {
2598 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2599 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2602 if item.is_struct() {
2603 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2604 Therefore, non-exhaustive structs cannot be constructed in external crates \
2605 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2606 matched against without a wildcard <code>..</code>; and \
2607 struct update syntax will not work.")?;
2608 } else if item.is_enum() {
2609 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2610 Therefore, when matching against variants of non-exhaustive enums, an \
2611 extra wildcard arm must be added to account for any future variants.")?;
2613 write!(w, "This type will require a wildcard arm in any match statements or \
2617 write!(w, "</div>")?;
2623 fn name_key(name: &str) -> (&str, u64, usize) {
2624 let end = name.bytes()
2625 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2627 // find number at end
2628 let split = name[0..end].bytes()
2629 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2631 // count leading zeroes
2633 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2635 // sort leading zeroes last
2636 let num_zeroes = after_zeroes - split;
2638 match name[split..end].parse() {
2639 Ok(n) => (&name[..split], n, num_zeroes),
2640 Err(_) => (name, 0, num_zeroes),
2644 fn item_module(w: &mut fmt::Formatter<'_>, cx: &Context,
2645 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2646 document(w, cx, item)?;
2648 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2650 // the order of item types in the listing
2651 fn reorder(ty: ItemType) -> u8 {
2653 ItemType::ExternCrate => 0,
2654 ItemType::Import => 1,
2655 ItemType::Primitive => 2,
2656 ItemType::Module => 3,
2657 ItemType::Macro => 4,
2658 ItemType::Struct => 5,
2659 ItemType::Enum => 6,
2660 ItemType::Constant => 7,
2661 ItemType::Static => 8,
2662 ItemType::Trait => 9,
2663 ItemType::Function => 10,
2664 ItemType::Typedef => 12,
2665 ItemType::Union => 13,
2670 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2671 let ty1 = i1.type_();
2672 let ty2 = i2.type_();
2674 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2676 let s1 = i1.stability.as_ref().map(|s| s.level);
2677 let s2 = i2.stability.as_ref().map(|s| s.level);
2679 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2680 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2683 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2684 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2685 name_key(lhs).cmp(&name_key(rhs))
2688 if cx.shared.sort_modules_alphabetically {
2689 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2691 // This call is to remove re-export duplicates in cases such as:
2696 // pub trait Double { fn foo(); }
2700 // pub use foo::bar::*;
2704 // `Double` will appear twice in the generated docs.
2706 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2707 // can be identical even if the elements are different (mostly in imports).
2708 // So in case this is an import, we keep everything by adding a "unique id"
2709 // (which is the position in the vector).
2710 indices.dedup_by_key(|i| (items[*i].def_id,
2711 if items[*i].name.as_ref().is_some() {
2712 Some(full_path(cx, &items[*i]))
2717 if items[*i].is_import() {
2723 debug!("{:?}", indices);
2724 let mut curty = None;
2725 for &idx in &indices {
2726 let myitem = &items[idx];
2727 if myitem.is_stripped() {
2731 let myty = Some(myitem.type_());
2732 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2733 // Put `extern crate` and `use` re-exports in the same section.
2735 } else if myty != curty {
2736 if curty.is_some() {
2737 write!(w, "</table>")?;
2740 let (short, name) = item_ty_to_strs(&myty.unwrap());
2741 write!(w, "<h2 id='{id}' class='section-header'>\
2742 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2743 id = cx.derive_id(short.to_owned()), name = name)?;
2746 match myitem.inner {
2747 clean::ExternCrateItem(ref name, ref src) => {
2748 use crate::html::format::HRef;
2752 write!(w, "<tr><td><code>{}extern crate {} as {};",
2753 VisSpace(&myitem.visibility),
2754 HRef::new(myitem.def_id, src),
2758 write!(w, "<tr><td><code>{}extern crate {};",
2759 VisSpace(&myitem.visibility),
2760 HRef::new(myitem.def_id, name))?
2763 write!(w, "</code></td></tr>")?;
2766 clean::ImportItem(ref import) => {
2767 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2768 VisSpace(&myitem.visibility), *import)?;
2772 if myitem.name.is_none() { continue }
2774 let unsafety_flag = match myitem.inner {
2775 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2776 if func.header.unsafety == hir::Unsafety::Unsafe => {
2777 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2782 let stab = myitem.stability_class();
2783 let add = if stab.is_some() {
2789 let doc_value = myitem.doc_value().unwrap_or("");
2791 <tr class='{stab}{add}module-item'>\
2792 <td><a class=\"{class}\" href=\"{href}\" \
2793 title='{title}'>{name}</a>{unsafety_flag}</td>\
2794 <td class='docblock-short'>{stab_tags}{docs}</td>\
2796 name = *myitem.name.as_ref().unwrap(),
2797 stab_tags = stability_tags(myitem),
2798 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2799 class = myitem.type_(),
2801 stab = stab.unwrap_or_else(|| String::new()),
2802 unsafety_flag = unsafety_flag,
2803 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2804 title = [full_path(cx, myitem), myitem.type_().to_string()]
2806 .filter_map(|s| if !s.is_empty() {
2811 .collect::<Vec<_>>()
2818 if curty.is_some() {
2819 write!(w, "</table>")?;
2824 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2826 fn stability_tags(item: &clean::Item) -> String {
2827 let mut tags = String::new();
2829 fn tag_html(class: &str, contents: &str) -> String {
2830 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2833 // The trailing space after each tag is to space it properly against the rest of the docs.
2834 if item.deprecation().is_some() {
2835 let mut message = "Deprecated";
2836 if let Some(ref stab) = item.stability {
2837 if let Some(ref depr) = stab.deprecation {
2838 if let Some(ref since) = depr.since {
2839 if !stability::deprecation_in_effect(&since) {
2840 message = "Deprecation planned";
2845 tags += &tag_html("deprecated", message);
2848 if let Some(stab) = item
2851 .filter(|s| s.level == stability::Unstable)
2853 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2854 tags += &tag_html("internal", "Internal");
2856 tags += &tag_html("unstable", "Experimental");
2860 if let Some(ref cfg) = item.attrs.cfg {
2861 tags += &tag_html("portability", &cfg.render_short_html());
2867 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2869 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2870 let mut stability = vec![];
2871 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2873 if let Some(Deprecation { note, since }) = &item.deprecation() {
2874 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2875 // but only display the future-deprecation messages for #[rustc_deprecated].
2876 let mut message = if let Some(since) = since {
2877 format!("Deprecated since {}", Escape(since))
2879 String::from("Deprecated")
2881 if let Some(ref stab) = item.stability {
2882 if let Some(ref depr) = stab.deprecation {
2883 if let Some(ref since) = depr.since {
2884 if !stability::deprecation_in_effect(&since) {
2885 message = format!("Deprecating in {}", Escape(&since));
2891 if let Some(note) = note {
2892 let mut ids = cx.id_map.borrow_mut();
2893 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2894 message.push_str(&format!(": {}", html));
2896 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2899 if let Some(stab) = item
2902 .filter(|stab| stab.level == stability::Unstable)
2904 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2906 let mut message = if is_rustc_private {
2907 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2909 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2913 if let Some(feature) = stab.feature.as_ref() {
2914 let mut feature = format!("<code>{}</code>", Escape(&feature));
2915 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2916 feature.push_str(&format!(
2917 " <a href=\"{url}{issue}\">#{issue}</a>",
2923 message.push_str(&format!(" ({})", feature));
2926 if let Some(unstable_reason) = &stab.unstable_reason {
2927 // Provide a more informative message than the compiler help.
2928 let unstable_reason = if is_rustc_private {
2929 "This crate is being loaded from the sysroot, a permanently unstable location \
2930 for private compiler dependencies. It is not intended for general use. Prefer \
2931 using a public version of this crate from \
2932 [crates.io](https://crates.io) via [`Cargo.toml`]\
2933 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2938 let mut ids = cx.id_map.borrow_mut();
2940 "<details><summary>{}</summary>{}</details>",
2942 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2946 let class = if is_rustc_private {
2951 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2954 if let Some(ref cfg) = item.attrs.cfg {
2955 stability.push(format!(
2956 "<div class='stab portability'>{}</div>",
2957 cfg.render_long_html()
2964 fn item_constant(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2965 c: &clean::Constant) -> fmt::Result {
2966 write!(w, "<pre class='rust const'>")?;
2967 render_attributes(w, it)?;
2968 write!(w, "{vis}const \
2969 {name}: {typ}</pre>",
2970 vis = VisSpace(&it.visibility),
2971 name = it.name.as_ref().unwrap(),
2976 fn item_static(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2977 s: &clean::Static) -> fmt::Result {
2978 write!(w, "<pre class='rust static'>")?;
2979 render_attributes(w, it)?;
2980 write!(w, "{vis}static {mutability}\
2981 {name}: {typ}</pre>",
2982 vis = VisSpace(&it.visibility),
2983 mutability = MutableSpace(s.mutability),
2984 name = it.name.as_ref().unwrap(),
2989 fn item_function(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2990 f: &clean::Function) -> fmt::Result {
2991 let header_len = format!(
2992 "{}{}{}{}{:#}fn {}{:#}",
2993 VisSpace(&it.visibility),
2994 ConstnessSpace(f.header.constness),
2995 UnsafetySpace(f.header.unsafety),
2996 AsyncSpace(f.header.asyncness),
2997 AbiSpace(f.header.abi),
2998 it.name.as_ref().unwrap(),
3001 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
3002 render_attributes(w, it)?;
3004 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
3005 {name}{generics}{decl}{where_clause}</pre>",
3006 vis = VisSpace(&it.visibility),
3007 constness = ConstnessSpace(f.header.constness),
3008 unsafety = UnsafetySpace(f.header.unsafety),
3009 asyncness = AsyncSpace(f.header.asyncness),
3010 abi = AbiSpace(f.header.abi),
3011 name = it.name.as_ref().unwrap(),
3012 generics = f.generics,
3013 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
3018 asyncness: f.header.asyncness,
3023 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter<'_>,
3024 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
3025 // If there's already another implementor that has the same abbridged name, use the
3026 // full path, for example in `std::iter::ExactSizeIterator`
3027 let use_absolute = match implementor.inner_impl().for_ {
3028 clean::ResolvedPath { ref path, is_generic: false, .. } |
3029 clean::BorrowedRef {
3030 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3032 } => implementor_dups[path.last_name()].1,
3035 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3036 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
3040 fn render_impls(cx: &Context, w: &mut fmt::Formatter<'_>,
3042 containing_item: &clean::Item) -> fmt::Result {
3044 let did = i.trait_did().unwrap();
3045 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3046 render_impl(w, cx, i, assoc_link,
3047 RenderMode::Normal, containing_item.stable_since(), true, None)?;
3052 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3053 let mut bounds = String::new();
3054 if !t_bounds.is_empty() {
3056 bounds.push_str(": ");
3058 for (i, p) in t_bounds.iter().enumerate() {
3060 bounds.push_str(" + ");
3062 bounds.push_str(&(*p).to_string());
3068 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3069 let lhs = format!("{}", lhs.inner_impl());
3070 let rhs = format!("{}", rhs.inner_impl());
3072 // lhs and rhs are formatted as HTML, which may be unnecessary
3073 name_key(&lhs).cmp(&name_key(&rhs))
3077 w: &mut fmt::Formatter<'_>,
3082 let bounds = bounds(&t.bounds, false);
3083 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3084 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3085 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3086 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3088 // Output the trait definition
3089 wrap_into_docblock(w, |w| {
3090 write!(w, "<pre class='rust trait'>")?;
3091 render_attributes(w, it)?;
3092 write!(w, "{}{}{}trait {}{}{}",
3093 VisSpace(&it.visibility),
3094 UnsafetySpace(t.unsafety),
3095 if t.is_auto { "auto " } else { "" },
3096 it.name.as_ref().unwrap(),
3100 if !t.generics.where_predicates.is_empty() {
3101 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3106 if t.items.is_empty() {
3107 write!(w, "{{ }}")?;
3109 // FIXME: we should be using a derived_id for the Anchors here
3113 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3116 if !types.is_empty() && !consts.is_empty() {
3121 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3124 if !consts.is_empty() && !required.is_empty() {
3127 for (pos, m) in required.iter().enumerate() {
3129 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3132 if pos < required.len() - 1 {
3133 write!(w, "<div class='item-spacer'></div>")?;
3136 if !required.is_empty() && !provided.is_empty() {
3139 for (pos, m) in provided.iter().enumerate() {
3141 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3143 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3144 write!(w, ",\n {{ ... }}\n")?;
3147 write!(w, " {{ ... }}\n")?;
3150 if pos < provided.len() - 1 {
3151 write!(w, "<div class='item-spacer'></div>")?;
3159 // Trait documentation
3160 document(w, cx, it)?;
3162 fn write_small_section_header(
3163 w: &mut fmt::Formatter<'_>,
3166 extra_content: &str,
3169 <h2 id='{0}' class='small-section-header'>\
3170 {1}<a href='#{0}' class='anchor'></a>\
3171 </h2>{2}", id, title, extra_content)
3174 fn write_loading_content(w: &mut fmt::Formatter<'_>, extra_content: &str) -> fmt::Result {
3175 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3178 fn trait_item(w: &mut fmt::Formatter<'_>, cx: &Context, m: &clean::Item, t: &clean::Item)
3180 let name = m.name.as_ref().unwrap();
3181 let item_type = m.type_();
3182 let id = cx.derive_id(format!("{}.{}", item_type, name));
3183 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3184 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3185 extra = render_spotlight_traits(m)?,
3188 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3189 write!(w, "</code>")?;
3190 render_stability_since(w, m, t)?;
3191 write!(w, "</h3>")?;
3192 document(w, cx, m)?;
3196 if !types.is_empty() {
3197 write_small_section_header(w, "associated-types", "Associated Types",
3198 "<div class='methods'>")?;
3200 trait_item(w, cx, *t, it)?;
3202 write_loading_content(w, "</div>")?;
3205 if !consts.is_empty() {
3206 write_small_section_header(w, "associated-const", "Associated Constants",
3207 "<div class='methods'>")?;
3209 trait_item(w, cx, *t, it)?;
3211 write_loading_content(w, "</div>")?;
3214 // Output the documentation for each function individually
3215 if !required.is_empty() {
3216 write_small_section_header(w, "required-methods", "Required methods",
3217 "<div class='methods'>")?;
3218 for m in &required {
3219 trait_item(w, cx, *m, it)?;
3221 write_loading_content(w, "</div>")?;
3223 if !provided.is_empty() {
3224 write_small_section_header(w, "provided-methods", "Provided methods",
3225 "<div class='methods'>")?;
3226 for m in &provided {
3227 trait_item(w, cx, *m, it)?;
3229 write_loading_content(w, "</div>")?;
3232 // If there are methods directly on this trait object, render them here.
3233 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3235 let cache = cache();
3237 let mut synthetic_types = Vec::new();
3239 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3240 // The DefId is for the first Type found with that name. The bool is
3241 // if any Types with the same name but different DefId have been found.
3242 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3243 for implementor in implementors {
3244 match implementor.inner_impl().for_ {
3245 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3246 clean::BorrowedRef {
3247 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3250 let &mut (prev_did, ref mut has_duplicates) =
3251 implementor_dups.entry(path.last_name()).or_insert((did, false));
3252 if prev_did != did {
3253 *has_duplicates = true;
3260 let (local, foreign) = implementors.iter()
3261 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3262 .map_or(true, |d| cache.paths.contains_key(&d)));
3265 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3266 .partition(|i| i.inner_impl().synthetic);
3268 synthetic.sort_by(compare_impl);
3269 concrete.sort_by(compare_impl);
3271 if !foreign.is_empty() {
3272 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3274 for implementor in foreign {
3275 let assoc_link = AssocItemLink::GotoSource(
3276 implementor.impl_item.def_id,
3277 &implementor.inner_impl().provided_trait_methods
3279 render_impl(w, cx, &implementor, assoc_link,
3280 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3283 write_loading_content(w, "")?;
3286 write_small_section_header(w, "implementors", "Implementors",
3287 "<div class='item-list' id='implementors-list'>")?;
3288 for implementor in concrete {
3289 render_implementor(cx, implementor, w, &implementor_dups)?;
3291 write_loading_content(w, "</div>")?;
3294 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3295 "<div class='item-list' id='synthetic-implementors-list'>")?;
3296 for implementor in synthetic {
3297 synthetic_types.extend(
3298 collect_paths_for_type(implementor.inner_impl().for_.clone())
3300 render_implementor(cx, implementor, w, &implementor_dups)?;
3302 write_loading_content(w, "</div>")?;
3305 // even without any implementations to write in, we still want the heading and list, so the
3306 // implementors javascript file pulled in below has somewhere to write the impls into
3307 write_small_section_header(w, "implementors", "Implementors",
3308 "<div class='item-list' id='implementors-list'>")?;
3309 write_loading_content(w, "</div>")?;
3312 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3313 "<div class='item-list' id='synthetic-implementors-list'>")?;
3314 write_loading_content(w, "</div>")?;
3317 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3318 as_json(&synthetic_types))?;
3320 write!(w, r#"<script type="text/javascript" async
3321 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3323 root_path = vec![".."; cx.current.len()].join("/"),
3324 path = if it.def_id.is_local() {
3325 cx.current.join("/")
3327 let (ref path, _) = cache.external_paths[&it.def_id];
3328 path[..path.len() - 1].join("/")
3330 ty = it.type_().css_class(),
3331 name = *it.name.as_ref().unwrap())?;
3335 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
3336 use crate::html::item_type::ItemType::*;
3338 let name = it.name.as_ref().unwrap();
3339 let ty = match it.type_() {
3340 Typedef | AssociatedType => AssociatedType,
3344 let anchor = format!("#{}.{}", ty, name);
3346 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3347 AssocItemLink::Anchor(None) => anchor,
3348 AssocItemLink::GotoSource(did, _) => {
3349 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3354 fn assoc_const(w: &mut fmt::Formatter<'_>,
3357 _default: Option<&String>,
3358 link: AssocItemLink<'_>) -> fmt::Result {
3359 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3360 VisSpace(&it.visibility),
3361 naive_assoc_href(it, link),
3362 it.name.as_ref().unwrap(),
3367 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3368 bounds: &[clean::GenericBound],
3369 default: Option<&clean::Type>,
3370 link: AssocItemLink<'_>) -> fmt::Result {
3371 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3372 naive_assoc_href(it, link),
3373 it.name.as_ref().unwrap())?;
3374 if !bounds.is_empty() {
3375 write!(w, ": {}", GenericBounds(bounds))?
3377 if let Some(default) = default {
3378 write!(w, " = {}", default)?;
3383 fn render_stability_since_raw<'a, T: fmt::Write>(
3385 ver: Option<&'a str>,
3386 containing_ver: Option<&'a str>,
3388 if let Some(v) = ver {
3389 if containing_ver != ver && v.len() > 0 {
3390 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3396 fn render_stability_since(w: &mut fmt::Formatter<'_>,
3398 containing_item: &clean::Item) -> fmt::Result {
3399 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3402 fn render_assoc_item(w: &mut fmt::Formatter<'_>,
3404 link: AssocItemLink<'_>,
3405 parent: ItemType) -> fmt::Result {
3406 fn method(w: &mut fmt::Formatter<'_>,
3408 header: hir::FnHeader,
3409 g: &clean::Generics,
3411 link: AssocItemLink<'_>,
3414 let name = meth.name.as_ref().unwrap();
3415 let anchor = format!("#{}.{}", meth.type_(), name);
3416 let href = match link {
3417 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3418 AssocItemLink::Anchor(None) => anchor,
3419 AssocItemLink::GotoSource(did, provided_methods) => {
3420 // We're creating a link from an impl-item to the corresponding
3421 // trait-item and need to map the anchored type accordingly.
3422 let ty = if provided_methods.contains(name) {
3428 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3431 let mut header_len = format!(
3432 "{}{}{}{}{}{:#}fn {}{:#}",
3433 VisSpace(&meth.visibility),
3434 ConstnessSpace(header.constness),
3435 UnsafetySpace(header.unsafety),
3436 AsyncSpace(header.asyncness),
3437 DefaultSpace(meth.is_default()),
3438 AbiSpace(header.abi),
3442 let (indent, end_newline) = if parent == ItemType::Trait {
3448 render_attributes(w, meth)?;
3449 write!(w, "{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3450 {generics}{decl}{where_clause}",
3451 VisSpace(&meth.visibility),
3452 ConstnessSpace(header.constness),
3453 UnsafetySpace(header.unsafety),
3454 AsyncSpace(header.asyncness),
3455 DefaultSpace(meth.is_default()),
3456 AbiSpace(header.abi),
3464 asyncness: header.asyncness,
3466 where_clause = WhereClause {
3473 clean::StrippedItem(..) => Ok(()),
3474 clean::TyMethodItem(ref m) => {
3475 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3477 clean::MethodItem(ref m) => {
3478 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3480 clean::AssociatedConstItem(ref ty, ref default) => {
3481 assoc_const(w, item, ty, default.as_ref(), link)
3483 clean::AssociatedTypeItem(ref bounds, ref default) => {
3484 assoc_type(w, item, bounds, default.as_ref(), link)
3486 _ => panic!("render_assoc_item called on non-associated-item")
3490 fn item_struct(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3491 s: &clean::Struct) -> fmt::Result {
3492 wrap_into_docblock(w, |w| {
3493 write!(w, "<pre class='rust struct'>")?;
3494 render_attributes(w, it)?;
3505 document(w, cx, it)?;
3506 let mut fields = s.fields.iter().filter_map(|f| {
3508 clean::StructFieldItem(ref ty) => Some((f, ty)),
3512 if let doctree::Plain = s.struct_type {
3513 if fields.peek().is_some() {
3514 write!(w, "<h2 id='fields' class='fields small-section-header'>
3515 Fields{}<a href='#fields' class='anchor'></a></h2>",
3516 document_non_exhaustive_header(it))?;
3517 document_non_exhaustive(w, it)?;
3518 for (field, ty) in fields {
3519 let id = cx.derive_id(format!("{}.{}",
3520 ItemType::StructField,
3521 field.name.as_ref().unwrap()));
3522 let ns_id = cx.derive_id(format!("{}.{}",
3523 field.name.as_ref().unwrap(),
3524 ItemType::StructField.name_space()));
3525 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3526 <a href=\"#{id}\" class=\"anchor field\"></a>\
3527 <code id=\"{ns_id}\">{name}: {ty}</code>\
3529 item_type = ItemType::StructField,
3532 name = field.name.as_ref().unwrap(),
3534 document(w, cx, field)?;
3538 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3541 fn item_union(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3542 s: &clean::Union) -> fmt::Result {
3543 wrap_into_docblock(w, |w| {
3544 write!(w, "<pre class='rust union'>")?;
3545 render_attributes(w, it)?;
3555 document(w, cx, it)?;
3556 let mut fields = s.fields.iter().filter_map(|f| {
3558 clean::StructFieldItem(ref ty) => Some((f, ty)),
3562 if fields.peek().is_some() {
3563 write!(w, "<h2 id='fields' class='fields small-section-header'>
3564 Fields<a href='#fields' class='anchor'></a></h2>")?;
3565 for (field, ty) in fields {
3566 let name = field.name.as_ref().expect("union field name");
3567 let id = format!("{}.{}", ItemType::StructField, name);
3568 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3569 <a href=\"#{id}\" class=\"anchor field\"></a>\
3570 <code>{name}: {ty}</code>\
3574 shortty = ItemType::StructField,
3576 if let Some(stability_class) = field.stability_class() {
3577 write!(w, "<span class='stab {stab}'></span>",
3578 stab = stability_class)?;
3580 document(w, cx, field)?;
3583 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3586 fn item_enum(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3587 e: &clean::Enum) -> fmt::Result {
3588 wrap_into_docblock(w, |w| {
3589 write!(w, "<pre class='rust enum'>")?;
3590 render_attributes(w, it)?;
3591 write!(w, "{}enum {}{}{}",
3592 VisSpace(&it.visibility),
3593 it.name.as_ref().unwrap(),
3595 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3596 if e.variants.is_empty() && !e.variants_stripped {
3597 write!(w, " {{}}")?;
3599 write!(w, " {{\n")?;
3600 for v in &e.variants {
3602 let name = v.name.as_ref().unwrap();
3604 clean::VariantItem(ref var) => {
3606 clean::VariantKind::CLike => write!(w, "{}", name)?,
3607 clean::VariantKind::Tuple(ref tys) => {
3608 write!(w, "{}(", name)?;
3609 for (i, ty) in tys.iter().enumerate() {
3611 write!(w, ", ")?
3613 write!(w, "{}", *ty)?;
3617 clean::VariantKind::Struct(ref s) => {
3633 if e.variants_stripped {
3634 write!(w, " // some variants omitted\n")?;
3641 document(w, cx, it)?;
3642 if !e.variants.is_empty() {
3643 write!(w, "<h2 id='variants' class='variants small-section-header'>
3644 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3645 document_non_exhaustive_header(it))?;
3646 document_non_exhaustive(w, it)?;
3647 for variant in &e.variants {
3648 let id = cx.derive_id(format!("{}.{}",
3650 variant.name.as_ref().unwrap()));
3651 let ns_id = cx.derive_id(format!("{}.{}",
3652 variant.name.as_ref().unwrap(),
3653 ItemType::Variant.name_space()));
3654 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3655 <a href=\"#{id}\" class=\"anchor field\"></a>\
3656 <code id='{ns_id}'>{name}",
3659 name = variant.name.as_ref().unwrap())?;
3660 if let clean::VariantItem(ref var) = variant.inner {
3661 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3663 for (i, ty) in tys.iter().enumerate() {
3665 write!(w, ", ")?;
3667 write!(w, "{}", *ty)?;
3672 write!(w, "</code></span>")?;
3673 document(w, cx, variant)?;
3675 use crate::clean::{Variant, VariantKind};
3676 if let clean::VariantItem(Variant {
3677 kind: VariantKind::Struct(ref s)
3678 }) = variant.inner {
3679 let variant_id = cx.derive_id(format!("{}.{}.fields",
3681 variant.name.as_ref().unwrap()));
3682 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3684 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3685 name = variant.name.as_ref().unwrap())?;
3686 for field in &s.fields {
3687 use crate::clean::StructFieldItem;
3688 if let StructFieldItem(ref ty) = field.inner {
3689 let id = cx.derive_id(format!("variant.{}.field.{}",
3690 variant.name.as_ref().unwrap(),
3691 field.name.as_ref().unwrap()));
3692 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3693 variant.name.as_ref().unwrap(),
3694 ItemType::Variant.name_space(),
3695 field.name.as_ref().unwrap(),
3696 ItemType::StructField.name_space()));
3697 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3698 <a href=\"#{id}\" class=\"anchor field\"></a>\
3699 <code id='{ns_id}'>{f}: {t}\
3703 f = field.name.as_ref().unwrap(),
3705 document(w, cx, field)?;
3708 write!(w, "</div></span>")?;
3710 render_stability_since(w, variant, it)?;
3713 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3717 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3718 let path = attr.path.to_string();
3722 } else if let Some(v) = attr.value_str() {
3723 Some(format!("{} = {:?}", path, v.as_str()))
3724 } else if let Some(values) = attr.meta_item_list() {
3725 let display: Vec<_> = values.iter().filter_map(|attr| {
3726 attr.meta_item().and_then(|mi| render_attribute(mi))
3729 if display.len() > 0 {
3730 Some(format!("{}({})", path, display.join(", ")))
3739 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3746 "unsafe_destructor_blind_to_params",
3750 fn render_attributes(w: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
3751 let mut attrs = String::new();
3753 for attr in &it.attrs.other_attrs {
3754 if !attr.ident_str().map_or(false, |name| ATTRIBUTE_WHITELIST.contains(&name)) {
3757 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3758 attrs.push_str(&format!("#[{}]\n", s));
3761 if attrs.len() > 0 {
3762 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3767 fn render_struct(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3768 g: Option<&clean::Generics>,
3769 ty: doctree::StructType,
3770 fields: &[clean::Item],
3772 structhead: bool) -> fmt::Result {
3774 VisSpace(&it.visibility),
3775 if structhead {"struct "} else {""},
3776 it.name.as_ref().unwrap())?;
3777 if let Some(g) = g {
3782 if let Some(g) = g {
3783 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3785 let mut has_visible_fields = false;
3787 for field in fields {
3788 if let clean::StructFieldItem(ref ty) = field.inner {
3789 write!(w, "\n{} {}{}: {},",
3791 VisSpace(&field.visibility),
3792 field.name.as_ref().unwrap(),
3794 has_visible_fields = true;
3798 if has_visible_fields {
3799 if it.has_stripped_fields().unwrap() {
3800 write!(w, "\n{} // some fields omitted", tab)?;
3802 write!(w, "\n{}", tab)?;
3803 } else if it.has_stripped_fields().unwrap() {
3804 // If there are no visible fields we can just display
3805 // `{ /* fields omitted */ }` to save space.
3806 write!(w, " /* fields omitted */ ")?;
3812 for (i, field) in fields.iter().enumerate() {
3817 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3820 clean::StructFieldItem(ref ty) => {
3821 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3827 if let Some(g) = g {
3828 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3833 // Needed for PhantomData.
3834 if let Some(g) = g {
3835 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3843 fn render_union(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3844 g: Option<&clean::Generics>,
3845 fields: &[clean::Item],
3847 structhead: bool) -> fmt::Result {
3849 VisSpace(&it.visibility),
3850 if structhead {"union "} else {""},
3851 it.name.as_ref().unwrap())?;
3852 if let Some(g) = g {
3853 write!(w, "{}", g)?;
3854 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3857 write!(w, " {{\n{}", tab)?;
3858 for field in fields {
3859 if let clean::StructFieldItem(ref ty) = field.inner {
3860 write!(w, " {}{}: {},\n{}",
3861 VisSpace(&field.visibility),
3862 field.name.as_ref().unwrap(),
3868 if it.has_stripped_fields().unwrap() {
3869 write!(w, " // some fields omitted\n{}", tab)?;
3875 #[derive(Copy, Clone)]
3876 enum AssocItemLink<'a> {
3877 Anchor(Option<&'a str>),
3878 GotoSource(DefId, &'a FxHashSet<String>),
3881 impl<'a> AssocItemLink<'a> {
3882 fn anchor(&self, id: &'a String) -> Self {
3884 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3885 ref other => *other,
3890 enum AssocItemRender<'a> {
3892 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3895 #[derive(Copy, Clone, PartialEq)]
3898 ForDeref { mut_: bool },
3901 fn render_assoc_items(w: &mut fmt::Formatter<'_>,
3903 containing_item: &clean::Item,
3905 what: AssocItemRender<'_>) -> fmt::Result {
3907 let v = match c.impls.get(&it) {
3909 None => return Ok(()),
3911 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3912 i.inner_impl().trait_.is_none()
3914 if !non_trait.is_empty() {
3915 let render_mode = match what {
3916 AssocItemRender::All => {
3918 <h2 id='methods' class='small-section-header'>\
3919 Methods<a href='#methods' class='anchor'></a>\
3924 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3926 <h2 id='deref-methods' class='small-section-header'>\
3927 Methods from {}<Target = {}>\
3928 <a href='#deref-methods' class='anchor'></a>\
3931 RenderMode::ForDeref { mut_: deref_mut_ }
3934 for i in &non_trait {
3935 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3936 containing_item.stable_since(), true, None)?;
3939 if let AssocItemRender::DerefFor { .. } = what {
3942 if !traits.is_empty() {
3943 let deref_impl = traits.iter().find(|t| {
3944 t.inner_impl().trait_.def_id() == c.deref_trait_did
3946 if let Some(impl_) = deref_impl {
3947 let has_deref_mut = traits.iter().find(|t| {
3948 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3950 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3953 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3955 .partition(|t| t.inner_impl().synthetic);
3956 let (blanket_impl, concrete) = concrete
3958 .partition(|t| t.inner_impl().blanket_impl.is_some());
3960 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3962 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3963 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3964 render_impls(self.0, fmt, &self.1, self.2)
3968 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3969 if !impls.is_empty() {
3971 <h2 id='implementations' class='small-section-header'>\
3972 Trait Implementations<a href='#implementations' class='anchor'></a>\
3974 <div id='implementations-list'>{}</div>", impls)?;
3977 if !synthetic.is_empty() {
3979 <h2 id='synthetic-implementations' class='small-section-header'>\
3980 Auto Trait Implementations\
3981 <a href='#synthetic-implementations' class='anchor'></a>\
3983 <div id='synthetic-implementations-list'>\
3985 render_impls(cx, w, &synthetic, containing_item)?;
3986 write!(w, "</div>")?;
3989 if !blanket_impl.is_empty() {
3991 <h2 id='blanket-implementations' class='small-section-header'>\
3992 Blanket Implementations\
3993 <a href='#blanket-implementations' class='anchor'></a>\
3995 <div id='blanket-implementations-list'>\
3997 render_impls(cx, w, &blanket_impl, containing_item)?;
3998 write!(w, "</div>")?;
4004 fn render_deref_methods(w: &mut fmt::Formatter<'_>, cx: &Context, impl_: &Impl,
4005 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
4006 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
4007 let target = impl_.inner_impl().items.iter().filter_map(|item| {
4009 clean::TypedefItem(ref t, true) => Some(&t.type_),
4012 }).next().expect("Expected associated type binding");
4013 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
4014 deref_mut_: deref_mut };
4015 if let Some(did) = target.def_id() {
4016 render_assoc_items(w, cx, container_item, did, what)
4018 if let Some(prim) = target.primitive_type() {
4019 if let Some(&did) = cache().primitive_locations.get(&prim) {
4020 render_assoc_items(w, cx, container_item, did, what)?;
4027 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
4028 let self_type_opt = match item.inner {
4029 clean::MethodItem(ref method) => method.decl.self_type(),
4030 clean::TyMethodItem(ref method) => method.decl.self_type(),
4034 if let Some(self_ty) = self_type_opt {
4035 let (by_mut_ref, by_box, by_value) = match self_ty {
4036 SelfTy::SelfBorrowed(_, mutability) |
4037 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4038 (mutability == Mutability::Mutable, false, false)
4040 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4041 (false, Some(did) == cache().owned_box_did, false)
4043 SelfTy::SelfValue => (false, false, true),
4044 _ => (false, false, false),
4047 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4053 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4054 let mut out = String::new();
4057 clean::FunctionItem(clean::Function { ref decl, .. }) |
4058 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4059 clean::MethodItem(clean::Method { ref decl, .. }) |
4060 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4061 out = spotlight_decl(decl)?;
4069 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4070 let mut out = String::new();
4071 let mut trait_ = String::new();
4073 if let Some(did) = decl.output.def_id() {
4075 if let Some(impls) = c.impls.get(&did) {
4077 let impl_ = i.inner_impl();
4078 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4081 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4082 <code class=\"content\">",
4084 trait_.push_str(&impl_.for_.to_string());
4087 //use the "where" class here to make it small
4088 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4089 let t_did = impl_.trait_.def_id().unwrap();
4090 for it in &impl_.items {
4091 if let clean::TypedefItem(ref tydef, _) = it.inner {
4092 out.push_str("<span class=\"where fmt-newline\"> ");
4093 assoc_type(&mut out, it, &[],
4095 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4096 out.push_str(";</span>");
4104 if !out.is_empty() {
4105 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4106 <span class='tooltiptext'>Important traits for {}</span></div>\
4107 <div class=\"content hidden\">",
4109 out.push_str("</code></div></div>");
4115 fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
4116 render_mode: RenderMode, outer_version: Option<&str>,
4117 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4118 if render_mode == RenderMode::Normal {
4119 let id = cx.derive_id(match i.inner_impl().trait_ {
4120 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4121 None => "impl".to_string(),
4123 if let Some(use_absolute) = use_absolute {
4124 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4125 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4127 for it in &i.inner_impl().items {
4128 if let clean::TypedefItem(ref tydef, _) = it.inner {
4129 write!(w, "<span class=\"where fmt-newline\"> ")?;
4130 assoc_type(w, it, &vec![], Some(&tydef.type_),
4131 AssocItemLink::Anchor(None))?;
4132 write!(w, ";</span>")?;
4136 write!(w, "</code>")?;
4138 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4142 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4143 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4144 render_stability_since_raw(w, since, outer_version)?;
4145 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4146 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4147 l, "goto source code")?;
4149 write!(w, "</h3>")?;
4150 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4151 let mut ids = cx.id_map.borrow_mut();
4152 write!(w, "<div class='docblock'>{}</div>",
4153 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4157 fn doc_impl_item(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
4158 link: AssocItemLink<'_>, render_mode: RenderMode,
4159 is_default_item: bool, outer_version: Option<&str>,
4160 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4161 let item_type = item.type_();
4162 let name = item.name.as_ref().unwrap();
4164 let render_method_item: bool = match render_mode {
4165 RenderMode::Normal => true,
4166 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4169 let (is_hidden, extra_class) = if trait_.is_none() ||
4170 item.doc_value().is_some() ||
4171 item.inner.is_associated() {
4177 clean::MethodItem(clean::Method { ref decl, .. }) |
4178 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4179 // Only render when the method is not static or we allow static methods
4180 if render_method_item {
4181 let id = cx.derive_id(format!("{}.{}", item_type, name));
4182 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4183 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4184 write!(w, "{}", spotlight_decl(decl)?)?;
4185 write!(w, "<code id='{}'>", ns_id)?;
4186 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4187 write!(w, "</code>")?;
4188 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4189 if let Some(l) = (Item { cx, item }).src_href() {
4190 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4191 l, "goto source code")?;
4193 write!(w, "</h4>")?;
4196 clean::TypedefItem(ref tydef, _) => {
4197 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4198 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4199 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4200 write!(w, "<code id='{}'>", ns_id)?;
4201 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4202 write!(w, "</code></h4>")?;
4204 clean::AssociatedConstItem(ref ty, ref default) => {
4205 let id = cx.derive_id(format!("{}.{}", item_type, name));
4206 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4207 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4208 write!(w, "<code id='{}'>", ns_id)?;
4209 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4210 write!(w, "</code>")?;
4211 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4212 if let Some(l) = (Item { cx, item }).src_href() {
4213 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4214 l, "goto source code")?;
4216 write!(w, "</h4>")?;
4218 clean::AssociatedTypeItem(ref bounds, ref default) => {
4219 let id = cx.derive_id(format!("{}.{}", item_type, name));
4220 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4221 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4222 write!(w, "<code id='{}'>", ns_id)?;
4223 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4224 write!(w, "</code></h4>")?;
4226 clean::StrippedItem(..) => return Ok(()),
4227 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4230 if render_method_item || render_mode == RenderMode::Normal {
4231 if !is_default_item {
4232 if let Some(t) = trait_ {
4233 // The trait item may have been stripped so we might not
4234 // find any documentation or stability for it.
4235 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4236 // We need the stability of the item from the trait
4237 // because impls can't have a stability.
4238 document_stability(w, cx, it, is_hidden)?;
4239 if item.doc_value().is_some() {
4240 document_full(w, item, cx, "", is_hidden)?;
4241 } else if show_def_docs {
4242 // In case the item isn't documented,
4243 // provide short documentation from the trait.
4244 document_short(w, cx, it, link, "", is_hidden)?;
4248 document_stability(w, cx, item, is_hidden)?;
4250 document_full(w, item, cx, "", is_hidden)?;
4254 document_stability(w, cx, item, is_hidden)?;
4256 document_short(w, cx, item, link, "", is_hidden)?;
4263 let traits = &cache().traits;
4264 let trait_ = i.trait_did().map(|did| &traits[&did]);
4266 write!(w, "<div class='impl-items'>")?;
4267 for trait_item in &i.inner_impl().items {
4268 doc_impl_item(w, cx, trait_item, link, render_mode,
4269 false, outer_version, trait_, show_def_docs)?;
4272 fn render_default_items(w: &mut fmt::Formatter<'_>,
4276 render_mode: RenderMode,
4277 outer_version: Option<&str>,
4278 show_def_docs: bool) -> fmt::Result {
4279 for trait_item in &t.items {
4280 let n = trait_item.name.clone();
4281 if i.items.iter().find(|m| m.name == n).is_some() {
4284 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4285 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4287 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4288 outer_version, None, show_def_docs)?;
4293 // If we've implemented a trait, then also emit documentation for all
4294 // default items which weren't overridden in the implementation block.
4295 if let Some(t) = trait_ {
4296 render_default_items(w, cx, t, &i.inner_impl(),
4297 render_mode, outer_version, show_def_docs)?;
4299 write!(w, "</div>")?;
4304 fn item_existential(
4305 w: &mut fmt::Formatter<'_>,
4308 t: &clean::Existential,
4310 write!(w, "<pre class='rust existential'>")?;
4311 render_attributes(w, it)?;
4312 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4313 it.name.as_ref().unwrap(),
4315 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4316 bounds = bounds(&t.bounds, false))?;
4318 document(w, cx, it)?;
4320 // Render any items associated directly to this alias, as otherwise they
4321 // won't be visible anywhere in the docs. It would be nice to also show
4322 // associated items from the aliased type (see discussion in #32077), but
4323 // we need #14072 to make sense of the generics.
4324 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4327 fn item_trait_alias(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4328 t: &clean::TraitAlias) -> fmt::Result {
4329 write!(w, "<pre class='rust trait-alias'>")?;
4330 render_attributes(w, it)?;
4331 write!(w, "trait {}{}{} = {};</pre>",
4332 it.name.as_ref().unwrap(),
4334 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4335 bounds(&t.bounds, true))?;
4337 document(w, cx, it)?;
4339 // Render any items associated directly to this alias, as otherwise they
4340 // won't be visible anywhere in the docs. It would be nice to also show
4341 // associated items from the aliased type (see discussion in #32077), but
4342 // we need #14072 to make sense of the generics.
4343 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4346 fn item_typedef(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4347 t: &clean::Typedef) -> fmt::Result {
4348 write!(w, "<pre class='rust typedef'>")?;
4349 render_attributes(w, it)?;
4350 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4351 it.name.as_ref().unwrap(),
4353 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4356 document(w, cx, it)?;
4358 // Render any items associated directly to this alias, as otherwise they
4359 // won't be visible anywhere in the docs. It would be nice to also show
4360 // associated items from the aliased type (see discussion in #32077), but
4361 // we need #14072 to make sense of the generics.
4362 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4365 fn item_foreign_type(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item) -> fmt::Result {
4366 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4367 render_attributes(w, it)?;
4370 " {}type {};\n}}</pre>",
4371 VisSpace(&it.visibility),
4372 it.name.as_ref().unwrap(),
4375 document(w, cx, it)?;
4377 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4380 impl<'a> fmt::Display for Sidebar<'a> {
4381 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4384 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4386 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4387 || it.is_enum() || it.is_mod() || it.is_typedef() {
4388 write!(fmt, "<p class='location'>{}{}</p>",
4390 clean::StructItem(..) => "Struct ",
4391 clean::TraitItem(..) => "Trait ",
4392 clean::PrimitiveItem(..) => "Primitive Type ",
4393 clean::UnionItem(..) => "Union ",
4394 clean::EnumItem(..) => "Enum ",
4395 clean::TypedefItem(..) => "Type Definition ",
4396 clean::ForeignTypeItem => "Foreign Type ",
4397 clean::ModuleItem(..) => if it.is_crate() {
4404 it.name.as_ref().unwrap())?;
4408 if let Some(ref version) = cache().crate_version {
4410 "<div class='block version'>\
4417 write!(fmt, "<div class=\"sidebar-elems\">")?;
4419 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4420 it.name.as_ref().expect("crates always have a name"))?;
4423 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4424 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4425 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4426 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4427 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4428 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4429 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4430 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4434 // The sidebar is designed to display sibling functions, modules and
4435 // other miscellaneous information. since there are lots of sibling
4436 // items (and that causes quadratic growth in large modules),
4437 // we refactor common parts into a shared JavaScript file per module.
4438 // still, we don't move everything into JS because we want to preserve
4439 // as much HTML as possible in order to allow non-JS-enabled browsers
4440 // to navigate the documentation (though slightly inefficiently).
4442 write!(fmt, "<p class='location'>")?;
4443 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4445 write!(fmt, "::<wbr>")?;
4447 write!(fmt, "<a href='{}index.html'>{}</a>",
4448 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4451 write!(fmt, "</p>")?;
4453 // Sidebar refers to the enclosing module, not this module.
4454 let relpath = if it.is_mod() { "../" } else { "" };
4456 "<script>window.sidebarCurrent = {{\
4461 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4462 ty = it.type_().css_class(),
4465 // There is no sidebar-items.js beyond the crate root path
4466 // FIXME maybe dynamic crate loading can be merged here
4468 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4471 // Closes sidebar-elems div.
4472 write!(fmt, "</div>")?;
4478 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4479 if used_links.insert(url.clone()) {
4483 while used_links.insert(format!("{}-{}", url, add)) == false {
4486 format!("{}-{}", url, add)
4492 used_links: &mut FxHashSet<String>,
4494 i.items.iter().filter_map(|item| {
4496 // Maybe check with clean::Visibility::Public as well?
4497 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4498 if !for_deref || should_render_item(item, false) {
4499 Some(format!("<a href=\"#{}\">{}</a>",
4500 get_next_url(used_links, format!("method.{}", name)),
4508 }).collect::<Vec<_>>()
4511 // The point is to url encode any potential character from a type with genericity.
4512 fn small_url_encode(s: &str) -> String {
4513 s.replace("<", "%3C")
4514 .replace(">", "%3E")
4515 .replace(" ", "%20")
4516 .replace("?", "%3F")
4517 .replace("'", "%27")
4518 .replace("&", "%26")
4519 .replace(",", "%2C")
4520 .replace(":", "%3A")
4521 .replace(";", "%3B")
4522 .replace("[", "%5B")
4523 .replace("]", "%5D")
4524 .replace("\"", "%22")
4527 fn sidebar_assoc_items(it: &clean::Item) -> String {
4528 let mut out = String::new();
4530 if let Some(v) = c.impls.get(&it.def_id) {
4531 let mut used_links = FxHashSet::default();
4534 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4535 let mut ret = v.iter()
4536 .filter(|i| i.inner_impl().trait_.is_none())
4537 .flat_map(move |i| get_methods(i.inner_impl(),
4539 &mut used_links_bor.borrow_mut()))
4540 .collect::<Vec<_>>();
4541 // We want links' order to be reproducible so we don't use unstable sort.
4543 if !ret.is_empty() {
4544 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4545 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4549 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4550 if let Some(impl_) = v.iter()
4551 .filter(|i| i.inner_impl().trait_.is_some())
4552 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4553 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4555 clean::TypedefItem(ref t, true) => Some(&t.type_),
4559 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4560 c.primitive_locations.get(&prim).cloned()
4561 })).and_then(|did| c.impls.get(&did));
4562 if let Some(impls) = inner_impl {
4563 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4564 out.push_str(&format!("Methods from {}<Target={}>",
4565 Escape(&format!("{:#}",
4566 impl_.inner_impl().trait_.as_ref().unwrap())),
4567 Escape(&format!("{:#}", target))));
4568 out.push_str("</a>");
4569 let mut ret = impls.iter()
4570 .filter(|i| i.inner_impl().trait_.is_none())
4571 .flat_map(|i| get_methods(i.inner_impl(),
4574 .collect::<Vec<_>>();
4575 // We want links' order to be reproducible so we don't use unstable sort.
4577 if !ret.is_empty() {
4578 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4584 let format_impls = |impls: Vec<&Impl>| {
4585 let mut links = FxHashSet::default();
4587 let mut ret = impls.iter()
4589 let is_negative_impl = is_negative_impl(i.inner_impl());
4590 if let Some(ref i) = i.inner_impl().trait_ {
4591 let i_display = format!("{:#}", i);
4592 let out = Escape(&i_display);
4593 let encoded = small_url_encode(&format!("{:#}", i));
4594 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4596 if is_negative_impl { "!" } else { "" },
4598 if links.insert(generated.clone()) {
4607 .collect::<Vec<String>>();
4612 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4614 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4615 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4617 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4619 let concrete_format = format_impls(concrete);
4620 let synthetic_format = format_impls(synthetic);
4621 let blanket_format = format_impls(blanket_impl);
4623 if !concrete_format.is_empty() {
4624 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4625 Trait Implementations</a>");
4626 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4629 if !synthetic_format.is_empty() {
4630 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4631 Auto Trait Implementations</a>");
4632 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4635 if !blanket_format.is_empty() {
4636 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4637 Blanket Implementations</a>");
4638 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4646 fn sidebar_struct(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4647 s: &clean::Struct) -> fmt::Result {
4648 let mut sidebar = String::new();
4649 let fields = get_struct_fields_name(&s.fields);
4651 if !fields.is_empty() {
4652 if let doctree::Plain = s.struct_type {
4653 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4654 <div class=\"sidebar-links\">{}</div>", fields));
4658 sidebar.push_str(&sidebar_assoc_items(it));
4660 if !sidebar.is_empty() {
4661 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4666 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4668 clean::ItemEnum::ImplItem(ref i) => {
4669 if let Some(ref trait_) = i.trait_ {
4670 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4679 fn is_negative_impl(i: &clean::Impl) -> bool {
4680 i.polarity == Some(clean::ImplPolarity::Negative)
4683 fn sidebar_trait(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4684 t: &clean::Trait) -> fmt::Result {
4685 let mut sidebar = String::new();
4691 Some(ref name) if m.is_associated_type() => {
4692 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4698 .collect::<String>();
4699 let consts = t.items
4703 Some(ref name) if m.is_associated_const() => {
4704 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4710 .collect::<String>();
4711 let mut required = t.items
4715 Some(ref name) if m.is_ty_method() => {
4716 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4722 .collect::<Vec<String>>();
4723 let mut provided = t.items
4727 Some(ref name) if m.is_method() => {
4728 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4733 .collect::<Vec<String>>();
4735 if !types.is_empty() {
4736 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4737 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4740 if !consts.is_empty() {
4741 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4742 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4745 if !required.is_empty() {
4747 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4748 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4749 required.join("")));
4751 if !provided.is_empty() {
4753 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4754 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4755 provided.join("")));
4760 if let Some(implementors) = c.implementors.get(&it.def_id) {
4761 let mut res = implementors.iter()
4762 .filter(|i| i.inner_impl().for_.def_id()
4763 .map_or(false, |d| !c.paths.contains_key(&d)))
4765 match extract_for_impl_name(&i.impl_item) {
4766 Some((ref name, ref url)) => {
4767 Some(format!("<a href=\"#impl-{}\">{}</a>",
4768 small_url_encode(url),
4774 .collect::<Vec<String>>();
4775 if !res.is_empty() {
4777 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4778 Implementations on Foreign Types</a><div \
4779 class=\"sidebar-links\">{}</div>",
4784 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4786 sidebar.push_str("<a class=\"sidebar-title\" \
4787 href=\"#synthetic-implementors\">Auto Implementors</a>");
4790 sidebar.push_str(&sidebar_assoc_items(it));
4792 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4795 fn sidebar_primitive(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4796 _p: &clean::PrimitiveType) -> fmt::Result {
4797 let sidebar = sidebar_assoc_items(it);
4799 if !sidebar.is_empty() {
4800 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4805 fn sidebar_typedef(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4806 _t: &clean::Typedef) -> fmt::Result {
4807 let sidebar = sidebar_assoc_items(it);
4809 if !sidebar.is_empty() {
4810 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4815 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4817 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4822 .filter_map(|f| match f.name {
4823 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4824 {name}</a>", name=name)),
4830 fn sidebar_union(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4831 u: &clean::Union) -> fmt::Result {
4832 let mut sidebar = String::new();
4833 let fields = get_struct_fields_name(&u.fields);
4835 if !fields.is_empty() {
4836 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4837 <div class=\"sidebar-links\">{}</div>", fields));
4840 sidebar.push_str(&sidebar_assoc_items(it));
4842 if !sidebar.is_empty() {
4843 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4848 fn sidebar_enum(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4849 e: &clean::Enum) -> fmt::Result {
4850 let mut sidebar = String::new();
4852 let variants = e.variants.iter()
4853 .filter_map(|v| match v.name {
4854 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4855 </a>", name = name)),
4858 .collect::<String>();
4859 if !variants.is_empty() {
4860 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4861 <div class=\"sidebar-links\">{}</div>", variants));
4864 sidebar.push_str(&sidebar_assoc_items(it));
4866 if !sidebar.is_empty() {
4867 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4872 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4874 ItemType::ExternCrate |
4875 ItemType::Import => ("reexports", "Re-exports"),
4876 ItemType::Module => ("modules", "Modules"),
4877 ItemType::Struct => ("structs", "Structs"),
4878 ItemType::Union => ("unions", "Unions"),
4879 ItemType::Enum => ("enums", "Enums"),
4880 ItemType::Function => ("functions", "Functions"),
4881 ItemType::Typedef => ("types", "Type Definitions"),
4882 ItemType::Static => ("statics", "Statics"),
4883 ItemType::Constant => ("constants", "Constants"),
4884 ItemType::Trait => ("traits", "Traits"),
4885 ItemType::Impl => ("impls", "Implementations"),
4886 ItemType::TyMethod => ("tymethods", "Type Methods"),
4887 ItemType::Method => ("methods", "Methods"),
4888 ItemType::StructField => ("fields", "Struct Fields"),
4889 ItemType::Variant => ("variants", "Variants"),
4890 ItemType::Macro => ("macros", "Macros"),
4891 ItemType::Primitive => ("primitives", "Primitive Types"),
4892 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4893 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4894 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4895 ItemType::Keyword => ("keywords", "Keywords"),
4896 ItemType::Existential => ("existentials", "Existentials"),
4897 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4898 ItemType::ProcDerive => ("derives", "Derive Macros"),
4899 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4903 fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item,
4904 items: &[clean::Item]) -> fmt::Result {
4905 let mut sidebar = String::new();
4907 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4908 it.type_() == ItemType::Import) {
4909 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4911 name = "Re-exports"));
4914 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4915 // to print its headings
4916 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4917 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4918 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4919 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4920 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4921 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4922 let (short, name) = item_ty_to_strs(&myty);
4923 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4929 if !sidebar.is_empty() {
4930 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4935 fn sidebar_foreign_type(fmt: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
4936 let sidebar = sidebar_assoc_items(it);
4937 if !sidebar.is_empty() {
4938 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4943 impl<'a> fmt::Display for Source<'a> {
4944 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4945 let Source(s) = *self;
4946 let lines = s.lines().count();
4948 let mut tmp = lines;
4953 write!(fmt, "<pre class=\"line-numbers\">")?;
4954 for i in 1..=lines {
4955 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4957 write!(fmt, "</pre>")?;
4959 highlight::render_with_highlighting(s, None, None, None))?;
4964 fn item_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4965 t: &clean::Macro) -> fmt::Result {
4966 wrap_into_docblock(w, |w| {
4967 w.write_str(&highlight::render_with_highlighting(&t.source,
4975 fn item_proc_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4978 let name = it.name.as_ref().expect("proc-macros always have names");
4980 MacroKind::Bang => {
4981 write!(w, "<pre class='rust macro'>")?;
4982 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4983 write!(w, "</pre>")?;
4985 MacroKind::Attr => {
4986 write!(w, "<pre class='rust attr'>")?;
4987 write!(w, "#[{}]", name)?;
4988 write!(w, "</pre>")?;
4990 MacroKind::Derive => {
4991 write!(w, "<pre class='rust derive'>")?;
4992 write!(w, "#[derive({})]", name)?;
4993 if !m.helpers.is_empty() {
4994 writeln!(w, "\n{{")?;
4995 writeln!(w, " // Attributes available to this derive:")?;
4996 for attr in &m.helpers {
4997 writeln!(w, " #[{}]", attr)?;
5001 write!(w, "</pre>")?;
5008 fn item_primitive(w: &mut fmt::Formatter<'_>, cx: &Context,
5010 _p: &clean::PrimitiveType) -> fmt::Result {
5011 document(w, cx, it)?;
5012 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
5015 fn item_keyword(w: &mut fmt::Formatter<'_>, cx: &Context,
5017 _p: &str) -> fmt::Result {
5021 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
5023 fn make_item_keywords(it: &clean::Item) -> String {
5024 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
5027 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
5028 let decl = match item.inner {
5029 clean::FunctionItem(ref f) => &f.decl,
5030 clean::MethodItem(ref m) => &m.decl,
5031 clean::TyMethodItem(ref m) => &m.decl,
5035 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
5036 let output = match decl.output {
5037 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
5041 Some(IndexItemFunctionType { inputs: inputs, output: output })
5044 fn get_index_type(clean_type: &clean::Type) -> Type {
5046 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5047 generics: get_generics(clean_type),
5052 /// Returns a list of all paths used in the type.
5053 /// This is used to help deduplicate imported impls
5054 /// for reexported types. If any of the contained
5055 /// types are re-exported, we don't use the corresponding
5056 /// entry from the js file, as inlining will have already
5057 /// picked up the impl
5058 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5059 let mut out = Vec::new();
5060 let mut visited = FxHashSet::default();
5061 let mut work = VecDeque::new();
5062 let cache = cache();
5064 work.push_back(first_ty);
5066 while let Some(ty) = work.pop_front() {
5067 if !visited.insert(ty.clone()) {
5072 clean::Type::ResolvedPath { did, .. } => {
5073 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5074 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5078 out.push(path.join("::"));
5084 clean::Type::Tuple(tys) => {
5085 work.extend(tys.into_iter());
5087 clean::Type::Slice(ty) => {
5088 work.push_back(*ty);
5090 clean::Type::Array(ty, _) => {
5091 work.push_back(*ty);
5093 clean::Type::Unique(ty) => {
5094 work.push_back(*ty);
5096 clean::Type::RawPointer(_, ty) => {
5097 work.push_back(*ty);
5099 clean::Type::BorrowedRef { type_, .. } => {
5100 work.push_back(*type_);
5102 clean::Type::QPath { self_type, trait_, .. } => {
5103 work.push_back(*self_type);
5104 work.push_back(*trait_);
5112 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5114 clean::ResolvedPath { ref path, .. } => {
5115 let segments = &path.segments;
5116 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5117 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5118 clean_type, accept_generic
5120 Some(path_segment.name.clone())
5122 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5123 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5124 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5125 // FIXME: add all from clean::Type.
5130 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5131 clean_type.generics()
5133 let r = types.iter()
5134 .filter_map(|t| get_index_type_name(t, false))
5135 .map(|s| s.to_ascii_lowercase())
5136 .collect::<Vec<_>>();
5145 pub fn cache() -> Arc<Cache> {
5146 CACHE_KEY.with(|c| c.borrow().clone())
5151 fn test_name_key() {
5152 assert_eq!(name_key("0"), ("", 0, 1));
5153 assert_eq!(name_key("123"), ("", 123, 0));
5154 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5155 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5156 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5157 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5158 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5159 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5164 fn test_name_sorting() {
5165 let names = ["Apple",
5167 "Fruit", "Fruit0", "Fruit00",
5168 "Fruit1", "Fruit01",
5169 "Fruit2", "Fruit02",
5174 let mut sorted = names.to_owned();
5175 sorted.sort_by_key(|&s| name_key(s));
5176 assert_eq!(names, sorted);