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<Vec<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 let mut iter = self.inputs.iter();
465 if match self.output {
466 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
467 None => iter.any(|ref i| i.name.is_none()),
471 let mut data = Vec::with_capacity(2);
472 data.push(self.inputs.to_json());
473 if let Some(ref output) = self.output {
474 if output.len() > 1 {
475 data.push(output.to_json());
477 data.push(output[0].to_json());
485 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
486 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
488 pub fn initial_ids() -> Vec<String> {
500 "synthetic-implementors",
502 "synthetic-implementors-list",
506 ].into_iter().map(|id| (String::from(*id))).collect()
509 /// Generates the documentation for `crate` into the directory `dst`
510 pub fn run(mut krate: clean::Crate,
511 options: RenderOptions,
512 passes: FxHashSet<String>,
513 renderinfo: RenderInfo,
514 diag: &errors::Handler) -> Result<(), Error> {
515 // need to save a copy of the options for rendering the index page
516 let md_opts = options.clone();
522 sort_modules_alphabetically,
525 extern_html_root_urls,
528 generate_search_filter,
529 generate_redirect_pages,
533 let src_root = match krate.src {
534 FileName::Real(ref p) => match p.parent() {
535 Some(p) => p.to_path_buf(),
536 None => PathBuf::new(),
540 let mut scx = SharedContext {
543 include_sources: true,
544 local_sources: Default::default(),
545 issue_tracker_base_url: None,
546 layout: layout::Layout {
548 favicon: String::new(),
550 krate: krate.name.clone(),
552 css_file_extension: extension_css,
553 created_dirs: Default::default(),
554 sort_modules_alphabetically,
558 generate_search_filter,
559 generate_redirect_pages,
562 // If user passed in `--playground-url` arg, we fill in crate name here
563 if let Some(url) = playground_url {
564 markdown::PLAYGROUND.with(|slot| {
565 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
569 // Crawl the crate attributes looking for attributes which control how we're
570 // going to emit HTML
571 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
572 for attr in attrs.lists("doc") {
573 match (attr.name_or_empty().get(), attr.value_str()) {
574 ("html_favicon_url", Some(s)) => {
575 scx.layout.favicon = s.to_string();
577 ("html_logo_url", Some(s)) => {
578 scx.layout.logo = s.to_string();
580 ("html_playground_url", Some(s)) => {
581 markdown::PLAYGROUND.with(|slot| {
582 let name = krate.name.clone();
583 *slot.borrow_mut() = Some((Some(name), s.to_string()));
586 ("issue_tracker_base_url", Some(s)) => {
587 scx.issue_tracker_base_url = Some(s.to_string());
589 ("html_no_source", None) if attr.is_word() => {
590 scx.include_sources = false;
597 try_err!(fs::create_dir_all(&dst), &dst);
598 krate = render_sources(&dst, &mut scx, krate)?;
602 render_redirect_pages: false,
603 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
604 id_map: Rc::new(RefCell::new(id_map)),
605 shared: Arc::new(scx),
608 // Crawl the crate to build various caches used for the output
612 external_param_names,
620 let external_paths = external_paths.into_iter()
621 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
624 let mut cache = Cache {
625 impls: Default::default(),
628 paths: Default::default(),
629 implementors: Default::default(),
631 parent_stack: Vec::new(),
632 search_index: Vec::new(),
633 parent_is_trait_impl: false,
634 extern_locations: Default::default(),
635 primitive_locations: Default::default(),
638 crate_version: krate.version.take(),
639 orphan_impl_items: Vec::new(),
640 orphan_trait_impls: Vec::new(),
641 traits: krate.external_traits.lock().replace(Default::default()),
645 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
646 param_names: external_param_names,
647 aliases: Default::default(),
650 // Cache where all our extern crates are located
651 for &(n, ref e) in &krate.externs {
652 let src_root = match e.src {
653 FileName::Real(ref p) => match p.parent() {
654 Some(p) => p.to_path_buf(),
655 None => PathBuf::new(),
659 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
660 cache.extern_locations.insert(n, (e.name.clone(), src_root,
661 extern_location(e, extern_url, &cx.dst)));
663 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
664 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
667 // Cache where all known primitives have their documentation located.
669 // Favor linking to as local extern as possible, so iterate all crates in
670 // reverse topological order.
671 for &(_, ref e) in krate.externs.iter().rev() {
672 for &(def_id, prim, _) in &e.primitives {
673 cache.primitive_locations.insert(prim, def_id);
676 for &(def_id, prim, _) in &krate.primitives {
677 cache.primitive_locations.insert(prim, def_id);
680 cache.stack.push(krate.name.clone());
681 krate = cache.fold_crate(krate);
683 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
684 if cache.traits.contains_key(&trait_did) {
686 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
691 // Build our search index
692 let index = build_index(&krate, &mut cache);
694 // Freeze the cache now that the index has been built. Put an Arc into TLS
695 // for future parallelization opportunities
696 let cache = Arc::new(cache);
697 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
698 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
700 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
702 // And finally render the whole crate's documentation
706 /// Builds the search index from the collected metadata
707 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
708 let mut nodeid_to_pathid = FxHashMap::default();
709 let mut crate_items = Vec::with_capacity(cache.search_index.len());
710 let mut crate_paths = Vec::<Json>::new();
712 let Cache { ref mut search_index,
713 ref orphan_impl_items,
714 ref mut paths, .. } = *cache;
716 // Attach all orphan items to the type's definition if the type
717 // has since been learned.
718 for &(did, ref item) in orphan_impl_items {
719 if let Some(&(ref fqp, _)) = paths.get(&did) {
720 search_index.push(IndexItem {
722 name: item.name.clone().unwrap(),
723 path: fqp[..fqp.len() - 1].join("::"),
724 desc: plain_summary_line_short(item.doc_value()),
727 search_type: get_index_search_type(&item),
732 // Reduce `NodeId` in paths into smaller sequential numbers,
733 // and prune the paths that do not appear in the index.
734 let mut lastpath = String::new();
735 let mut lastpathid = 0usize;
737 for item in search_index {
738 item.parent_idx = item.parent.map(|nodeid| {
739 if nodeid_to_pathid.contains_key(&nodeid) {
740 *nodeid_to_pathid.get(&nodeid).unwrap()
742 let pathid = lastpathid;
743 nodeid_to_pathid.insert(nodeid, pathid);
746 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
747 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
752 // Omit the parent path if it is same to that of the prior item.
753 if lastpath == item.path {
756 lastpath = item.path.clone();
758 crate_items.push(item.to_json());
761 let crate_doc = krate.module.as_ref().map(|module| {
762 plain_summary_line_short(module.doc_value())
763 }).unwrap_or(String::new());
765 let mut crate_data = BTreeMap::new();
766 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
767 crate_data.insert("i".to_owned(), Json::Array(crate_items));
768 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
770 // Collect the index into a string
771 format!("searchIndex[{}] = {};",
772 as_json(&krate.name),
773 Json::Object(crate_data))
778 krate: &clean::Crate,
780 search_index: String,
781 options: &RenderOptions,
782 diag: &errors::Handler,
783 ) -> Result<(), Error> {
784 // Write out the shared files. Note that these are shared among all rustdoc
785 // docs placed in the output directory, so this needs to be a synchronized
786 // operation with respect to all other rustdocs running around.
787 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
789 // Add all the static files. These may already exist, but we just
790 // overwrite them anyway to make sure that they're fresh and up-to-date.
792 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
793 static_files::RUSTDOC_CSS,
794 options.enable_minification)?;
795 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
796 static_files::SETTINGS_CSS,
797 options.enable_minification)?;
798 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
799 static_files::NOSCRIPT_CSS,
800 options.enable_minification)?;
802 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
803 // then we'll run over the "official" styles.
804 let mut themes: FxHashSet<String> = FxHashSet::default();
806 for entry in &cx.shared.themes {
807 let content = try_err!(fs::read(&entry), &entry);
808 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
809 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
810 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
811 content.as_slice())?;
812 themes.insert(theme.to_owned());
815 if (*cx.shared).layout.logo.is_empty() {
816 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
817 static_files::RUST_LOGO)?;
819 if (*cx.shared).layout.favicon.is_empty() {
820 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
821 static_files::RUST_FAVICON)?;
823 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
824 static_files::BRUSH_SVG)?;
825 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
826 static_files::WHEEL_SVG)?;
827 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
828 static_files::DOWN_ARROW_SVG)?;
829 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
830 static_files::themes::LIGHT,
831 options.enable_minification)?;
832 themes.insert("light".to_owned());
833 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
834 static_files::themes::DARK,
835 options.enable_minification)?;
836 themes.insert("dark".to_owned());
838 let mut themes: Vec<&String> = themes.iter().collect();
840 // To avoid theme switch latencies as much as possible, we put everything theme related
841 // at the beginning of the html files into another js file.
842 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
844 r#"var themes = document.getElementById("theme-choices");
845 var themePicker = document.getElementById("theme-picker");
847 function switchThemeButtonState() {{
848 if (themes.style.display === "block") {{
849 themes.style.display = "none";
850 themePicker.style.borderBottomRightRadius = "3px";
851 themePicker.style.borderBottomLeftRadius = "3px";
853 themes.style.display = "block";
854 themePicker.style.borderBottomRightRadius = "0";
855 themePicker.style.borderBottomLeftRadius = "0";
859 function handleThemeButtonsBlur(e) {{
860 var active = document.activeElement;
861 var related = e.relatedTarget;
863 if (active.id !== "themePicker" &&
864 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
866 (related.id !== "themePicker" &&
867 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
868 switchThemeButtonState();
872 themePicker.onclick = switchThemeButtonState;
873 themePicker.onblur = handleThemeButtonsBlur;
874 [{}].forEach(function(item) {{
875 var but = document.createElement('button');
876 but.innerHTML = item;
877 but.onclick = function(el) {{
878 switchTheme(currentTheme, mainTheme, item);
880 but.onblur = handleThemeButtonsBlur;
881 themes.appendChild(but);
884 .map(|s| format!("\"{}\"", s))
885 .collect::<Vec<String>>()
886 .join(",")).as_bytes(),
889 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
890 static_files::MAIN_JS,
891 options.enable_minification)?;
892 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
893 static_files::SETTINGS_JS,
894 options.enable_minification)?;
895 if cx.shared.include_sources {
896 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
897 static_files::sidebar::SOURCE_SCRIPT,
898 options.enable_minification)?;
902 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
903 &format!("var resourcesSuffix = \"{}\";{}",
904 cx.shared.resource_suffix,
905 static_files::STORAGE_JS),
906 options.enable_minification)?;
909 if let Some(ref css) = cx.shared.css_file_extension {
910 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
911 if !options.enable_minification {
912 try_err!(fs::copy(css, out), css);
914 let buffer = try_err!(fs::read_to_string(css), css);
915 write_minify(out, &buffer, options.enable_minification)?;
918 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
919 static_files::NORMALIZE_CSS,
920 options.enable_minification)?;
921 write(cx.dst.join("FiraSans-Regular.woff"),
922 static_files::fira_sans::REGULAR)?;
923 write(cx.dst.join("FiraSans-Medium.woff"),
924 static_files::fira_sans::MEDIUM)?;
925 write(cx.dst.join("FiraSans-LICENSE.txt"),
926 static_files::fira_sans::LICENSE)?;
927 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
928 static_files::source_serif_pro::REGULAR)?;
929 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
930 static_files::source_serif_pro::BOLD)?;
931 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
932 static_files::source_serif_pro::ITALIC)?;
933 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
934 static_files::source_serif_pro::LICENSE)?;
935 write(cx.dst.join("SourceCodePro-Regular.woff"),
936 static_files::source_code_pro::REGULAR)?;
937 write(cx.dst.join("SourceCodePro-Semibold.woff"),
938 static_files::source_code_pro::SEMIBOLD)?;
939 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
940 static_files::source_code_pro::LICENSE)?;
941 write(cx.dst.join("LICENSE-MIT.txt"),
942 static_files::LICENSE_MIT)?;
943 write(cx.dst.join("LICENSE-APACHE.txt"),
944 static_files::LICENSE_APACHE)?;
945 write(cx.dst.join("COPYRIGHT.txt"),
946 static_files::COPYRIGHT)?;
952 for_search_index: bool,
953 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
956 let mut ret = Vec::new();
957 let mut krates = Vec::new();
958 let mut variables = Vec::new();
960 let mut krate = krate.to_owned();
963 for line in BufReader::new(File::open(path)?).lines() {
965 if for_search_index && line.starts_with("var R") {
966 variables.push(line.clone());
967 // We need to check if the crate name has been put into a variable as well.
968 let tokens = js::simple_minify(&line).apply(js::clean_tokens);
970 while pos < tokens.len() {
971 if let Some((var_pos, Some(value_pos))) =
972 js::get_variable_name_and_value_positions(&tokens, pos) {
973 if let Some(s) = tokens.0[value_pos].get_string() {
974 if &s[1..s.len() - 1] == krate {
975 if let Some(var) = tokens[var_pos].get_other() {
976 krate = var.to_owned();
986 if !line.starts_with(key) {
989 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
992 ret.push(line.to_string());
993 krates.push(line[key.len() + 2..].split('"')
995 .map(|s| s.to_owned())
996 .unwrap_or_else(|| String::new()));
999 Ok((ret, krates, variables))
1002 fn show_item(item: &IndexItem, krate: &str) -> String {
1003 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
1004 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
1005 if let Some(p) = item.parent_idx {
1006 format!(",'parent':{}", p)
1012 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
1014 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
1015 let mut w = try_err!(File::create(&dst), &dst);
1016 let mut output = String::with_capacity(100);
1017 for (alias, items) in &cache.aliases {
1018 if items.is_empty() {
1021 output.push_str(&format!("\"{}\":[{}],",
1024 .map(|v| show_item(v, &krate.name))
1025 .collect::<Vec<_>>()
1028 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1030 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1031 for aliases in &all_aliases {
1032 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1036 use std::ffi::OsString;
1041 children: FxHashMap<OsString, Hierarchy>,
1042 elems: FxHashSet<OsString>,
1046 fn new(elem: OsString) -> Hierarchy {
1049 children: FxHashMap::default(),
1050 elems: FxHashSet::default(),
1054 fn to_json_string(&self) -> String {
1055 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1056 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1057 let mut files = self.elems.iter()
1058 .map(|s| format!("\"{}\"",
1060 .expect("invalid osstring conversion")))
1061 .collect::<Vec<_>>();
1062 files.sort_unstable_by(|a, b| a.cmp(b));
1063 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1064 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1065 name=self.elem.to_str().expect("invalid osstring conversion"),
1066 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1067 files=files.join(","))
1071 if cx.shared.include_sources {
1072 use std::path::Component;
1074 let mut hierarchy = Hierarchy::new(OsString::new());
1075 for source in cx.shared.local_sources.iter()
1076 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1078 let mut h = &mut hierarchy;
1079 let mut elems = source.components()
1082 Component::Normal(s) => Some(s.to_owned()),
1088 let cur_elem = elems.next().expect("empty file path");
1089 if elems.peek().is_none() {
1090 h.elems.insert(cur_elem);
1093 let e = cur_elem.clone();
1094 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1095 h = h.children.get_mut(&cur_elem).expect("not found child");
1100 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1101 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1104 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1106 hierarchy.to_json_string()));
1108 let mut w = try_err!(File::create(&dst), &dst);
1109 try_err!(writeln!(&mut w,
1110 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1111 all_sources.join("\n")),
1115 // Update the search index
1116 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1117 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1121 all_indexes.push(search_index);
1123 // Sort the indexes by crate so the file will be generated identically even
1124 // with rustdoc running in parallel.
1126 let mut w = try_err!(File::create(&dst), &dst);
1127 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1128 try_err!(write_minify_replacer(&mut w,
1129 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1130 options.enable_minification),
1132 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1134 if options.enable_index_page {
1135 if let Some(index_page) = options.index_page.clone() {
1136 let mut md_opts = options.clone();
1137 md_opts.output = cx.dst.clone();
1138 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1140 crate::markdown::render(index_page, md_opts, diag);
1142 let dst = cx.dst.join("index.html");
1143 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1144 let page = layout::Page {
1145 title: "Index of crates",
1148 static_root_path: cx.shared.static_root_path.deref(),
1149 description: "List of crates",
1150 keywords: BASIC_KEYWORDS,
1151 resource_suffix: &cx.shared.resource_suffix,
1153 static_extra_scripts: &[],
1155 krates.push(krate.name.clone());
1159 let content = format!(
1161 <span class='in-band'>List of all crates</span>\
1162 </h1><ul class='mod'>{}</ul>",
1166 format!("<li><a href=\"{}index.html\">{}</li>",
1169 .collect::<String>());
1170 try_err!(layout::render(&mut w, &cx.shared.layout,
1171 &page, &(""), &content,
1172 cx.shared.css_file_extension.is_some(),
1174 cx.shared.generate_search_filter), &dst);
1175 try_err!(w.flush(), &dst);
1179 // Update the list of all implementors for traits
1180 let dst = cx.dst.join("implementors");
1181 for (&did, imps) in &cache.implementors {
1182 // Private modules can leak through to this phase of rustdoc, which
1183 // could contain implementations for otherwise private types. In some
1184 // rare cases we could find an implementation for an item which wasn't
1185 // indexed, so we just skip this step in that case.
1187 // FIXME: this is a vague explanation for why this can't be a `get`, in
1188 // theory it should be...
1189 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1191 None => match cache.external_paths.get(&did) {
1197 let mut have_impls = false;
1198 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1200 // If the trait and implementation are in the same crate, then
1201 // there's no need to emit information about it (there's inlining
1202 // going on). If they're in different crates then the crate defining
1203 // the trait will be interested in our implementation.
1204 if imp.impl_item.def_id.krate == did.krate { continue }
1205 // If the implementation is from another crate then that crate
1207 if !imp.impl_item.def_id.is_local() { continue }
1209 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1210 as_json(&imp.inner_impl().to_string()),
1211 imp.inner_impl().synthetic,
1212 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1214 implementors.push_str("];");
1216 // Only create a js file if we have impls to add to it. If the trait is
1217 // documented locally though we always create the file to avoid dead
1219 if !have_impls && !cache.paths.contains_key(&did) {
1223 let mut mydst = dst.clone();
1224 for part in &remote_path[..remote_path.len() - 1] {
1227 try_err!(fs::create_dir_all(&mydst), &mydst);
1228 mydst.push(&format!("{}.{}.js",
1229 remote_item_type.css_class(),
1230 remote_path[remote_path.len() - 1]));
1232 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1235 all_implementors.push(implementors);
1236 // Sort the implementors by crate so the file will be generated
1237 // identically even with rustdoc running in parallel.
1238 all_implementors.sort();
1240 let mut f = try_err!(File::create(&mydst), &mydst);
1241 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1242 for implementor in &all_implementors {
1243 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1245 try_err!(writeln!(&mut f, "{}", r"
1246 if (window.register_implementors) {
1247 window.register_implementors(implementors);
1249 window.pending_implementors = implementors;
1252 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1257 fn render_sources(dst: &Path, scx: &mut SharedContext,
1258 krate: clean::Crate) -> Result<clean::Crate, Error> {
1259 info!("emitting source files");
1260 let dst = dst.join("src").join(&krate.name);
1261 try_err!(fs::create_dir_all(&dst), &dst);
1262 let mut folder = SourceCollector {
1266 Ok(folder.fold_crate(krate))
1269 /// Writes the entire contents of a string to a destination, not attempting to
1270 /// catch any errors.
1271 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1272 Ok(try_err!(fs::write(&dst, contents), &dst))
1275 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1276 if enable_minification {
1277 if dst.extension() == Some(&OsStr::new("css")) {
1278 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1279 write(dst, res.as_bytes())
1281 write(dst, minifier::js::minify(contents).as_bytes())
1284 write(dst, contents.as_bytes())
1288 fn write_minify_replacer<W: Write>(
1291 enable_minification: bool,
1292 ) -> io::Result<()> {
1293 use minifier::js::{Keyword, ReservedChar, Token};
1295 if enable_minification {
1297 minifier::js::simple_minify(contents)
1299 // We keep backlines.
1300 minifier::js::clean_tokens_except(f, |c| {
1301 c.get_char() != Some(ReservedChar::Backline)
1305 minifier::js::replace_token_with(f, |t| {
1307 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1308 Token::String(s) => {
1309 let s = &s[1..s.len() -1]; // The quotes are included
1311 Some(Token::Other("E"))
1312 } else if s == "t" {
1313 Some(Token::Other("T"))
1314 } else if s == "u" {
1315 Some(Token::Other("U"))
1325 // We add a backline after the newly created variables.
1326 minifier::js::aggregate_strings_into_array_with_separation(
1329 Token::Char(ReservedChar::Backline),
1334 writeln!(dst, "{}", contents)
1338 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1339 /// things like ".." to components which preserve the "top down" hierarchy of a
1340 /// static HTML tree. Each component in the cleaned path will be passed as an
1341 /// argument to `f`. The very last component of the path (ie the file name) will
1342 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1343 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1346 // make it relative, if possible
1347 let p = p.strip_prefix(src_root).unwrap_or(p);
1349 let mut iter = p.components().peekable();
1351 while let Some(c) = iter.next() {
1352 if !keep_filename && iter.peek().is_none() {
1357 Component::ParentDir => f("up".as_ref()),
1358 Component::Normal(c) => f(c),
1364 /// Attempts to find where an external crate is located, given that we're
1365 /// rendering in to the specified source destination.
1366 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1369 // See if there's documentation generated into the local directory
1370 let local_location = dst.join(&e.name);
1371 if local_location.is_dir() {
1375 if let Some(url) = extern_url {
1376 let mut url = url.to_string();
1377 if !url.ends_with("/") {
1383 // Failing that, see if there's an attribute specifying where to find this
1385 e.attrs.lists("doc")
1386 .filter(|a| a.check_name("html_root_url"))
1387 .filter_map(|a| a.value_str())
1389 let mut url = url.to_string();
1390 if !url.ends_with("/") {
1394 }).next().unwrap_or(Unknown) // Well, at least we tried.
1397 impl<'a> DocFolder for SourceCollector<'a> {
1398 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1399 // If we're including source files, and we haven't seen this file yet,
1400 // then we need to render it out to the filesystem.
1401 if self.scx.include_sources
1402 // skip all invalid or macro spans
1403 && item.source.filename.is_real()
1404 // skip non-local items
1405 && item.def_id.is_local() {
1407 // If it turns out that we couldn't read this file, then we probably
1408 // can't read any of the files (generating html output from json or
1409 // something like that), so just don't include sources for the
1410 // entire crate. The other option is maintaining this mapping on a
1411 // per-file basis, but that's probably not worth it...
1413 .include_sources = match self.emit_source(&item.source.filename) {
1416 println!("warning: source code was requested to be rendered, \
1417 but processing `{}` had an error: {}",
1418 item.source.filename, e);
1419 println!(" skipping rendering of source code");
1424 self.fold_item_recur(item)
1428 impl<'a> SourceCollector<'a> {
1429 /// Renders the given filename into its corresponding HTML source file.
1430 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1431 let p = match *filename {
1432 FileName::Real(ref file) => file,
1435 if self.scx.local_sources.contains_key(&**p) {
1436 // We've already emitted this source
1440 let contents = fs::read_to_string(&p)?;
1442 // Remove the utf-8 BOM if any
1443 let contents = if contents.starts_with("\u{feff}") {
1449 // Create the intermediate directories
1450 let mut cur = self.dst.clone();
1451 let mut root_path = String::from("../../");
1452 let mut href = String::new();
1453 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1454 cur.push(component);
1455 fs::create_dir_all(&cur).unwrap();
1456 root_path.push_str("../");
1457 href.push_str(&component.to_string_lossy());
1460 let mut fname = p.file_name()
1461 .expect("source has no filename")
1463 fname.push(".html");
1465 href.push_str(&fname.to_string_lossy());
1467 let mut w = BufWriter::new(File::create(&cur)?);
1468 let title = format!("{} -- source", cur.file_name().unwrap()
1469 .to_string_lossy());
1470 let desc = format!("Source to the Rust file `{}`.", filename);
1471 let page = layout::Page {
1473 css_class: "source",
1474 root_path: &root_path,
1475 static_root_path: self.scx.static_root_path.deref(),
1477 keywords: BASIC_KEYWORDS,
1478 resource_suffix: &self.scx.resource_suffix,
1479 extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
1480 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1482 layout::render(&mut w, &self.scx.layout,
1483 &page, &(""), &Source(contents),
1484 self.scx.css_file_extension.is_some(),
1486 self.scx.generate_search_filter)?;
1488 self.scx.local_sources.insert(p.clone(), href);
1493 impl DocFolder for Cache {
1494 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1495 if item.def_id.is_local() {
1496 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1499 // If this is a stripped module,
1500 // we don't want it or its children in the search index.
1501 let orig_stripped_mod = match item.inner {
1502 clean::StrippedItem(box clean::ModuleItem(..)) => {
1503 mem::replace(&mut self.stripped_mod, true)
1505 _ => self.stripped_mod,
1508 // If the impl is from a masked crate or references something from a
1509 // masked crate then remove it completely.
1510 if let clean::ImplItem(ref i) = item.inner {
1511 if self.masked_crates.contains(&item.def_id.krate) ||
1512 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1513 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1518 // Register any generics to their corresponding string. This is used
1519 // when pretty-printing types.
1520 if let Some(generics) = item.inner.generics() {
1521 self.generics(generics);
1524 // Propagate a trait method's documentation to all implementors of the
1526 if let clean::TraitItem(ref t) = item.inner {
1527 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1530 // Collect all the implementors of traits.
1531 if let clean::ImplItem(ref i) = item.inner {
1532 if let Some(did) = i.trait_.def_id() {
1533 if i.blanket_impl.is_none() {
1534 self.implementors.entry(did).or_default().push(Impl {
1535 impl_item: item.clone(),
1541 // Index this method for searching later on.
1542 if let Some(ref s) = item.name {
1543 let (parent, is_inherent_impl_item) = match item.inner {
1544 clean::StrippedItem(..) => ((None, None), false),
1545 clean::AssociatedConstItem(..) |
1546 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1547 // skip associated items in trait impls
1548 ((None, None), false)
1550 clean::AssociatedTypeItem(..) |
1551 clean::TyMethodItem(..) |
1552 clean::StructFieldItem(..) |
1553 clean::VariantItem(..) => {
1554 ((Some(*self.parent_stack.last().unwrap()),
1555 Some(&self.stack[..self.stack.len() - 1])),
1558 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1559 if self.parent_stack.is_empty() {
1560 ((None, None), false)
1562 let last = self.parent_stack.last().unwrap();
1564 let path = match self.paths.get(&did) {
1565 // The current stack not necessarily has correlation
1566 // for where the type was defined. On the other
1567 // hand, `paths` always has the right
1568 // information if present.
1569 Some(&(ref fqp, ItemType::Trait)) |
1570 Some(&(ref fqp, ItemType::Struct)) |
1571 Some(&(ref fqp, ItemType::Union)) |
1572 Some(&(ref fqp, ItemType::Enum)) =>
1573 Some(&fqp[..fqp.len() - 1]),
1574 Some(..) => Some(&*self.stack),
1577 ((Some(*last), path), true)
1580 _ => ((None, Some(&*self.stack)), false)
1584 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1585 debug_assert!(!item.is_stripped());
1587 // A crate has a module at its root, containing all items,
1588 // which should not be indexed. The crate-item itself is
1589 // inserted later on when serializing the search-index.
1590 if item.def_id.index != CRATE_DEF_INDEX {
1591 self.search_index.push(IndexItem {
1593 name: s.to_string(),
1594 path: path.join("::"),
1595 desc: plain_summary_line_short(item.doc_value()),
1598 search_type: get_index_search_type(&item),
1602 (Some(parent), None) if is_inherent_impl_item => {
1603 // We have a parent, but we don't know where they're
1604 // defined yet. Wait for later to index this item.
1605 self.orphan_impl_items.push((parent, item.clone()));
1611 // Keep track of the fully qualified path for this item.
1612 let pushed = match item.name {
1613 Some(ref n) if !n.is_empty() => {
1614 self.stack.push(n.to_string());
1621 clean::StructItem(..) | clean::EnumItem(..) |
1622 clean::TypedefItem(..) | clean::TraitItem(..) |
1623 clean::FunctionItem(..) | clean::ModuleItem(..) |
1624 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1625 clean::ConstantItem(..) | clean::StaticItem(..) |
1626 clean::UnionItem(..) | clean::ForeignTypeItem |
1627 clean::MacroItem(..) | clean::ProcMacroItem(..)
1628 if !self.stripped_mod => {
1629 // Re-exported items mean that the same id can show up twice
1630 // in the rustdoc ast that we're looking at. We know,
1631 // however, that a re-exported item doesn't show up in the
1632 // `public_items` map, so we can skip inserting into the
1633 // paths map if there was already an entry present and we're
1634 // not a public item.
1635 if !self.paths.contains_key(&item.def_id) ||
1636 self.access_levels.is_public(item.def_id)
1638 self.paths.insert(item.def_id,
1639 (self.stack.clone(), item.type_()));
1641 self.add_aliases(&item);
1643 // Link variants to their parent enum because pages aren't emitted
1644 // for each variant.
1645 clean::VariantItem(..) if !self.stripped_mod => {
1646 let mut stack = self.stack.clone();
1648 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1651 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1652 self.add_aliases(&item);
1653 self.paths.insert(item.def_id, (self.stack.clone(),
1660 // Maintain the parent stack
1661 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1662 let parent_pushed = match item.inner {
1663 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1664 clean::StructItem(..) | clean::UnionItem(..) => {
1665 self.parent_stack.push(item.def_id);
1666 self.parent_is_trait_impl = false;
1669 clean::ImplItem(ref i) => {
1670 self.parent_is_trait_impl = i.trait_.is_some();
1672 clean::ResolvedPath{ did, .. } => {
1673 self.parent_stack.push(did);
1677 let prim_did = t.primitive_type().and_then(|t| {
1678 self.primitive_locations.get(&t).cloned()
1682 self.parent_stack.push(did);
1693 // Once we've recursively found all the generics, hoard off all the
1694 // implementations elsewhere.
1695 let ret = self.fold_item_recur(item).and_then(|item| {
1696 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1697 // Figure out the id of this impl. This may map to a
1698 // primitive rather than always to a struct/enum.
1699 // Note: matching twice to restrict the lifetime of the `i` borrow.
1700 let mut dids = FxHashSet::default();
1701 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1703 clean::ResolvedPath { did, .. } |
1704 clean::BorrowedRef {
1705 type_: box clean::ResolvedPath { did, .. }, ..
1710 let did = t.primitive_type().and_then(|t| {
1711 self.primitive_locations.get(&t).cloned()
1714 if let Some(did) = did {
1720 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1721 for bound in generics {
1722 if let Some(did) = bound.def_id() {
1730 let impl_item = Impl {
1733 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1735 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1738 let trait_did = impl_item.trait_did().unwrap();
1739 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1747 if pushed { self.stack.pop().unwrap(); }
1748 if parent_pushed { self.parent_stack.pop().unwrap(); }
1749 self.stripped_mod = orig_stripped_mod;
1750 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1756 fn generics(&mut self, generics: &clean::Generics) {
1757 for param in &generics.params {
1759 clean::GenericParamDefKind::Lifetime => {}
1760 clean::GenericParamDefKind::Type { did, .. } |
1761 clean::GenericParamDefKind::Const { did, .. } => {
1762 self.param_names.insert(did, param.name.clone());
1768 fn add_aliases(&mut self, item: &clean::Item) {
1769 if item.def_id.index == CRATE_DEF_INDEX {
1772 if let Some(ref item_name) = item.name {
1773 let path = self.paths.get(&item.def_id)
1774 .map(|p| p.0[..p.0.len() - 1].join("::"))
1775 .unwrap_or("std".to_owned());
1776 for alias in item.attrs.lists("doc")
1777 .filter(|a| a.check_name("alias"))
1778 .filter_map(|a| a.value_str()
1779 .map(|s| s.to_string().replace("\"", "")))
1780 .filter(|v| !v.is_empty())
1781 .collect::<FxHashSet<_>>()
1783 self.aliases.entry(alias)
1784 .or_insert(Vec::with_capacity(1))
1787 name: item_name.to_string(),
1789 desc: plain_summary_line_short(item.doc_value()),
1792 search_type: get_index_search_type(&item),
1799 #[derive(Debug, Eq, PartialEq, Hash)]
1806 fn new(mut url: String, name: String) -> ItemEntry {
1807 while url.starts_with('/') {
1817 impl fmt::Display for ItemEntry {
1818 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1819 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1823 impl PartialOrd for ItemEntry {
1824 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1825 Some(self.cmp(other))
1829 impl Ord for ItemEntry {
1830 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1831 self.name.cmp(&other.name)
1837 structs: FxHashSet<ItemEntry>,
1838 enums: FxHashSet<ItemEntry>,
1839 unions: FxHashSet<ItemEntry>,
1840 primitives: FxHashSet<ItemEntry>,
1841 traits: FxHashSet<ItemEntry>,
1842 macros: FxHashSet<ItemEntry>,
1843 functions: FxHashSet<ItemEntry>,
1844 typedefs: FxHashSet<ItemEntry>,
1845 existentials: FxHashSet<ItemEntry>,
1846 statics: FxHashSet<ItemEntry>,
1847 constants: FxHashSet<ItemEntry>,
1848 keywords: FxHashSet<ItemEntry>,
1849 attributes: FxHashSet<ItemEntry>,
1850 derives: FxHashSet<ItemEntry>,
1851 trait_aliases: FxHashSet<ItemEntry>,
1855 fn new() -> AllTypes {
1856 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1858 structs: new_set(100),
1859 enums: new_set(100),
1860 unions: new_set(100),
1861 primitives: new_set(26),
1862 traits: new_set(100),
1863 macros: new_set(100),
1864 functions: new_set(100),
1865 typedefs: new_set(100),
1866 existentials: new_set(100),
1867 statics: new_set(100),
1868 constants: new_set(100),
1869 keywords: new_set(100),
1870 attributes: new_set(100),
1871 derives: new_set(100),
1872 trait_aliases: new_set(100),
1876 fn append(&mut self, item_name: String, item_type: &ItemType) {
1877 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1878 if let Some(name) = url.pop() {
1879 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1881 let name = url.join("::");
1883 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1884 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1885 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1886 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1887 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1888 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1889 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1890 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1891 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1892 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1893 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1894 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1895 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1896 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1903 fn print_entries(f: &mut fmt::Formatter<'_>, e: &FxHashSet<ItemEntry>, title: &str,
1904 class: &str) -> fmt::Result {
1906 let mut e: Vec<&ItemEntry> = e.iter().collect();
1908 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1912 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1917 impl fmt::Display for AllTypes {
1918 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1921 <span class='out-of-band'>\
1922 <span id='render-detail'>\
1923 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1924 [<span class='inner'>−</span>]\
1928 <span class='in-band'>List of all items</span>\
1930 print_entries(f, &self.structs, "Structs", "structs")?;
1931 print_entries(f, &self.enums, "Enums", "enums")?;
1932 print_entries(f, &self.unions, "Unions", "unions")?;
1933 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1934 print_entries(f, &self.traits, "Traits", "traits")?;
1935 print_entries(f, &self.macros, "Macros", "macros")?;
1936 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1937 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1938 print_entries(f, &self.functions, "Functions", "functions")?;
1939 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1940 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1941 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1942 print_entries(f, &self.statics, "Statics", "statics")?;
1943 print_entries(f, &self.constants, "Constants", "constants")
1948 struct Settings<'a> {
1949 // (id, explanation, default value)
1950 settings: Vec<(&'static str, &'static str, bool)>,
1955 impl<'a> Settings<'a> {
1956 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1959 ("item-declarations", "Auto-hide item declarations.", true),
1960 ("item-attributes", "Auto-hide item attributes.", true),
1961 ("trait-implementations", "Auto-hide trait implementations documentation",
1963 ("method-docs", "Auto-hide item methods' documentation", false),
1964 ("go-to-only-result", "Directly go to item in search if there is only one result",
1966 ("line-numbers", "Show line numbers on code examples", false),
1974 impl<'a> fmt::Display for Settings<'a> {
1975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1978 <span class='in-band'>Rustdoc settings</span>\
1980 <div class='settings'>{}</div>\
1981 <script src='{}settings{}.js'></script>",
1982 self.settings.iter()
1983 .map(|(id, text, enabled)| {
1984 format!("<div class='setting-line'>\
1985 <label class='toggle'>\
1986 <input type='checkbox' id='{}' {}>\
1987 <span class='slider'></span>\
1990 </div>", id, if *enabled { " checked" } else { "" }, text)
1992 .collect::<String>(),
1999 fn derive_id(&self, id: String) -> String {
2000 let mut map = self.id_map.borrow_mut();
2004 /// String representation of how to get back to the root path of the 'doc/'
2005 /// folder in terms of a relative URL.
2006 fn root_path(&self) -> String {
2007 "../".repeat(self.current.len())
2010 /// Recurse in the directory structure and change the "root path" to make
2011 /// sure it always points to the top (relatively).
2012 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2013 F: FnOnce(&mut Context) -> T,
2016 panic!("Unexpected empty destination: {:?}", self.current);
2018 let prev = self.dst.clone();
2020 self.current.push(s);
2022 info!("Recursing into {}", self.dst.display());
2026 info!("Recursed; leaving {}", self.dst.display());
2028 // Go back to where we were at
2030 self.current.pop().unwrap();
2035 /// Main method for rendering a crate.
2037 /// This currently isn't parallelized, but it'd be pretty easy to add
2038 /// parallelization to this function.
2039 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2040 let mut item = match krate.module.take() {
2042 None => return Ok(()),
2044 let final_file = self.dst.join(&krate.name)
2046 let settings_file = self.dst.join("settings.html");
2048 let crate_name = krate.name.clone();
2049 item.name = Some(krate.name);
2051 let mut all = AllTypes::new();
2054 // Render the crate documentation
2055 let mut work = vec![(self.clone(), item)];
2057 while let Some((mut cx, item)) = work.pop() {
2058 cx.item(item, &mut all, |cx, item| {
2059 work.push((cx.clone(), item))
2064 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2065 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2066 if !root_path.ends_with('/') {
2067 root_path.push('/');
2069 let mut page = layout::Page {
2070 title: "List of all items in this crate",
2073 static_root_path: self.shared.static_root_path.deref(),
2074 description: "List of all items in this crate",
2075 keywords: BASIC_KEYWORDS,
2076 resource_suffix: &self.shared.resource_suffix,
2078 static_extra_scripts: &[],
2080 let sidebar = if let Some(ref version) = cache().crate_version {
2081 format!("<p class='location'>Crate {}</p>\
2082 <div class='block version'>\
2085 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2086 crate_name, version)
2090 try_err!(layout::render(&mut w, &self.shared.layout,
2091 &page, &sidebar, &all,
2092 self.shared.css_file_extension.is_some(),
2093 &self.shared.themes,
2094 self.shared.generate_search_filter),
2097 // Generating settings page.
2098 let settings = Settings::new("./", &self.shared.resource_suffix);
2099 page.title = "Rustdoc settings";
2100 page.description = "Settings of Rustdoc";
2101 page.root_path = "./";
2103 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2104 let mut themes = self.shared.themes.clone();
2105 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2106 themes.push(PathBuf::from("settings.css"));
2107 let layout = self.shared.layout.clone();
2108 try_err!(layout::render(&mut w, &layout,
2109 &page, &sidebar, &settings,
2110 self.shared.css_file_extension.is_some(),
2112 self.shared.generate_search_filter),
2118 fn render_item(&self,
2119 writer: &mut dyn io::Write,
2123 // A little unfortunate that this is done like this, but it sure
2124 // does make formatting *a lot* nicer.
2125 CURRENT_LOCATION_KEY.with(|slot| {
2126 *slot.borrow_mut() = self.current.clone();
2129 let mut title = if it.is_primitive() || it.is_keyword() {
2130 // No need to include the namespace for primitive types and keywords
2133 self.current.join("::")
2136 if !title.is_empty() {
2137 title.push_str("::");
2139 title.push_str(it.name.as_ref().unwrap());
2141 title.push_str(" - Rust");
2142 let tyname = it.type_().css_class();
2143 let desc = if it.is_crate() {
2144 format!("API documentation for the Rust `{}` crate.",
2145 self.shared.layout.krate)
2147 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2148 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2150 let keywords = make_item_keywords(it);
2151 let page = layout::Page {
2153 root_path: &self.root_path(),
2154 static_root_path: self.shared.static_root_path.deref(),
2157 keywords: &keywords,
2158 resource_suffix: &self.shared.resource_suffix,
2160 static_extra_scripts: &[],
2164 self.id_map.borrow_mut().reset();
2165 self.id_map.borrow_mut().populate(initial_ids());
2168 if !self.render_redirect_pages {
2169 layout::render(writer, &self.shared.layout, &page,
2170 &Sidebar{ cx: self, item: it },
2171 &Item{ cx: self, item: it },
2172 self.shared.css_file_extension.is_some(),
2173 &self.shared.themes,
2174 self.shared.generate_search_filter)?;
2176 let mut url = self.root_path();
2177 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2178 for name in &names[..names.len() - 1] {
2182 url.push_str(&item_path(ty, names.last().unwrap()));
2183 layout::redirect(writer, &url)?;
2189 /// Non-parallelized version of rendering an item. This will take the input
2190 /// item, render its contents, and then invoke the specified closure with
2191 /// all sub-items which need to be rendered.
2193 /// The rendering driver uses this closure to queue up more work.
2194 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2195 where F: FnMut(&mut Context, clean::Item),
2197 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2198 // if they contain impls for public types. These modules can also
2199 // contain items such as publicly re-exported structures.
2201 // External crates will provide links to these structures, so
2202 // these modules are recursed into, but not rendered normally
2203 // (a flag on the context).
2204 if !self.render_redirect_pages {
2205 self.render_redirect_pages = item.is_stripped();
2209 // modules are special because they add a namespace. We also need to
2210 // recurse into the items of the module as well.
2211 let name = item.name.as_ref().unwrap().to_string();
2212 let mut item = Some(item);
2213 self.recurse(name, |this| {
2214 let item = item.take().unwrap();
2216 let mut buf = Vec::new();
2217 this.render_item(&mut buf, &item, false).unwrap();
2218 // buf will be empty if the module is stripped and there is no redirect for it
2219 if !buf.is_empty() {
2220 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2221 let joint_dst = this.dst.join("index.html");
2222 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2225 let m = match item.inner {
2226 clean::StrippedItem(box clean::ModuleItem(m)) |
2227 clean::ModuleItem(m) => m,
2231 // Render sidebar-items.js used throughout this module.
2232 if !this.render_redirect_pages {
2233 let items = this.build_sidebar_items(&m);
2234 let js_dst = this.dst.join("sidebar-items.js");
2235 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2236 try_err!(write!(&mut js_out, "initSidebarItems({});",
2237 as_json(&items)), &js_dst);
2240 for item in m.items {
2246 } else if item.name.is_some() {
2247 let mut buf = Vec::new();
2248 self.render_item(&mut buf, &item, true).unwrap();
2249 // buf will be empty if the item is stripped and there is no redirect for it
2250 if !buf.is_empty() {
2251 let name = item.name.as_ref().unwrap();
2252 let item_type = item.type_();
2253 let file_name = &item_path(item_type, name);
2254 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2255 let joint_dst = self.dst.join(file_name);
2256 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2258 if !self.render_redirect_pages {
2259 all.append(full_path(self, &item), &item_type);
2261 if self.shared.generate_redirect_pages {
2262 // Redirect from a sane URL using the namespace to Rustdoc's
2263 // URL for the page.
2264 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2265 let redir_dst = self.dst.join(redir_name);
2266 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2269 let mut redirect_out = BufWriter::new(redirect_out);
2270 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2273 // If the item is a macro, redirect from the old macro URL (with !)
2274 // to the new one (without).
2275 if item_type == ItemType::Macro {
2276 let redir_name = format!("{}.{}!.html", item_type, name);
2277 let redir_dst = self.dst.join(redir_name);
2278 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2279 let mut redirect_out = BufWriter::new(redirect_out);
2280 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2287 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2288 // BTreeMap instead of HashMap to get a sorted output
2289 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2290 for item in &m.items {
2291 if item.is_stripped() { continue }
2293 let short = item.type_().css_class();
2294 let myname = match item.name {
2296 Some(ref s) => s.to_string(),
2298 let short = short.to_string();
2299 map.entry(short).or_default()
2300 .push((myname, Some(plain_summary_line(item.doc_value()))));
2303 if self.shared.sort_modules_alphabetically {
2304 for (_, items) in &mut map {
2313 /// Generates a url appropriate for an `href` attribute back to the source of
2316 /// The url generated, when clicked, will redirect the browser back to the
2317 /// original source code.
2319 /// If `None` is returned, then a source link couldn't be generated. This
2320 /// may happen, for example, with externally inlined items where the source
2321 /// of their crate documentation isn't known.
2322 fn src_href(&self) -> Option<String> {
2323 let mut root = self.cx.root_path();
2325 let cache = cache();
2326 let mut path = String::new();
2328 // We can safely ignore macros from other libraries
2329 let file = match self.item.source.filename {
2330 FileName::Real(ref path) => path,
2334 let (krate, path) = if self.item.def_id.is_local() {
2335 if let Some(path) = self.cx.shared.local_sources.get(file) {
2336 (&self.cx.shared.layout.krate, path)
2341 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2342 (ref name, ref src, Local) => (name, src),
2343 (ref name, ref src, Remote(ref s)) => {
2344 root = s.to_string();
2347 (_, _, Unknown) => return None,
2350 clean_srcpath(&src_root, file, false, |component| {
2351 path.push_str(&component.to_string_lossy());
2354 let mut fname = file.file_name().expect("source has no filename")
2356 fname.push(".html");
2357 path.push_str(&fname.to_string_lossy());
2361 let lines = if self.item.source.loline == self.item.source.hiline {
2362 self.item.source.loline.to_string()
2364 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2366 Some(format!("{root}src/{krate}/{path}#{lines}",
2367 root = Escape(&root),
2374 fn wrap_into_docblock<F>(w: &mut fmt::Formatter<'_>,
2375 f: F) -> fmt::Result
2376 where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result {
2377 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2382 impl<'a> fmt::Display for Item<'a> {
2383 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2384 debug_assert!(!self.item.is_stripped());
2385 // Write the breadcrumb trail header for the top
2386 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2387 if let Some(version) = self.item.stable_since() {
2388 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2392 "<span id='render-detail'>\
2393 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2394 title=\"collapse all docs\">\
2395 [<span class='inner'>−</span>]\
2401 // When this item is part of a `pub use` in a downstream crate, the
2402 // [src] link in the downstream documentation will actually come back to
2403 // this page, and this link will be auto-clicked. The `id` attribute is
2404 // used to find the link to auto-click.
2405 if self.cx.shared.include_sources && !self.item.is_primitive() {
2406 if let Some(l) = self.src_href() {
2407 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2408 l, "goto source code")?;
2412 write!(fmt, "</span>")?; // out-of-band
2413 write!(fmt, "<span class='in-band'>")?;
2414 match self.item.inner {
2415 clean::ModuleItem(ref m) => if m.is_crate {
2416 write!(fmt, "Crate ")?;
2418 write!(fmt, "Module ")?;
2420 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2421 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2422 clean::StructItem(..) => write!(fmt, "Struct ")?,
2423 clean::UnionItem(..) => write!(fmt, "Union ")?,
2424 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2425 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2426 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2427 clean::ProcMacroItem(ref mac) => match mac.kind {
2428 MacroKind::Bang => write!(fmt, "Macro ")?,
2429 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2430 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2431 MacroKind::ProcMacroStub => unreachable!(),
2433 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2434 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2435 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2436 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2437 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2438 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2439 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2441 // We don't generate pages for any other type.
2445 if !self.item.is_primitive() && !self.item.is_keyword() {
2446 let cur = &self.cx.current;
2447 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2448 for (i, component) in cur.iter().enumerate().take(amt) {
2449 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2450 "../".repeat(cur.len() - i - 1),
2454 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2455 self.item.type_(), self.item.name.as_ref().unwrap())?;
2457 write!(fmt, "</span></h1>")?; // in-band
2459 match self.item.inner {
2460 clean::ModuleItem(ref m) =>
2461 item_module(fmt, self.cx, self.item, &m.items),
2462 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2463 item_function(fmt, self.cx, self.item, f),
2464 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2465 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2466 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2467 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2468 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2469 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2470 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2471 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2472 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2473 item_static(fmt, self.cx, self.item, i),
2474 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2475 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2476 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2477 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2478 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2480 // We don't generate pages for any other type.
2487 fn item_path(ty: ItemType, name: &str) -> String {
2489 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2490 _ => format!("{}.{}.html", ty.css_class(), name),
2494 fn full_path(cx: &Context, item: &clean::Item) -> String {
2495 let mut s = cx.current.join("::");
2497 s.push_str(item.name.as_ref().unwrap());
2501 fn shorter<'a>(s: Option<&'a str>) -> String {
2503 Some(s) => s.lines()
2504 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2506 (*line).chars().any(|chr|{
2507 !chr.is_whitespace()
2509 }).collect::<Vec<_>>().join("\n"),
2510 None => String::new()
2515 fn plain_summary_line(s: Option<&str>) -> String {
2516 let line = shorter(s).replace("\n", " ");
2517 markdown::plain_summary_line_full(&line[..], false)
2521 fn plain_summary_line_short(s: Option<&str>) -> String {
2522 let line = shorter(s).replace("\n", " ");
2523 markdown::plain_summary_line_full(&line[..], true)
2526 fn document(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item) -> fmt::Result {
2527 if let Some(ref name) = item.name {
2528 info!("Documenting {}", name);
2530 document_stability(w, cx, item, false)?;
2531 document_full(w, item, cx, "", false)?;
2535 /// Render md_text as markdown.
2536 fn render_markdown(w: &mut fmt::Formatter<'_>,
2539 links: Vec<(String, String)>,
2543 let mut ids = cx.id_map.borrow_mut();
2544 write!(w, "<div class='docblock{}'>{}{}</div>",
2545 if is_hidden { " hidden" } else { "" },
2547 Markdown(md_text, &links, RefCell::new(&mut ids),
2552 w: &mut fmt::Formatter<'_>,
2555 link: AssocItemLink<'_>,
2556 prefix: &str, is_hidden: bool
2558 if let Some(s) = item.doc_value() {
2559 let markdown = if s.contains('\n') {
2560 format!("{} [Read more]({})",
2561 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2563 plain_summary_line(Some(s))
2565 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2566 } else if !prefix.is_empty() {
2567 write!(w, "<div class='docblock{}'>{}</div>",
2568 if is_hidden { " hidden" } else { "" },
2574 fn document_full(w: &mut fmt::Formatter<'_>, item: &clean::Item,
2575 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2576 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2577 debug!("Doc block: =====\n{}\n=====", s);
2578 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2579 } else if !prefix.is_empty() {
2580 write!(w, "<div class='docblock{}'>{}</div>",
2581 if is_hidden { " hidden" } else { "" },
2587 fn document_stability(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
2588 is_hidden: bool) -> fmt::Result {
2589 let stabilities = short_stability(item, cx);
2590 if !stabilities.is_empty() {
2591 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2592 for stability in stabilities {
2593 write!(w, "{}", stability)?;
2595 write!(w, "</div>")?;
2600 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2601 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2604 fn document_non_exhaustive(w: &mut fmt::Formatter<'_>, item: &clean::Item) -> fmt::Result {
2605 if item.is_non_exhaustive() {
2606 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2607 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2610 if item.is_struct() {
2611 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2612 Therefore, non-exhaustive structs cannot be constructed in external crates \
2613 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2614 matched against without a wildcard <code>..</code>; and \
2615 struct update syntax will not work.")?;
2616 } else if item.is_enum() {
2617 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2618 Therefore, when matching against variants of non-exhaustive enums, an \
2619 extra wildcard arm must be added to account for any future variants.")?;
2621 write!(w, "This type will require a wildcard arm in any match statements or \
2625 write!(w, "</div>")?;
2631 fn name_key(name: &str) -> (&str, u64, usize) {
2632 let end = name.bytes()
2633 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2635 // find number at end
2636 let split = name[0..end].bytes()
2637 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2639 // count leading zeroes
2641 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2643 // sort leading zeroes last
2644 let num_zeroes = after_zeroes - split;
2646 match name[split..end].parse() {
2647 Ok(n) => (&name[..split], n, num_zeroes),
2648 Err(_) => (name, 0, num_zeroes),
2652 fn item_module(w: &mut fmt::Formatter<'_>, cx: &Context,
2653 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2654 document(w, cx, item)?;
2656 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2658 // the order of item types in the listing
2659 fn reorder(ty: ItemType) -> u8 {
2661 ItemType::ExternCrate => 0,
2662 ItemType::Import => 1,
2663 ItemType::Primitive => 2,
2664 ItemType::Module => 3,
2665 ItemType::Macro => 4,
2666 ItemType::Struct => 5,
2667 ItemType::Enum => 6,
2668 ItemType::Constant => 7,
2669 ItemType::Static => 8,
2670 ItemType::Trait => 9,
2671 ItemType::Function => 10,
2672 ItemType::Typedef => 12,
2673 ItemType::Union => 13,
2678 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2679 let ty1 = i1.type_();
2680 let ty2 = i2.type_();
2682 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2684 let s1 = i1.stability.as_ref().map(|s| s.level);
2685 let s2 = i2.stability.as_ref().map(|s| s.level);
2687 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2688 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2691 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2692 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2693 name_key(lhs).cmp(&name_key(rhs))
2696 if cx.shared.sort_modules_alphabetically {
2697 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2699 // This call is to remove re-export duplicates in cases such as:
2704 // pub trait Double { fn foo(); }
2708 // pub use foo::bar::*;
2712 // `Double` will appear twice in the generated docs.
2714 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2715 // can be identical even if the elements are different (mostly in imports).
2716 // So in case this is an import, we keep everything by adding a "unique id"
2717 // (which is the position in the vector).
2718 indices.dedup_by_key(|i| (items[*i].def_id,
2719 if items[*i].name.as_ref().is_some() {
2720 Some(full_path(cx, &items[*i]))
2725 if items[*i].is_import() {
2731 debug!("{:?}", indices);
2732 let mut curty = None;
2733 for &idx in &indices {
2734 let myitem = &items[idx];
2735 if myitem.is_stripped() {
2739 let myty = Some(myitem.type_());
2740 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2741 // Put `extern crate` and `use` re-exports in the same section.
2743 } else if myty != curty {
2744 if curty.is_some() {
2745 write!(w, "</table>")?;
2748 let (short, name) = item_ty_to_strs(&myty.unwrap());
2749 write!(w, "<h2 id='{id}' class='section-header'>\
2750 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2751 id = cx.derive_id(short.to_owned()), name = name)?;
2754 match myitem.inner {
2755 clean::ExternCrateItem(ref name, ref src) => {
2756 use crate::html::format::HRef;
2760 write!(w, "<tr><td><code>{}extern crate {} as {};",
2761 VisSpace(&myitem.visibility),
2762 HRef::new(myitem.def_id, src),
2766 write!(w, "<tr><td><code>{}extern crate {};",
2767 VisSpace(&myitem.visibility),
2768 HRef::new(myitem.def_id, name))?
2771 write!(w, "</code></td></tr>")?;
2774 clean::ImportItem(ref import) => {
2775 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2776 VisSpace(&myitem.visibility), *import)?;
2780 if myitem.name.is_none() { continue }
2782 let unsafety_flag = match myitem.inner {
2783 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2784 if func.header.unsafety == hir::Unsafety::Unsafe => {
2785 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2790 let stab = myitem.stability_class();
2791 let add = if stab.is_some() {
2797 let doc_value = myitem.doc_value().unwrap_or("");
2799 <tr class='{stab}{add}module-item'>\
2800 <td><a class=\"{class}\" href=\"{href}\" \
2801 title='{title}'>{name}</a>{unsafety_flag}</td>\
2802 <td class='docblock-short'>{stab_tags}{docs}</td>\
2804 name = *myitem.name.as_ref().unwrap(),
2805 stab_tags = stability_tags(myitem),
2806 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2807 class = myitem.type_(),
2809 stab = stab.unwrap_or_else(|| String::new()),
2810 unsafety_flag = unsafety_flag,
2811 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2812 title = [full_path(cx, myitem), myitem.type_().to_string()]
2814 .filter_map(|s| if !s.is_empty() {
2819 .collect::<Vec<_>>()
2826 if curty.is_some() {
2827 write!(w, "</table>")?;
2832 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2834 fn stability_tags(item: &clean::Item) -> String {
2835 let mut tags = String::new();
2837 fn tag_html(class: &str, contents: &str) -> String {
2838 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2841 // The trailing space after each tag is to space it properly against the rest of the docs.
2842 if item.deprecation().is_some() {
2843 let mut message = "Deprecated";
2844 if let Some(ref stab) = item.stability {
2845 if let Some(ref depr) = stab.deprecation {
2846 if let Some(ref since) = depr.since {
2847 if !stability::deprecation_in_effect(&since) {
2848 message = "Deprecation planned";
2853 tags += &tag_html("deprecated", message);
2856 if let Some(stab) = item
2859 .filter(|s| s.level == stability::Unstable)
2861 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2862 tags += &tag_html("internal", "Internal");
2864 tags += &tag_html("unstable", "Experimental");
2868 if let Some(ref cfg) = item.attrs.cfg {
2869 tags += &tag_html("portability", &cfg.render_short_html());
2875 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2877 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2878 let mut stability = vec![];
2879 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2881 if let Some(Deprecation { note, since }) = &item.deprecation() {
2882 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2883 // but only display the future-deprecation messages for #[rustc_deprecated].
2884 let mut message = if let Some(since) = since {
2885 format!("Deprecated since {}", Escape(since))
2887 String::from("Deprecated")
2889 if let Some(ref stab) = item.stability {
2890 if let Some(ref depr) = stab.deprecation {
2891 if let Some(ref since) = depr.since {
2892 if !stability::deprecation_in_effect(&since) {
2893 message = format!("Deprecating in {}", Escape(&since));
2899 if let Some(note) = note {
2900 let mut ids = cx.id_map.borrow_mut();
2901 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2902 message.push_str(&format!(": {}", html));
2904 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2907 if let Some(stab) = item
2910 .filter(|stab| stab.level == stability::Unstable)
2912 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2914 let mut message = if is_rustc_private {
2915 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2917 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2921 if let Some(feature) = stab.feature.as_ref() {
2922 let mut feature = format!("<code>{}</code>", Escape(&feature));
2923 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2924 feature.push_str(&format!(
2925 " <a href=\"{url}{issue}\">#{issue}</a>",
2931 message.push_str(&format!(" ({})", feature));
2934 if let Some(unstable_reason) = &stab.unstable_reason {
2935 // Provide a more informative message than the compiler help.
2936 let unstable_reason = if is_rustc_private {
2937 "This crate is being loaded from the sysroot, a permanently unstable location \
2938 for private compiler dependencies. It is not intended for general use. Prefer \
2939 using a public version of this crate from \
2940 [crates.io](https://crates.io) via [`Cargo.toml`]\
2941 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2946 let mut ids = cx.id_map.borrow_mut();
2948 "<details><summary>{}</summary>{}</details>",
2950 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2954 let class = if is_rustc_private {
2959 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2962 if let Some(ref cfg) = item.attrs.cfg {
2963 stability.push(format!(
2964 "<div class='stab portability'>{}</div>",
2965 cfg.render_long_html()
2972 fn item_constant(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2973 c: &clean::Constant) -> fmt::Result {
2974 write!(w, "<pre class='rust const'>")?;
2975 render_attributes(w, it)?;
2976 write!(w, "{vis}const \
2977 {name}: {typ}</pre>",
2978 vis = VisSpace(&it.visibility),
2979 name = it.name.as_ref().unwrap(),
2984 fn item_static(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2985 s: &clean::Static) -> fmt::Result {
2986 write!(w, "<pre class='rust static'>")?;
2987 render_attributes(w, it)?;
2988 write!(w, "{vis}static {mutability}\
2989 {name}: {typ}</pre>",
2990 vis = VisSpace(&it.visibility),
2991 mutability = MutableSpace(s.mutability),
2992 name = it.name.as_ref().unwrap(),
2997 fn item_function(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2998 f: &clean::Function) -> fmt::Result {
2999 let header_len = format!(
3000 "{}{}{}{}{:#}fn {}{:#}",
3001 VisSpace(&it.visibility),
3002 ConstnessSpace(f.header.constness),
3003 UnsafetySpace(f.header.unsafety),
3004 AsyncSpace(f.header.asyncness),
3005 AbiSpace(f.header.abi),
3006 it.name.as_ref().unwrap(),
3009 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
3010 render_attributes(w, it)?;
3012 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
3013 {name}{generics}{decl}{where_clause}</pre>",
3014 vis = VisSpace(&it.visibility),
3015 constness = ConstnessSpace(f.header.constness),
3016 unsafety = UnsafetySpace(f.header.unsafety),
3017 asyncness = AsyncSpace(f.header.asyncness),
3018 abi = AbiSpace(f.header.abi),
3019 name = it.name.as_ref().unwrap(),
3020 generics = f.generics,
3021 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
3026 asyncness: f.header.asyncness,
3031 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter<'_>,
3032 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
3033 // If there's already another implementor that has the same abbridged name, use the
3034 // full path, for example in `std::iter::ExactSizeIterator`
3035 let use_absolute = match implementor.inner_impl().for_ {
3036 clean::ResolvedPath { ref path, is_generic: false, .. } |
3037 clean::BorrowedRef {
3038 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3040 } => implementor_dups[path.last_name()].1,
3043 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3044 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
3048 fn render_impls(cx: &Context, w: &mut fmt::Formatter<'_>,
3050 containing_item: &clean::Item) -> fmt::Result {
3052 let did = i.trait_did().unwrap();
3053 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3054 render_impl(w, cx, i, assoc_link,
3055 RenderMode::Normal, containing_item.stable_since(), true, None)?;
3060 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3061 let mut bounds = String::new();
3062 if !t_bounds.is_empty() {
3064 bounds.push_str(": ");
3066 for (i, p) in t_bounds.iter().enumerate() {
3068 bounds.push_str(" + ");
3070 bounds.push_str(&(*p).to_string());
3076 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3077 let lhs = format!("{}", lhs.inner_impl());
3078 let rhs = format!("{}", rhs.inner_impl());
3080 // lhs and rhs are formatted as HTML, which may be unnecessary
3081 name_key(&lhs).cmp(&name_key(&rhs))
3085 w: &mut fmt::Formatter<'_>,
3090 let bounds = bounds(&t.bounds, false);
3091 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3092 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3093 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3094 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3096 // Output the trait definition
3097 wrap_into_docblock(w, |w| {
3098 write!(w, "<pre class='rust trait'>")?;
3099 render_attributes(w, it)?;
3100 write!(w, "{}{}{}trait {}{}{}",
3101 VisSpace(&it.visibility),
3102 UnsafetySpace(t.unsafety),
3103 if t.is_auto { "auto " } else { "" },
3104 it.name.as_ref().unwrap(),
3108 if !t.generics.where_predicates.is_empty() {
3109 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3114 if t.items.is_empty() {
3115 write!(w, "{{ }}")?;
3117 // FIXME: we should be using a derived_id for the Anchors here
3121 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3124 if !types.is_empty() && !consts.is_empty() {
3129 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3132 if !consts.is_empty() && !required.is_empty() {
3135 for (pos, m) in required.iter().enumerate() {
3137 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3140 if pos < required.len() - 1 {
3141 write!(w, "<div class='item-spacer'></div>")?;
3144 if !required.is_empty() && !provided.is_empty() {
3147 for (pos, m) in provided.iter().enumerate() {
3149 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3151 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3152 write!(w, ",\n {{ ... }}\n")?;
3155 write!(w, " {{ ... }}\n")?;
3158 if pos < provided.len() - 1 {
3159 write!(w, "<div class='item-spacer'></div>")?;
3167 // Trait documentation
3168 document(w, cx, it)?;
3170 fn write_small_section_header(
3171 w: &mut fmt::Formatter<'_>,
3174 extra_content: &str,
3177 <h2 id='{0}' class='small-section-header'>\
3178 {1}<a href='#{0}' class='anchor'></a>\
3179 </h2>{2}", id, title, extra_content)
3182 fn write_loading_content(w: &mut fmt::Formatter<'_>, extra_content: &str) -> fmt::Result {
3183 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3186 fn trait_item(w: &mut fmt::Formatter<'_>, cx: &Context, m: &clean::Item, t: &clean::Item)
3188 let name = m.name.as_ref().unwrap();
3189 let item_type = m.type_();
3190 let id = cx.derive_id(format!("{}.{}", item_type, name));
3191 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3192 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3193 extra = render_spotlight_traits(m)?,
3196 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3197 write!(w, "</code>")?;
3198 render_stability_since(w, m, t)?;
3199 write!(w, "</h3>")?;
3200 document(w, cx, m)?;
3204 if !types.is_empty() {
3205 write_small_section_header(w, "associated-types", "Associated Types",
3206 "<div class='methods'>")?;
3208 trait_item(w, cx, *t, it)?;
3210 write_loading_content(w, "</div>")?;
3213 if !consts.is_empty() {
3214 write_small_section_header(w, "associated-const", "Associated Constants",
3215 "<div class='methods'>")?;
3217 trait_item(w, cx, *t, it)?;
3219 write_loading_content(w, "</div>")?;
3222 // Output the documentation for each function individually
3223 if !required.is_empty() {
3224 write_small_section_header(w, "required-methods", "Required methods",
3225 "<div class='methods'>")?;
3226 for m in &required {
3227 trait_item(w, cx, *m, it)?;
3229 write_loading_content(w, "</div>")?;
3231 if !provided.is_empty() {
3232 write_small_section_header(w, "provided-methods", "Provided methods",
3233 "<div class='methods'>")?;
3234 for m in &provided {
3235 trait_item(w, cx, *m, it)?;
3237 write_loading_content(w, "</div>")?;
3240 // If there are methods directly on this trait object, render them here.
3241 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3243 let cache = cache();
3245 let mut synthetic_types = Vec::new();
3247 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3248 // The DefId is for the first Type found with that name. The bool is
3249 // if any Types with the same name but different DefId have been found.
3250 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3251 for implementor in implementors {
3252 match implementor.inner_impl().for_ {
3253 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3254 clean::BorrowedRef {
3255 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3258 let &mut (prev_did, ref mut has_duplicates) =
3259 implementor_dups.entry(path.last_name()).or_insert((did, false));
3260 if prev_did != did {
3261 *has_duplicates = true;
3268 let (local, foreign) = implementors.iter()
3269 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3270 .map_or(true, |d| cache.paths.contains_key(&d)));
3273 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3274 .partition(|i| i.inner_impl().synthetic);
3276 synthetic.sort_by(compare_impl);
3277 concrete.sort_by(compare_impl);
3279 if !foreign.is_empty() {
3280 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3282 for implementor in foreign {
3283 let assoc_link = AssocItemLink::GotoSource(
3284 implementor.impl_item.def_id,
3285 &implementor.inner_impl().provided_trait_methods
3287 render_impl(w, cx, &implementor, assoc_link,
3288 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3291 write_loading_content(w, "")?;
3294 write_small_section_header(w, "implementors", "Implementors",
3295 "<div class='item-list' id='implementors-list'>")?;
3296 for implementor in concrete {
3297 render_implementor(cx, implementor, w, &implementor_dups)?;
3299 write_loading_content(w, "</div>")?;
3302 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3303 "<div class='item-list' id='synthetic-implementors-list'>")?;
3304 for implementor in synthetic {
3305 synthetic_types.extend(
3306 collect_paths_for_type(implementor.inner_impl().for_.clone())
3308 render_implementor(cx, implementor, w, &implementor_dups)?;
3310 write_loading_content(w, "</div>")?;
3313 // even without any implementations to write in, we still want the heading and list, so the
3314 // implementors javascript file pulled in below has somewhere to write the impls into
3315 write_small_section_header(w, "implementors", "Implementors",
3316 "<div class='item-list' id='implementors-list'>")?;
3317 write_loading_content(w, "</div>")?;
3320 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3321 "<div class='item-list' id='synthetic-implementors-list'>")?;
3322 write_loading_content(w, "</div>")?;
3325 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3326 as_json(&synthetic_types))?;
3328 write!(w, r#"<script type="text/javascript" async
3329 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3331 root_path = vec![".."; cx.current.len()].join("/"),
3332 path = if it.def_id.is_local() {
3333 cx.current.join("/")
3335 let (ref path, _) = cache.external_paths[&it.def_id];
3336 path[..path.len() - 1].join("/")
3338 ty = it.type_().css_class(),
3339 name = *it.name.as_ref().unwrap())?;
3343 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
3344 use crate::html::item_type::ItemType::*;
3346 let name = it.name.as_ref().unwrap();
3347 let ty = match it.type_() {
3348 Typedef | AssociatedType => AssociatedType,
3352 let anchor = format!("#{}.{}", ty, name);
3354 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3355 AssocItemLink::Anchor(None) => anchor,
3356 AssocItemLink::GotoSource(did, _) => {
3357 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3362 fn assoc_const(w: &mut fmt::Formatter<'_>,
3365 _default: Option<&String>,
3366 link: AssocItemLink<'_>) -> fmt::Result {
3367 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3368 VisSpace(&it.visibility),
3369 naive_assoc_href(it, link),
3370 it.name.as_ref().unwrap(),
3375 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3376 bounds: &[clean::GenericBound],
3377 default: Option<&clean::Type>,
3378 link: AssocItemLink<'_>) -> fmt::Result {
3379 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3380 naive_assoc_href(it, link),
3381 it.name.as_ref().unwrap())?;
3382 if !bounds.is_empty() {
3383 write!(w, ": {}", GenericBounds(bounds))?
3385 if let Some(default) = default {
3386 write!(w, " = {}", default)?;
3391 fn render_stability_since_raw<'a, T: fmt::Write>(
3393 ver: Option<&'a str>,
3394 containing_ver: Option<&'a str>,
3396 if let Some(v) = ver {
3397 if containing_ver != ver && v.len() > 0 {
3398 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3404 fn render_stability_since(w: &mut fmt::Formatter<'_>,
3406 containing_item: &clean::Item) -> fmt::Result {
3407 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3410 fn render_assoc_item(w: &mut fmt::Formatter<'_>,
3412 link: AssocItemLink<'_>,
3413 parent: ItemType) -> fmt::Result {
3414 fn method(w: &mut fmt::Formatter<'_>,
3416 header: hir::FnHeader,
3417 g: &clean::Generics,
3419 link: AssocItemLink<'_>,
3422 let name = meth.name.as_ref().unwrap();
3423 let anchor = format!("#{}.{}", meth.type_(), name);
3424 let href = match link {
3425 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3426 AssocItemLink::Anchor(None) => anchor,
3427 AssocItemLink::GotoSource(did, provided_methods) => {
3428 // We're creating a link from an impl-item to the corresponding
3429 // trait-item and need to map the anchored type accordingly.
3430 let ty = if provided_methods.contains(name) {
3436 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3439 let mut header_len = format!(
3440 "{}{}{}{}{}{:#}fn {}{:#}",
3441 VisSpace(&meth.visibility),
3442 ConstnessSpace(header.constness),
3443 UnsafetySpace(header.unsafety),
3444 AsyncSpace(header.asyncness),
3445 DefaultSpace(meth.is_default()),
3446 AbiSpace(header.abi),
3450 let (indent, end_newline) = if parent == ItemType::Trait {
3456 render_attributes(w, meth)?;
3457 write!(w, "{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3458 {generics}{decl}{where_clause}",
3459 VisSpace(&meth.visibility),
3460 ConstnessSpace(header.constness),
3461 UnsafetySpace(header.unsafety),
3462 AsyncSpace(header.asyncness),
3463 DefaultSpace(meth.is_default()),
3464 AbiSpace(header.abi),
3472 asyncness: header.asyncness,
3474 where_clause = WhereClause {
3481 clean::StrippedItem(..) => Ok(()),
3482 clean::TyMethodItem(ref m) => {
3483 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3485 clean::MethodItem(ref m) => {
3486 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3488 clean::AssociatedConstItem(ref ty, ref default) => {
3489 assoc_const(w, item, ty, default.as_ref(), link)
3491 clean::AssociatedTypeItem(ref bounds, ref default) => {
3492 assoc_type(w, item, bounds, default.as_ref(), link)
3494 _ => panic!("render_assoc_item called on non-associated-item")
3498 fn item_struct(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3499 s: &clean::Struct) -> fmt::Result {
3500 wrap_into_docblock(w, |w| {
3501 write!(w, "<pre class='rust struct'>")?;
3502 render_attributes(w, it)?;
3513 document(w, cx, it)?;
3514 let mut fields = s.fields.iter().filter_map(|f| {
3516 clean::StructFieldItem(ref ty) => Some((f, ty)),
3520 if let doctree::Plain = s.struct_type {
3521 if fields.peek().is_some() {
3522 write!(w, "<h2 id='fields' class='fields small-section-header'>
3523 Fields{}<a href='#fields' class='anchor'></a></h2>",
3524 document_non_exhaustive_header(it))?;
3525 document_non_exhaustive(w, it)?;
3526 for (field, ty) in fields {
3527 let id = cx.derive_id(format!("{}.{}",
3528 ItemType::StructField,
3529 field.name.as_ref().unwrap()));
3530 let ns_id = cx.derive_id(format!("{}.{}",
3531 field.name.as_ref().unwrap(),
3532 ItemType::StructField.name_space()));
3533 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3534 <a href=\"#{id}\" class=\"anchor field\"></a>\
3535 <code id=\"{ns_id}\">{name}: {ty}</code>\
3537 item_type = ItemType::StructField,
3540 name = field.name.as_ref().unwrap(),
3542 document(w, cx, field)?;
3546 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3549 fn item_union(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3550 s: &clean::Union) -> fmt::Result {
3551 wrap_into_docblock(w, |w| {
3552 write!(w, "<pre class='rust union'>")?;
3553 render_attributes(w, it)?;
3563 document(w, cx, it)?;
3564 let mut fields = s.fields.iter().filter_map(|f| {
3566 clean::StructFieldItem(ref ty) => Some((f, ty)),
3570 if fields.peek().is_some() {
3571 write!(w, "<h2 id='fields' class='fields small-section-header'>
3572 Fields<a href='#fields' class='anchor'></a></h2>")?;
3573 for (field, ty) in fields {
3574 let name = field.name.as_ref().expect("union field name");
3575 let id = format!("{}.{}", ItemType::StructField, name);
3576 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3577 <a href=\"#{id}\" class=\"anchor field\"></a>\
3578 <code>{name}: {ty}</code>\
3582 shortty = ItemType::StructField,
3584 if let Some(stability_class) = field.stability_class() {
3585 write!(w, "<span class='stab {stab}'></span>",
3586 stab = stability_class)?;
3588 document(w, cx, field)?;
3591 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3594 fn item_enum(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3595 e: &clean::Enum) -> fmt::Result {
3596 wrap_into_docblock(w, |w| {
3597 write!(w, "<pre class='rust enum'>")?;
3598 render_attributes(w, it)?;
3599 write!(w, "{}enum {}{}{}",
3600 VisSpace(&it.visibility),
3601 it.name.as_ref().unwrap(),
3603 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3604 if e.variants.is_empty() && !e.variants_stripped {
3605 write!(w, " {{}}")?;
3607 write!(w, " {{\n")?;
3608 for v in &e.variants {
3610 let name = v.name.as_ref().unwrap();
3612 clean::VariantItem(ref var) => {
3614 clean::VariantKind::CLike => write!(w, "{}", name)?,
3615 clean::VariantKind::Tuple(ref tys) => {
3616 write!(w, "{}(", name)?;
3617 for (i, ty) in tys.iter().enumerate() {
3619 write!(w, ", ")?
3621 write!(w, "{}", *ty)?;
3625 clean::VariantKind::Struct(ref s) => {
3641 if e.variants_stripped {
3642 write!(w, " // some variants omitted\n")?;
3649 document(w, cx, it)?;
3650 if !e.variants.is_empty() {
3651 write!(w, "<h2 id='variants' class='variants small-section-header'>
3652 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3653 document_non_exhaustive_header(it))?;
3654 document_non_exhaustive(w, it)?;
3655 for variant in &e.variants {
3656 let id = cx.derive_id(format!("{}.{}",
3658 variant.name.as_ref().unwrap()));
3659 let ns_id = cx.derive_id(format!("{}.{}",
3660 variant.name.as_ref().unwrap(),
3661 ItemType::Variant.name_space()));
3662 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3663 <a href=\"#{id}\" class=\"anchor field\"></a>\
3664 <code id='{ns_id}'>{name}",
3667 name = variant.name.as_ref().unwrap())?;
3668 if let clean::VariantItem(ref var) = variant.inner {
3669 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3671 for (i, ty) in tys.iter().enumerate() {
3673 write!(w, ", ")?;
3675 write!(w, "{}", *ty)?;
3680 write!(w, "</code></span>")?;
3681 document(w, cx, variant)?;
3683 use crate::clean::{Variant, VariantKind};
3684 if let clean::VariantItem(Variant {
3685 kind: VariantKind::Struct(ref s)
3686 }) = variant.inner {
3687 let variant_id = cx.derive_id(format!("{}.{}.fields",
3689 variant.name.as_ref().unwrap()));
3690 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3692 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3693 name = variant.name.as_ref().unwrap())?;
3694 for field in &s.fields {
3695 use crate::clean::StructFieldItem;
3696 if let StructFieldItem(ref ty) = field.inner {
3697 let id = cx.derive_id(format!("variant.{}.field.{}",
3698 variant.name.as_ref().unwrap(),
3699 field.name.as_ref().unwrap()));
3700 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3701 variant.name.as_ref().unwrap(),
3702 ItemType::Variant.name_space(),
3703 field.name.as_ref().unwrap(),
3704 ItemType::StructField.name_space()));
3705 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3706 <a href=\"#{id}\" class=\"anchor field\"></a>\
3707 <code id='{ns_id}'>{f}: {t}\
3711 f = field.name.as_ref().unwrap(),
3713 document(w, cx, field)?;
3716 write!(w, "</div></span>")?;
3718 render_stability_since(w, variant, it)?;
3721 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3725 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3726 let path = attr.path.to_string();
3730 } else if let Some(v) = attr.value_str() {
3731 Some(format!("{} = {:?}", path, v.as_str()))
3732 } else if let Some(values) = attr.meta_item_list() {
3733 let display: Vec<_> = values.iter().filter_map(|attr| {
3734 attr.meta_item().and_then(|mi| render_attribute(mi))
3737 if display.len() > 0 {
3738 Some(format!("{}({})", path, display.join(", ")))
3747 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3754 "unsafe_destructor_blind_to_params",
3758 fn render_attributes(w: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
3759 let mut attrs = String::new();
3761 for attr in &it.attrs.other_attrs {
3762 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty().get()) {
3765 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3766 attrs.push_str(&format!("#[{}]\n", s));
3769 if attrs.len() > 0 {
3770 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3775 fn render_struct(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3776 g: Option<&clean::Generics>,
3777 ty: doctree::StructType,
3778 fields: &[clean::Item],
3780 structhead: bool) -> fmt::Result {
3782 VisSpace(&it.visibility),
3783 if structhead {"struct "} else {""},
3784 it.name.as_ref().unwrap())?;
3785 if let Some(g) = g {
3790 if let Some(g) = g {
3791 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3793 let mut has_visible_fields = false;
3795 for field in fields {
3796 if let clean::StructFieldItem(ref ty) = field.inner {
3797 write!(w, "\n{} {}{}: {},",
3799 VisSpace(&field.visibility),
3800 field.name.as_ref().unwrap(),
3802 has_visible_fields = true;
3806 if has_visible_fields {
3807 if it.has_stripped_fields().unwrap() {
3808 write!(w, "\n{} // some fields omitted", tab)?;
3810 write!(w, "\n{}", tab)?;
3811 } else if it.has_stripped_fields().unwrap() {
3812 // If there are no visible fields we can just display
3813 // `{ /* fields omitted */ }` to save space.
3814 write!(w, " /* fields omitted */ ")?;
3820 for (i, field) in fields.iter().enumerate() {
3825 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3828 clean::StructFieldItem(ref ty) => {
3829 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3835 if let Some(g) = g {
3836 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3841 // Needed for PhantomData.
3842 if let Some(g) = g {
3843 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3851 fn render_union(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3852 g: Option<&clean::Generics>,
3853 fields: &[clean::Item],
3855 structhead: bool) -> fmt::Result {
3857 VisSpace(&it.visibility),
3858 if structhead {"union "} else {""},
3859 it.name.as_ref().unwrap())?;
3860 if let Some(g) = g {
3861 write!(w, "{}", g)?;
3862 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3865 write!(w, " {{\n{}", tab)?;
3866 for field in fields {
3867 if let clean::StructFieldItem(ref ty) = field.inner {
3868 write!(w, " {}{}: {},\n{}",
3869 VisSpace(&field.visibility),
3870 field.name.as_ref().unwrap(),
3876 if it.has_stripped_fields().unwrap() {
3877 write!(w, " // some fields omitted\n{}", tab)?;
3883 #[derive(Copy, Clone)]
3884 enum AssocItemLink<'a> {
3885 Anchor(Option<&'a str>),
3886 GotoSource(DefId, &'a FxHashSet<String>),
3889 impl<'a> AssocItemLink<'a> {
3890 fn anchor(&self, id: &'a String) -> Self {
3892 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3893 ref other => *other,
3898 enum AssocItemRender<'a> {
3900 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3903 #[derive(Copy, Clone, PartialEq)]
3906 ForDeref { mut_: bool },
3909 fn render_assoc_items(w: &mut fmt::Formatter<'_>,
3911 containing_item: &clean::Item,
3913 what: AssocItemRender<'_>) -> fmt::Result {
3915 let v = match c.impls.get(&it) {
3917 None => return Ok(()),
3919 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3920 i.inner_impl().trait_.is_none()
3922 if !non_trait.is_empty() {
3923 let render_mode = match what {
3924 AssocItemRender::All => {
3926 <h2 id='methods' class='small-section-header'>\
3927 Methods<a href='#methods' class='anchor'></a>\
3932 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3934 <h2 id='deref-methods' class='small-section-header'>\
3935 Methods from {}<Target = {}>\
3936 <a href='#deref-methods' class='anchor'></a>\
3939 RenderMode::ForDeref { mut_: deref_mut_ }
3942 for i in &non_trait {
3943 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3944 containing_item.stable_since(), true, None)?;
3947 if let AssocItemRender::DerefFor { .. } = what {
3950 if !traits.is_empty() {
3951 let deref_impl = traits.iter().find(|t| {
3952 t.inner_impl().trait_.def_id() == c.deref_trait_did
3954 if let Some(impl_) = deref_impl {
3955 let has_deref_mut = traits.iter().find(|t| {
3956 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3958 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3961 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3963 .partition(|t| t.inner_impl().synthetic);
3964 let (blanket_impl, concrete) = concrete
3966 .partition(|t| t.inner_impl().blanket_impl.is_some());
3968 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3970 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3971 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3972 render_impls(self.0, fmt, &self.1, self.2)
3976 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3977 if !impls.is_empty() {
3979 <h2 id='implementations' class='small-section-header'>\
3980 Trait Implementations<a href='#implementations' class='anchor'></a>\
3982 <div id='implementations-list'>{}</div>", impls)?;
3985 if !synthetic.is_empty() {
3987 <h2 id='synthetic-implementations' class='small-section-header'>\
3988 Auto Trait Implementations\
3989 <a href='#synthetic-implementations' class='anchor'></a>\
3991 <div id='synthetic-implementations-list'>\
3993 render_impls(cx, w, &synthetic, containing_item)?;
3994 write!(w, "</div>")?;
3997 if !blanket_impl.is_empty() {
3999 <h2 id='blanket-implementations' class='small-section-header'>\
4000 Blanket Implementations\
4001 <a href='#blanket-implementations' class='anchor'></a>\
4003 <div id='blanket-implementations-list'>\
4005 render_impls(cx, w, &blanket_impl, containing_item)?;
4006 write!(w, "</div>")?;
4012 fn render_deref_methods(w: &mut fmt::Formatter<'_>, cx: &Context, impl_: &Impl,
4013 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
4014 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
4015 let target = impl_.inner_impl().items.iter().filter_map(|item| {
4017 clean::TypedefItem(ref t, true) => Some(&t.type_),
4020 }).next().expect("Expected associated type binding");
4021 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
4022 deref_mut_: deref_mut };
4023 if let Some(did) = target.def_id() {
4024 render_assoc_items(w, cx, container_item, did, what)
4026 if let Some(prim) = target.primitive_type() {
4027 if let Some(&did) = cache().primitive_locations.get(&prim) {
4028 render_assoc_items(w, cx, container_item, did, what)?;
4035 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
4036 let self_type_opt = match item.inner {
4037 clean::MethodItem(ref method) => method.decl.self_type(),
4038 clean::TyMethodItem(ref method) => method.decl.self_type(),
4042 if let Some(self_ty) = self_type_opt {
4043 let (by_mut_ref, by_box, by_value) = match self_ty {
4044 SelfTy::SelfBorrowed(_, mutability) |
4045 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4046 (mutability == Mutability::Mutable, false, false)
4048 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4049 (false, Some(did) == cache().owned_box_did, false)
4051 SelfTy::SelfValue => (false, false, true),
4052 _ => (false, false, false),
4055 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4061 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4062 let mut out = String::new();
4065 clean::FunctionItem(clean::Function { ref decl, .. }) |
4066 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4067 clean::MethodItem(clean::Method { ref decl, .. }) |
4068 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4069 out = spotlight_decl(decl)?;
4077 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4078 let mut out = String::new();
4079 let mut trait_ = String::new();
4081 if let Some(did) = decl.output.def_id() {
4083 if let Some(impls) = c.impls.get(&did) {
4085 let impl_ = i.inner_impl();
4086 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4089 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4090 <code class=\"content\">",
4092 trait_.push_str(&impl_.for_.to_string());
4095 //use the "where" class here to make it small
4096 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4097 let t_did = impl_.trait_.def_id().unwrap();
4098 for it in &impl_.items {
4099 if let clean::TypedefItem(ref tydef, _) = it.inner {
4100 out.push_str("<span class=\"where fmt-newline\"> ");
4101 assoc_type(&mut out, it, &[],
4103 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4104 out.push_str(";</span>");
4112 if !out.is_empty() {
4113 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4114 <span class='tooltiptext'>Important traits for {}</span></div>\
4115 <div class=\"content hidden\">",
4117 out.push_str("</code></div></div>");
4123 fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
4124 render_mode: RenderMode, outer_version: Option<&str>,
4125 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4126 if render_mode == RenderMode::Normal {
4127 let id = cx.derive_id(match i.inner_impl().trait_ {
4128 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4129 None => "impl".to_string(),
4131 if let Some(use_absolute) = use_absolute {
4132 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4133 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4135 for it in &i.inner_impl().items {
4136 if let clean::TypedefItem(ref tydef, _) = it.inner {
4137 write!(w, "<span class=\"where fmt-newline\"> ")?;
4138 assoc_type(w, it, &vec![], Some(&tydef.type_),
4139 AssocItemLink::Anchor(None))?;
4140 write!(w, ";</span>")?;
4144 write!(w, "</code>")?;
4146 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4150 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4151 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4152 render_stability_since_raw(w, since, outer_version)?;
4153 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4154 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4155 l, "goto source code")?;
4157 write!(w, "</h3>")?;
4158 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4159 let mut ids = cx.id_map.borrow_mut();
4160 write!(w, "<div class='docblock'>{}</div>",
4161 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4165 fn doc_impl_item(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
4166 link: AssocItemLink<'_>, render_mode: RenderMode,
4167 is_default_item: bool, outer_version: Option<&str>,
4168 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4169 let item_type = item.type_();
4170 let name = item.name.as_ref().unwrap();
4172 let render_method_item: bool = match render_mode {
4173 RenderMode::Normal => true,
4174 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4177 let (is_hidden, extra_class) = if trait_.is_none() ||
4178 item.doc_value().is_some() ||
4179 item.inner.is_associated() {
4185 clean::MethodItem(clean::Method { ref decl, .. }) |
4186 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4187 // Only render when the method is not static or we allow static methods
4188 if render_method_item {
4189 let id = cx.derive_id(format!("{}.{}", item_type, name));
4190 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4191 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4192 write!(w, "{}", spotlight_decl(decl)?)?;
4193 write!(w, "<code id='{}'>", ns_id)?;
4194 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4195 write!(w, "</code>")?;
4196 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4197 if let Some(l) = (Item { cx, item }).src_href() {
4198 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4199 l, "goto source code")?;
4201 write!(w, "</h4>")?;
4204 clean::TypedefItem(ref tydef, _) => {
4205 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, 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_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4210 write!(w, "</code></h4>")?;
4212 clean::AssociatedConstItem(ref ty, ref default) => {
4213 let id = cx.derive_id(format!("{}.{}", item_type, name));
4214 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4215 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4216 write!(w, "<code id='{}'>", ns_id)?;
4217 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4218 write!(w, "</code>")?;
4219 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4220 if let Some(l) = (Item { cx, item }).src_href() {
4221 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4222 l, "goto source code")?;
4224 write!(w, "</h4>")?;
4226 clean::AssociatedTypeItem(ref bounds, ref default) => {
4227 let id = cx.derive_id(format!("{}.{}", item_type, name));
4228 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4229 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4230 write!(w, "<code id='{}'>", ns_id)?;
4231 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4232 write!(w, "</code></h4>")?;
4234 clean::StrippedItem(..) => return Ok(()),
4235 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4238 if render_method_item || render_mode == RenderMode::Normal {
4239 if !is_default_item {
4240 if let Some(t) = trait_ {
4241 // The trait item may have been stripped so we might not
4242 // find any documentation or stability for it.
4243 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4244 // We need the stability of the item from the trait
4245 // because impls can't have a stability.
4246 document_stability(w, cx, it, is_hidden)?;
4247 if item.doc_value().is_some() {
4248 document_full(w, item, cx, "", is_hidden)?;
4249 } else if show_def_docs {
4250 // In case the item isn't documented,
4251 // provide short documentation from the trait.
4252 document_short(w, cx, it, link, "", is_hidden)?;
4256 document_stability(w, cx, item, is_hidden)?;
4258 document_full(w, item, cx, "", is_hidden)?;
4262 document_stability(w, cx, item, is_hidden)?;
4264 document_short(w, cx, item, link, "", is_hidden)?;
4271 let traits = &cache().traits;
4272 let trait_ = i.trait_did().map(|did| &traits[&did]);
4274 write!(w, "<div class='impl-items'>")?;
4275 for trait_item in &i.inner_impl().items {
4276 doc_impl_item(w, cx, trait_item, link, render_mode,
4277 false, outer_version, trait_, show_def_docs)?;
4280 fn render_default_items(w: &mut fmt::Formatter<'_>,
4284 render_mode: RenderMode,
4285 outer_version: Option<&str>,
4286 show_def_docs: bool) -> fmt::Result {
4287 for trait_item in &t.items {
4288 let n = trait_item.name.clone();
4289 if i.items.iter().find(|m| m.name == n).is_some() {
4292 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4293 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4295 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4296 outer_version, None, show_def_docs)?;
4301 // If we've implemented a trait, then also emit documentation for all
4302 // default items which weren't overridden in the implementation block.
4303 if let Some(t) = trait_ {
4304 render_default_items(w, cx, t, &i.inner_impl(),
4305 render_mode, outer_version, show_def_docs)?;
4307 write!(w, "</div>")?;
4312 fn item_existential(
4313 w: &mut fmt::Formatter<'_>,
4316 t: &clean::Existential,
4318 write!(w, "<pre class='rust existential'>")?;
4319 render_attributes(w, it)?;
4320 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4321 it.name.as_ref().unwrap(),
4323 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4324 bounds = bounds(&t.bounds, false))?;
4326 document(w, cx, it)?;
4328 // Render any items associated directly to this alias, as otherwise they
4329 // won't be visible anywhere in the docs. It would be nice to also show
4330 // associated items from the aliased type (see discussion in #32077), but
4331 // we need #14072 to make sense of the generics.
4332 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4335 fn item_trait_alias(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4336 t: &clean::TraitAlias) -> fmt::Result {
4337 write!(w, "<pre class='rust trait-alias'>")?;
4338 render_attributes(w, it)?;
4339 write!(w, "trait {}{}{} = {};</pre>",
4340 it.name.as_ref().unwrap(),
4342 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4343 bounds(&t.bounds, true))?;
4345 document(w, cx, it)?;
4347 // Render any items associated directly to this alias, as otherwise they
4348 // won't be visible anywhere in the docs. It would be nice to also show
4349 // associated items from the aliased type (see discussion in #32077), but
4350 // we need #14072 to make sense of the generics.
4351 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4354 fn item_typedef(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4355 t: &clean::Typedef) -> fmt::Result {
4356 write!(w, "<pre class='rust typedef'>")?;
4357 render_attributes(w, it)?;
4358 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4359 it.name.as_ref().unwrap(),
4361 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4364 document(w, cx, it)?;
4366 // Render any items associated directly to this alias, as otherwise they
4367 // won't be visible anywhere in the docs. It would be nice to also show
4368 // associated items from the aliased type (see discussion in #32077), but
4369 // we need #14072 to make sense of the generics.
4370 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4373 fn item_foreign_type(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item) -> fmt::Result {
4374 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4375 render_attributes(w, it)?;
4378 " {}type {};\n}}</pre>",
4379 VisSpace(&it.visibility),
4380 it.name.as_ref().unwrap(),
4383 document(w, cx, it)?;
4385 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4388 impl<'a> fmt::Display for Sidebar<'a> {
4389 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4392 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4394 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4395 || it.is_enum() || it.is_mod() || it.is_typedef() {
4396 write!(fmt, "<p class='location'>{}{}</p>",
4398 clean::StructItem(..) => "Struct ",
4399 clean::TraitItem(..) => "Trait ",
4400 clean::PrimitiveItem(..) => "Primitive Type ",
4401 clean::UnionItem(..) => "Union ",
4402 clean::EnumItem(..) => "Enum ",
4403 clean::TypedefItem(..) => "Type Definition ",
4404 clean::ForeignTypeItem => "Foreign Type ",
4405 clean::ModuleItem(..) => if it.is_crate() {
4412 it.name.as_ref().unwrap())?;
4416 if let Some(ref version) = cache().crate_version {
4418 "<div class='block version'>\
4425 write!(fmt, "<div class=\"sidebar-elems\">")?;
4427 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4428 it.name.as_ref().expect("crates always have a name"))?;
4431 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4432 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4433 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4434 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4435 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4436 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4437 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4438 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4442 // The sidebar is designed to display sibling functions, modules and
4443 // other miscellaneous information. since there are lots of sibling
4444 // items (and that causes quadratic growth in large modules),
4445 // we refactor common parts into a shared JavaScript file per module.
4446 // still, we don't move everything into JS because we want to preserve
4447 // as much HTML as possible in order to allow non-JS-enabled browsers
4448 // to navigate the documentation (though slightly inefficiently).
4450 write!(fmt, "<p class='location'>")?;
4451 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4453 write!(fmt, "::<wbr>")?;
4455 write!(fmt, "<a href='{}index.html'>{}</a>",
4456 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4459 write!(fmt, "</p>")?;
4461 // Sidebar refers to the enclosing module, not this module.
4462 let relpath = if it.is_mod() { "../" } else { "" };
4464 "<script>window.sidebarCurrent = {{\
4469 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4470 ty = it.type_().css_class(),
4473 // There is no sidebar-items.js beyond the crate root path
4474 // FIXME maybe dynamic crate loading can be merged here
4476 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4479 // Closes sidebar-elems div.
4480 write!(fmt, "</div>")?;
4486 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4487 if used_links.insert(url.clone()) {
4491 while used_links.insert(format!("{}-{}", url, add)) == false {
4494 format!("{}-{}", url, add)
4500 used_links: &mut FxHashSet<String>,
4502 i.items.iter().filter_map(|item| {
4504 // Maybe check with clean::Visibility::Public as well?
4505 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4506 if !for_deref || should_render_item(item, false) {
4507 Some(format!("<a href=\"#{}\">{}</a>",
4508 get_next_url(used_links, format!("method.{}", name)),
4516 }).collect::<Vec<_>>()
4519 // The point is to url encode any potential character from a type with genericity.
4520 fn small_url_encode(s: &str) -> String {
4521 s.replace("<", "%3C")
4522 .replace(">", "%3E")
4523 .replace(" ", "%20")
4524 .replace("?", "%3F")
4525 .replace("'", "%27")
4526 .replace("&", "%26")
4527 .replace(",", "%2C")
4528 .replace(":", "%3A")
4529 .replace(";", "%3B")
4530 .replace("[", "%5B")
4531 .replace("]", "%5D")
4532 .replace("\"", "%22")
4535 fn sidebar_assoc_items(it: &clean::Item) -> String {
4536 let mut out = String::new();
4538 if let Some(v) = c.impls.get(&it.def_id) {
4539 let mut used_links = FxHashSet::default();
4542 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4543 let mut ret = v.iter()
4544 .filter(|i| i.inner_impl().trait_.is_none())
4545 .flat_map(move |i| get_methods(i.inner_impl(),
4547 &mut used_links_bor.borrow_mut()))
4548 .collect::<Vec<_>>();
4549 // We want links' order to be reproducible so we don't use unstable sort.
4551 if !ret.is_empty() {
4552 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4553 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4557 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4558 if let Some(impl_) = v.iter()
4559 .filter(|i| i.inner_impl().trait_.is_some())
4560 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4561 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4563 clean::TypedefItem(ref t, true) => Some(&t.type_),
4567 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4568 c.primitive_locations.get(&prim).cloned()
4569 })).and_then(|did| c.impls.get(&did));
4570 if let Some(impls) = inner_impl {
4571 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4572 out.push_str(&format!("Methods from {}<Target={}>",
4573 Escape(&format!("{:#}",
4574 impl_.inner_impl().trait_.as_ref().unwrap())),
4575 Escape(&format!("{:#}", target))));
4576 out.push_str("</a>");
4577 let mut ret = impls.iter()
4578 .filter(|i| i.inner_impl().trait_.is_none())
4579 .flat_map(|i| get_methods(i.inner_impl(),
4582 .collect::<Vec<_>>();
4583 // We want links' order to be reproducible so we don't use unstable sort.
4585 if !ret.is_empty() {
4586 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4592 let format_impls = |impls: Vec<&Impl>| {
4593 let mut links = FxHashSet::default();
4595 let mut ret = impls.iter()
4597 let is_negative_impl = is_negative_impl(i.inner_impl());
4598 if let Some(ref i) = i.inner_impl().trait_ {
4599 let i_display = format!("{:#}", i);
4600 let out = Escape(&i_display);
4601 let encoded = small_url_encode(&format!("{:#}", i));
4602 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4604 if is_negative_impl { "!" } else { "" },
4606 if links.insert(generated.clone()) {
4615 .collect::<Vec<String>>();
4620 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4622 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4623 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4625 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4627 let concrete_format = format_impls(concrete);
4628 let synthetic_format = format_impls(synthetic);
4629 let blanket_format = format_impls(blanket_impl);
4631 if !concrete_format.is_empty() {
4632 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4633 Trait Implementations</a>");
4634 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4637 if !synthetic_format.is_empty() {
4638 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4639 Auto Trait Implementations</a>");
4640 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4643 if !blanket_format.is_empty() {
4644 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4645 Blanket Implementations</a>");
4646 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4654 fn sidebar_struct(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4655 s: &clean::Struct) -> fmt::Result {
4656 let mut sidebar = String::new();
4657 let fields = get_struct_fields_name(&s.fields);
4659 if !fields.is_empty() {
4660 if let doctree::Plain = s.struct_type {
4661 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4662 <div class=\"sidebar-links\">{}</div>", fields));
4666 sidebar.push_str(&sidebar_assoc_items(it));
4668 if !sidebar.is_empty() {
4669 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4674 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4676 clean::ItemEnum::ImplItem(ref i) => {
4677 if let Some(ref trait_) = i.trait_ {
4678 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4687 fn is_negative_impl(i: &clean::Impl) -> bool {
4688 i.polarity == Some(clean::ImplPolarity::Negative)
4691 fn sidebar_trait(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4692 t: &clean::Trait) -> fmt::Result {
4693 let mut sidebar = String::new();
4699 Some(ref name) if m.is_associated_type() => {
4700 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4706 .collect::<String>();
4707 let consts = t.items
4711 Some(ref name) if m.is_associated_const() => {
4712 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4718 .collect::<String>();
4719 let mut required = t.items
4723 Some(ref name) if m.is_ty_method() => {
4724 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4730 .collect::<Vec<String>>();
4731 let mut provided = t.items
4735 Some(ref name) if m.is_method() => {
4736 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4741 .collect::<Vec<String>>();
4743 if !types.is_empty() {
4744 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4745 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4748 if !consts.is_empty() {
4749 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4750 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4753 if !required.is_empty() {
4755 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4756 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4757 required.join("")));
4759 if !provided.is_empty() {
4761 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4762 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4763 provided.join("")));
4768 if let Some(implementors) = c.implementors.get(&it.def_id) {
4769 let mut res = implementors.iter()
4770 .filter(|i| i.inner_impl().for_.def_id()
4771 .map_or(false, |d| !c.paths.contains_key(&d)))
4773 match extract_for_impl_name(&i.impl_item) {
4774 Some((ref name, ref url)) => {
4775 Some(format!("<a href=\"#impl-{}\">{}</a>",
4776 small_url_encode(url),
4782 .collect::<Vec<String>>();
4783 if !res.is_empty() {
4785 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4786 Implementations on Foreign Types</a><div \
4787 class=\"sidebar-links\">{}</div>",
4792 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4794 sidebar.push_str("<a class=\"sidebar-title\" \
4795 href=\"#synthetic-implementors\">Auto Implementors</a>");
4798 sidebar.push_str(&sidebar_assoc_items(it));
4800 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4803 fn sidebar_primitive(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4804 _p: &clean::PrimitiveType) -> fmt::Result {
4805 let sidebar = sidebar_assoc_items(it);
4807 if !sidebar.is_empty() {
4808 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4813 fn sidebar_typedef(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4814 _t: &clean::Typedef) -> fmt::Result {
4815 let sidebar = sidebar_assoc_items(it);
4817 if !sidebar.is_empty() {
4818 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4823 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4825 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4830 .filter_map(|f| match f.name {
4831 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4832 {name}</a>", name=name)),
4838 fn sidebar_union(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4839 u: &clean::Union) -> fmt::Result {
4840 let mut sidebar = String::new();
4841 let fields = get_struct_fields_name(&u.fields);
4843 if !fields.is_empty() {
4844 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4845 <div class=\"sidebar-links\">{}</div>", fields));
4848 sidebar.push_str(&sidebar_assoc_items(it));
4850 if !sidebar.is_empty() {
4851 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4856 fn sidebar_enum(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4857 e: &clean::Enum) -> fmt::Result {
4858 let mut sidebar = String::new();
4860 let variants = e.variants.iter()
4861 .filter_map(|v| match v.name {
4862 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4863 </a>", name = name)),
4866 .collect::<String>();
4867 if !variants.is_empty() {
4868 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4869 <div class=\"sidebar-links\">{}</div>", variants));
4872 sidebar.push_str(&sidebar_assoc_items(it));
4874 if !sidebar.is_empty() {
4875 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4880 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4882 ItemType::ExternCrate |
4883 ItemType::Import => ("reexports", "Re-exports"),
4884 ItemType::Module => ("modules", "Modules"),
4885 ItemType::Struct => ("structs", "Structs"),
4886 ItemType::Union => ("unions", "Unions"),
4887 ItemType::Enum => ("enums", "Enums"),
4888 ItemType::Function => ("functions", "Functions"),
4889 ItemType::Typedef => ("types", "Type Definitions"),
4890 ItemType::Static => ("statics", "Statics"),
4891 ItemType::Constant => ("constants", "Constants"),
4892 ItemType::Trait => ("traits", "Traits"),
4893 ItemType::Impl => ("impls", "Implementations"),
4894 ItemType::TyMethod => ("tymethods", "Type Methods"),
4895 ItemType::Method => ("methods", "Methods"),
4896 ItemType::StructField => ("fields", "Struct Fields"),
4897 ItemType::Variant => ("variants", "Variants"),
4898 ItemType::Macro => ("macros", "Macros"),
4899 ItemType::Primitive => ("primitives", "Primitive Types"),
4900 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4901 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4902 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4903 ItemType::Keyword => ("keywords", "Keywords"),
4904 ItemType::Existential => ("existentials", "Existentials"),
4905 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4906 ItemType::ProcDerive => ("derives", "Derive Macros"),
4907 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4911 fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item,
4912 items: &[clean::Item]) -> fmt::Result {
4913 let mut sidebar = String::new();
4915 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4916 it.type_() == ItemType::Import) {
4917 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4919 name = "Re-exports"));
4922 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4923 // to print its headings
4924 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4925 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4926 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4927 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4928 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4929 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4930 let (short, name) = item_ty_to_strs(&myty);
4931 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4937 if !sidebar.is_empty() {
4938 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4943 fn sidebar_foreign_type(fmt: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
4944 let sidebar = sidebar_assoc_items(it);
4945 if !sidebar.is_empty() {
4946 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4951 impl<'a> fmt::Display for Source<'a> {
4952 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4953 let Source(s) = *self;
4954 let lines = s.lines().count();
4956 let mut tmp = lines;
4961 write!(fmt, "<pre class=\"line-numbers\">")?;
4962 for i in 1..=lines {
4963 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4965 write!(fmt, "</pre>")?;
4967 highlight::render_with_highlighting(s, None, None, None))?;
4972 fn item_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4973 t: &clean::Macro) -> fmt::Result {
4974 wrap_into_docblock(w, |w| {
4975 w.write_str(&highlight::render_with_highlighting(&t.source,
4983 fn item_proc_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4986 let name = it.name.as_ref().expect("proc-macros always have names");
4988 MacroKind::Bang => {
4989 write!(w, "<pre class='rust macro'>")?;
4990 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4991 write!(w, "</pre>")?;
4993 MacroKind::Attr => {
4994 write!(w, "<pre class='rust attr'>")?;
4995 write!(w, "#[{}]", name)?;
4996 write!(w, "</pre>")?;
4998 MacroKind::Derive => {
4999 write!(w, "<pre class='rust derive'>")?;
5000 write!(w, "#[derive({})]", name)?;
5001 if !m.helpers.is_empty() {
5002 writeln!(w, "\n{{")?;
5003 writeln!(w, " // Attributes available to this derive:")?;
5004 for attr in &m.helpers {
5005 writeln!(w, " #[{}]", attr)?;
5009 write!(w, "</pre>")?;
5016 fn item_primitive(w: &mut fmt::Formatter<'_>, cx: &Context,
5018 _p: &clean::PrimitiveType) -> fmt::Result {
5019 document(w, cx, it)?;
5020 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
5023 fn item_keyword(w: &mut fmt::Formatter<'_>, cx: &Context,
5025 _p: &str) -> fmt::Result {
5029 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
5031 fn make_item_keywords(it: &clean::Item) -> String {
5032 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
5035 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
5036 let (all_types, ret_types) = match item.inner {
5037 clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
5038 clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
5039 clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
5043 let inputs = all_types.iter().map(|arg| {
5044 get_index_type(&arg)
5045 }).filter(|a| a.name.is_some()).collect();
5046 let output = ret_types.iter().map(|arg| {
5047 get_index_type(&arg)
5048 }).filter(|a| a.name.is_some()).collect::<Vec<_>>();
5049 let output = if output.is_empty() {
5055 Some(IndexItemFunctionType { inputs, output })
5058 fn get_index_type(clean_type: &clean::Type) -> Type {
5060 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5061 generics: get_generics(clean_type),
5066 /// Returns a list of all paths used in the type.
5067 /// This is used to help deduplicate imported impls
5068 /// for reexported types. If any of the contained
5069 /// types are re-exported, we don't use the corresponding
5070 /// entry from the js file, as inlining will have already
5071 /// picked up the impl
5072 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5073 let mut out = Vec::new();
5074 let mut visited = FxHashSet::default();
5075 let mut work = VecDeque::new();
5076 let cache = cache();
5078 work.push_back(first_ty);
5080 while let Some(ty) = work.pop_front() {
5081 if !visited.insert(ty.clone()) {
5086 clean::Type::ResolvedPath { did, .. } => {
5087 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5088 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5092 out.push(path.join("::"));
5098 clean::Type::Tuple(tys) => {
5099 work.extend(tys.into_iter());
5101 clean::Type::Slice(ty) => {
5102 work.push_back(*ty);
5104 clean::Type::Array(ty, _) => {
5105 work.push_back(*ty);
5107 clean::Type::Unique(ty) => {
5108 work.push_back(*ty);
5110 clean::Type::RawPointer(_, ty) => {
5111 work.push_back(*ty);
5113 clean::Type::BorrowedRef { type_, .. } => {
5114 work.push_back(*type_);
5116 clean::Type::QPath { self_type, trait_, .. } => {
5117 work.push_back(*self_type);
5118 work.push_back(*trait_);
5126 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5128 clean::ResolvedPath { ref path, .. } => {
5129 let segments = &path.segments;
5130 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5131 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5132 clean_type, accept_generic
5134 Some(path_segment.name.clone())
5136 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5137 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5138 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5139 // FIXME: add all from clean::Type.
5144 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5145 clean_type.generics()
5147 let r = types.iter()
5148 .filter_map(|t| get_index_type_name(t, false))
5149 .map(|s| s.to_ascii_lowercase())
5150 .collect::<Vec<_>>();
5159 pub fn cache() -> Arc<Cache> {
5160 CACHE_KEY.with(|c| c.borrow().clone())
5165 fn test_name_key() {
5166 assert_eq!(name_key("0"), ("", 0, 1));
5167 assert_eq!(name_key("123"), ("", 123, 0));
5168 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5169 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5170 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5171 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5172 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5173 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5178 fn test_name_sorting() {
5179 let names = ["Apple",
5181 "Fruit", "Fruit0", "Fruit00",
5182 "Fruit1", "Fruit01",
5183 "Fruit2", "Fruit02",
5188 let mut sorted = names.to_owned();
5189 sorted.sort_by_key(|&s| name_key(s));
5190 assert_eq!(names, sorted);