1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
28 pub use self::ExternalLocation::*;
31 use std::cell::RefCell;
32 use std::cmp::Ordering;
33 use std::collections::{BTreeMap, VecDeque};
34 use std::default::Default;
36 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
38 use std::fs::{self, File, OpenOptions};
39 use std::io::prelude::*;
40 use std::io::{self, BufWriter, BufReader};
42 use std::path::{PathBuf, Path, Component};
48 use serialize::json::{ToJson, Json, as_json};
50 use syntax::edition::Edition;
51 use syntax::ext::base::MacroKind;
52 use syntax::source_map::FileName;
53 use syntax::feature_gate::UnstableFeatures;
54 use syntax::symbol::{Symbol, sym};
55 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
56 use rustc::middle::privacy::AccessLevels;
57 use rustc::middle::stability;
59 use rustc::util::nodemap::{FxHashMap, FxHashSet};
60 use rustc_data_structures::flock;
62 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
63 use crate::config::RenderOptions;
65 use crate::fold::DocFolder;
66 use crate::html::escape::Escape;
67 use crate::html::format::{AsyncSpace, ConstnessSpace};
68 use crate::html::format::{GenericBounds, WhereClause, href, AbiSpace, DefaultSpace};
69 use crate::html::format::{VisSpace, Function, UnsafetySpace, MutableSpace};
70 use crate::html::format::fmt_impl_for_trait_page;
71 use crate::html::item_type::ItemType;
72 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
73 use crate::html::{highlight, layout, static_files};
77 /// A pair of name and its optional document.
78 pub type NameDoc = (String, Option<String>);
80 pub struct SlashChecker<'a>(pub &'a str);
82 impl<'a> Display for SlashChecker<'a> {
83 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
84 if !self.0.ends_with("/") && !self.0.is_empty() {
85 write!(f, "{}/", self.0)
87 write!(f, "{}", self.0)
92 /// Major driving force in all rustdoc rendering. This contains information
93 /// about where in the tree-like hierarchy rendering is occurring and controls
94 /// how the current page is being rendered.
96 /// It is intended that this context is a lightweight object which can be fairly
97 /// easily cloned because it is cloned per work-job (about once per item in the
101 /// Current hierarchy of components leading down to what's currently being
103 pub current: Vec<String>,
104 /// The current destination folder of where HTML artifacts should be placed.
105 /// This changes as the context descends into the module hierarchy.
107 /// A flag, which when `true`, will render pages which redirect to the
108 /// real location of an item. This is used to allow external links to
109 /// publicly reused items to redirect to the right location.
110 pub render_redirect_pages: bool,
111 pub codes: ErrorCodes,
112 /// The default edition used to parse doctests.
113 pub edition: Edition,
114 /// The map used to ensure all generated 'id=' attributes are unique.
115 id_map: Rc<RefCell<IdMap>>,
116 pub shared: Arc<SharedContext>,
119 struct SharedContext {
120 /// The path to the crate root source minus the file name.
121 /// Used for simplifying paths to the highlighted source code files.
122 pub src_root: PathBuf,
123 /// This describes the layout of each page, and is not modified after
124 /// creation of the context (contains info like the favicon and added html).
125 pub layout: layout::Layout,
126 /// This flag indicates whether `[src]` links should be generated or not. If
127 /// the source files are present in the html rendering, then this will be
129 pub include_sources: bool,
130 /// The local file sources we've emitted and their respective url-paths.
131 pub local_sources: FxHashMap<PathBuf, String>,
132 /// All the passes that were run on this crate.
133 pub passes: FxHashSet<String>,
134 /// The base-URL of the issue tracker for when an item has been tagged with
136 pub issue_tracker_base_url: Option<String>,
137 /// The given user css file which allow to customize the generated
138 /// documentation theme.
139 pub css_file_extension: Option<PathBuf>,
140 /// The directories that have already been created in this doc run. Used to reduce the number
141 /// of spurious `create_dir_all` calls.
142 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
143 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
144 /// should be ordered alphabetically or in order of appearance (in the source code).
145 pub sort_modules_alphabetically: bool,
146 /// Additional themes to be added to the generated docs.
147 pub themes: Vec<PathBuf>,
148 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
150 pub resource_suffix: String,
151 /// Optional path string to be used to load static files on output pages. If not set, uses
152 /// combinations of `../` to reach the documentation root.
153 pub static_root_path: Option<String>,
154 /// If false, the `select` element to have search filtering by crates on rendered docs
155 /// won't be generated.
156 pub generate_search_filter: bool,
157 /// Option disabled by default to generate files used by RLS and some other tools.
158 pub generate_redirect_pages: bool,
162 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
163 let mut dirs = self.created_dirs.borrow_mut();
164 if !dirs.contains(dst) {
165 fs::create_dir_all(dst)?;
166 dirs.insert(dst.to_path_buf());
174 /// Returns `true` if the `collapse-docs` pass was run on this crate.
175 pub fn was_collapsed(&self) -> bool {
176 self.passes.contains("collapse-docs")
179 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
180 /// `collapsed_doc_value` of the given item.
181 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
182 if self.was_collapsed() {
183 item.collapsed_doc_value().map(|s| s.into())
185 item.doc_value().map(|s| s.into())
190 /// Indicates where an external crate can be found.
191 pub enum ExternalLocation {
192 /// Remote URL root of the external crate
194 /// This external crate can be found in the local doc/ folder
196 /// The external crate could not be found.
200 /// Metadata about implementations for a type or trait.
201 #[derive(Clone, Debug)]
203 pub impl_item: clean::Item,
207 fn inner_impl(&self) -> &clean::Impl {
208 match self.impl_item.inner {
209 clean::ImplItem(ref impl_) => impl_,
210 _ => panic!("non-impl item found in impl")
214 fn trait_did(&self) -> Option<DefId> {
215 self.inner_impl().trait_.def_id()
222 pub error: io::Error,
225 impl error::Error for Error {
226 fn description(&self) -> &str {
227 self.error.description()
231 impl Display for Error {
232 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
233 write!(f, "\"{}\": {}", self.file.display(), self.error)
238 pub fn new(e: io::Error, file: &Path) -> Error {
240 file: file.to_path_buf(),
246 macro_rules! try_none {
247 ($e:expr, $file:expr) => ({
251 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
257 macro_rules! try_err {
258 ($e:expr, $file:expr) => ({
261 Err(e) => return Err(Error::new(e, $file)),
266 /// This cache is used to store information about the `clean::Crate` being
267 /// rendered in order to provide more useful documentation. This contains
268 /// information like all implementors of a trait, all traits a type implements,
269 /// documentation for all known traits, etc.
271 /// This structure purposefully does not implement `Clone` because it's intended
272 /// to be a fairly large and expensive structure to clone. Instead this adheres
273 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
274 /// rendering threads.
277 /// Mapping of typaram ids to the name of the type parameter. This is used
278 /// when pretty-printing a type (so pretty-printing doesn't have to
279 /// painfully maintain a context like this)
280 pub param_names: FxHashMap<DefId, String>,
282 /// Maps a type ID to all known implementations for that type. This is only
283 /// recognized for intra-crate `ResolvedPath` types, and is used to print
284 /// out extra documentation on the page of an enum/struct.
286 /// The values of the map are a list of implementations and documentation
287 /// found on that implementation.
288 pub impls: FxHashMap<DefId, Vec<Impl>>,
290 /// Maintains a mapping of local crate `NodeId`s to the fully qualified name
291 /// and "short type description" of that node. This is used when generating
292 /// URLs when a type is being linked to. External paths are not located in
293 /// this map because the `External` type itself has all the information
295 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
297 /// Similar to `paths`, but only holds external paths. This is only used for
298 /// generating explicit hyperlinks to other crates.
299 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
301 /// Maps local `DefId`s of exported types to fully qualified paths.
302 /// Unlike 'paths', this mapping ignores any renames that occur
303 /// due to 'use' statements.
305 /// This map is used when writing out the special 'implementors'
306 /// javascript file. By using the exact path that the type
307 /// is declared with, we ensure that each path will be identical
308 /// to the path used if the corresponding type is inlined. By
309 /// doing this, we can detect duplicate impls on a trait page, and only display
310 /// the impl for the inlined type.
311 pub exact_paths: FxHashMap<DefId, Vec<String>>,
313 /// This map contains information about all known traits of this crate.
314 /// Implementations of a crate should inherit the documentation of the
315 /// parent trait if no extra documentation is specified, and default methods
316 /// should show up in documentation about trait implementations.
317 pub traits: FxHashMap<DefId, clean::Trait>,
319 /// When rendering traits, it's often useful to be able to list all
320 /// implementors of the trait, and this mapping is exactly, that: a mapping
321 /// of trait ids to the list of known implementors of the trait
322 pub implementors: FxHashMap<DefId, Vec<Impl>>,
324 /// Cache of where external crate documentation can be found.
325 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
327 /// Cache of where documentation for primitives can be found.
328 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
330 // Note that external items for which `doc(hidden)` applies to are shown as
331 // non-reachable while local items aren't. This is because we're reusing
332 // the access levels from the privacy check pass.
333 pub access_levels: AccessLevels<DefId>,
335 /// The version of the crate being documented, if given from the `--crate-version` flag.
336 pub crate_version: Option<String>,
338 // Private fields only used when initially crawling a crate to build a cache
341 parent_stack: Vec<DefId>,
342 parent_is_trait_impl: bool,
343 search_index: Vec<IndexItem>,
345 deref_trait_did: Option<DefId>,
346 deref_mut_trait_did: Option<DefId>,
347 owned_box_did: Option<DefId>,
348 masked_crates: FxHashSet<CrateNum>,
350 // In rare case where a structure is defined in one module but implemented
351 // in another, if the implementing module is parsed before defining module,
352 // then the fully qualified name of the structure isn't presented in `paths`
353 // yet when its implementation methods are being indexed. Caches such methods
354 // and their parent id here and indexes them at the end of crate parsing.
355 orphan_impl_items: Vec<(DefId, clean::Item)>,
357 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
358 // even though the trait itself is not exported. This can happen if a trait
359 // was defined in function/expression scope, since the impl will be picked
360 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
361 // crawl. In order to prevent crashes when looking for spotlight traits or
362 // when gathering trait documentation on a type, hold impls here while
363 // folding and add them to the cache later on if we find the trait.
364 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
366 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
367 /// we need the alias element to have an array of items.
368 aliases: FxHashMap<String, Vec<IndexItem>>,
371 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
372 /// Later on moved into `CACHE_KEY`.
374 pub struct RenderInfo {
375 pub inlined: FxHashSet<DefId>,
376 pub external_paths: crate::core::ExternalPaths,
377 pub external_param_names: FxHashMap<DefId, String>,
378 pub exact_paths: FxHashMap<DefId, Vec<String>>,
379 pub access_levels: AccessLevels<DefId>,
380 pub deref_trait_did: Option<DefId>,
381 pub deref_mut_trait_did: Option<DefId>,
382 pub owned_box_did: Option<DefId>,
385 /// Helper struct to render all source code to HTML pages
386 struct SourceCollector<'a> {
387 scx: &'a mut SharedContext,
389 /// Root destination to place all HTML output into
393 /// Wrapper struct to render the source code of a file. This will do things like
394 /// adding line numbers to the left-hand side.
395 struct Source<'a>(&'a str);
397 // Helper structs for rendering items/sidebars and carrying along contextual
400 #[derive(Copy, Clone)]
403 item: &'a clean::Item,
406 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
408 /// Struct representing one entry in the JS search index. These are all emitted
409 /// by hand to a large JS file at the end of cache-creation.
416 parent: Option<DefId>,
417 parent_idx: Option<usize>,
418 search_type: Option<IndexItemFunctionType>,
421 impl ToJson for IndexItem {
422 fn to_json(&self) -> Json {
423 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
425 let mut data = Vec::with_capacity(6);
426 data.push((self.ty as usize).to_json());
427 data.push(self.name.to_json());
428 data.push(self.path.to_json());
429 data.push(self.desc.to_json());
430 data.push(self.parent_idx.to_json());
431 data.push(self.search_type.to_json());
437 /// A type used for the search index.
440 name: Option<String>,
441 generics: Option<Vec<String>>,
444 impl ToJson for Type {
445 fn to_json(&self) -> Json {
448 let mut data = Vec::with_capacity(2);
449 data.push(name.to_json());
450 if let Some(ref generics) = self.generics {
451 data.push(generics.to_json());
460 /// Full type of functions/methods in the search index.
462 struct IndexItemFunctionType {
464 output: Option<Vec<Type>>,
467 impl ToJson for IndexItemFunctionType {
468 fn to_json(&self) -> Json {
469 // If we couldn't figure out a type, just write `null`.
470 let mut iter = self.inputs.iter();
471 if match self.output {
472 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
473 None => iter.any(|ref i| i.name.is_none()),
477 let mut data = Vec::with_capacity(2);
478 data.push(self.inputs.to_json());
479 if let Some(ref output) = self.output {
480 if output.len() > 1 {
481 data.push(output.to_json());
483 data.push(output[0].to_json());
491 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
492 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
494 pub fn initial_ids() -> Vec<String> {
506 "synthetic-implementors",
508 "synthetic-implementors-list",
512 ].iter().map(|id| (String::from(*id))).collect()
515 /// Generates the documentation for `crate` into the directory `dst`
516 pub fn run(mut krate: clean::Crate,
517 options: RenderOptions,
518 passes: FxHashSet<String>,
519 renderinfo: RenderInfo,
520 diag: &errors::Handler,
521 edition: Edition) -> Result<(), Error> {
522 // need to save a copy of the options for rendering the index page
523 let md_opts = options.clone();
529 sort_modules_alphabetically,
532 extern_html_root_urls,
535 generate_search_filter,
536 generate_redirect_pages,
540 let src_root = match krate.src {
541 FileName::Real(ref p) => match p.parent() {
542 Some(p) => p.to_path_buf(),
543 None => PathBuf::new(),
547 let mut scx = SharedContext {
550 include_sources: true,
551 local_sources: Default::default(),
552 issue_tracker_base_url: None,
553 layout: layout::Layout {
555 favicon: String::new(),
557 krate: krate.name.clone(),
559 css_file_extension: extension_css,
560 created_dirs: Default::default(),
561 sort_modules_alphabetically,
565 generate_search_filter,
566 generate_redirect_pages,
569 // If user passed in `--playground-url` arg, we fill in crate name here
570 if let Some(url) = playground_url {
571 markdown::PLAYGROUND.with(|slot| {
572 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
576 // Crawl the crate attributes looking for attributes which control how we're
577 // going to emit HTML
578 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
579 for attr in attrs.lists(sym::doc) {
580 match (attr.name_or_empty(), attr.value_str()) {
581 (sym::html_favicon_url, Some(s)) => {
582 scx.layout.favicon = s.to_string();
584 (sym::html_logo_url, Some(s)) => {
585 scx.layout.logo = s.to_string();
587 (sym::html_playground_url, Some(s)) => {
588 markdown::PLAYGROUND.with(|slot| {
589 let name = krate.name.clone();
590 *slot.borrow_mut() = Some((Some(name), s.to_string()));
593 (sym::issue_tracker_base_url, Some(s)) => {
594 scx.issue_tracker_base_url = Some(s.to_string());
596 (sym::html_no_source, None) if attr.is_word() => {
597 scx.include_sources = false;
604 try_err!(fs::create_dir_all(&dst), &dst);
605 krate = render_sources(&dst, &mut scx, krate)?;
609 render_redirect_pages: false,
610 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
612 id_map: Rc::new(RefCell::new(id_map)),
613 shared: Arc::new(scx),
616 // Crawl the crate to build various caches used for the output
620 external_param_names,
628 let external_paths = external_paths.into_iter()
629 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
632 let mut cache = Cache {
633 impls: Default::default(),
636 paths: Default::default(),
637 implementors: Default::default(),
639 parent_stack: Vec::new(),
640 search_index: Vec::new(),
641 parent_is_trait_impl: false,
642 extern_locations: Default::default(),
643 primitive_locations: Default::default(),
646 crate_version: krate.version.take(),
647 orphan_impl_items: Vec::new(),
648 orphan_trait_impls: Vec::new(),
649 traits: krate.external_traits.lock().replace(Default::default()),
653 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
654 param_names: external_param_names,
655 aliases: Default::default(),
658 // Cache where all our extern crates are located
659 for &(n, ref e) in &krate.externs {
660 let src_root = match e.src {
661 FileName::Real(ref p) => match p.parent() {
662 Some(p) => p.to_path_buf(),
663 None => PathBuf::new(),
667 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
668 cache.extern_locations.insert(n, (e.name.clone(), src_root,
669 extern_location(e, extern_url, &cx.dst)));
671 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
672 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
675 // Cache where all known primitives have their documentation located.
677 // Favor linking to as local extern as possible, so iterate all crates in
678 // reverse topological order.
679 for &(_, ref e) in krate.externs.iter().rev() {
680 for &(def_id, prim, _) in &e.primitives {
681 cache.primitive_locations.insert(prim, def_id);
684 for &(def_id, prim, _) in &krate.primitives {
685 cache.primitive_locations.insert(prim, def_id);
688 cache.stack.push(krate.name.clone());
689 krate = cache.fold_crate(krate);
691 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
692 if cache.traits.contains_key(&trait_did) {
694 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
699 // Build our search index
700 let index = build_index(&krate, &mut cache);
702 // Freeze the cache now that the index has been built. Put an Arc into TLS
703 // for future parallelization opportunities
704 let cache = Arc::new(cache);
705 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
706 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
708 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
710 // And finally render the whole crate's documentation
714 /// Builds the search index from the collected metadata
715 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
716 let mut nodeid_to_pathid = FxHashMap::default();
717 let mut crate_items = Vec::with_capacity(cache.search_index.len());
718 let mut crate_paths = Vec::<Json>::new();
720 let Cache { ref mut search_index,
721 ref orphan_impl_items,
722 ref mut paths, .. } = *cache;
724 // Attach all orphan items to the type's definition if the type
725 // has since been learned.
726 for &(did, ref item) in orphan_impl_items {
727 if let Some(&(ref fqp, _)) = paths.get(&did) {
728 search_index.push(IndexItem {
730 name: item.name.clone().unwrap(),
731 path: fqp[..fqp.len() - 1].join("::"),
732 desc: plain_summary_line_short(item.doc_value()),
735 search_type: get_index_search_type(&item),
740 // Reduce `NodeId` in paths into smaller sequential numbers,
741 // and prune the paths that do not appear in the index.
742 let mut lastpath = String::new();
743 let mut lastpathid = 0usize;
745 for item in search_index {
746 item.parent_idx = item.parent.map(|nodeid| {
747 if nodeid_to_pathid.contains_key(&nodeid) {
748 *nodeid_to_pathid.get(&nodeid).unwrap()
750 let pathid = lastpathid;
751 nodeid_to_pathid.insert(nodeid, pathid);
754 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
755 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
760 // Omit the parent path if it is same to that of the prior item.
761 if lastpath == item.path {
764 lastpath = item.path.clone();
766 crate_items.push(item.to_json());
769 let crate_doc = krate.module.as_ref().map(|module| {
770 plain_summary_line_short(module.doc_value())
771 }).unwrap_or(String::new());
773 let mut crate_data = BTreeMap::new();
774 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
775 crate_data.insert("i".to_owned(), Json::Array(crate_items));
776 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
778 // Collect the index into a string
779 format!("searchIndex[{}] = {};",
780 as_json(&krate.name),
781 Json::Object(crate_data))
786 krate: &clean::Crate,
788 search_index: String,
789 options: &RenderOptions,
790 diag: &errors::Handler,
791 ) -> Result<(), Error> {
792 // Write out the shared files. Note that these are shared among all rustdoc
793 // docs placed in the output directory, so this needs to be a synchronized
794 // operation with respect to all other rustdocs running around.
795 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
797 // Add all the static files. These may already exist, but we just
798 // overwrite them anyway to make sure that they're fresh and up-to-date.
800 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
801 static_files::RUSTDOC_CSS,
802 options.enable_minification)?;
803 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
804 static_files::SETTINGS_CSS,
805 options.enable_minification)?;
806 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
807 static_files::NOSCRIPT_CSS,
808 options.enable_minification)?;
810 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
811 // then we'll run over the "official" styles.
812 let mut themes: FxHashSet<String> = FxHashSet::default();
814 for entry in &cx.shared.themes {
815 let content = try_err!(fs::read(&entry), &entry);
816 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
817 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
818 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
819 content.as_slice())?;
820 themes.insert(theme.to_owned());
823 if (*cx.shared).layout.logo.is_empty() {
824 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
825 static_files::RUST_LOGO)?;
827 if (*cx.shared).layout.favicon.is_empty() {
828 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
829 static_files::RUST_FAVICON)?;
831 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
832 static_files::BRUSH_SVG)?;
833 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
834 static_files::WHEEL_SVG)?;
835 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
836 static_files::DOWN_ARROW_SVG)?;
837 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
838 static_files::themes::LIGHT,
839 options.enable_minification)?;
840 themes.insert("light".to_owned());
841 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
842 static_files::themes::DARK,
843 options.enable_minification)?;
844 themes.insert("dark".to_owned());
846 let mut themes: Vec<&String> = themes.iter().collect();
848 // To avoid theme switch latencies as much as possible, we put everything theme related
849 // at the beginning of the html files into another js file.
850 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
852 r#"var themes = document.getElementById("theme-choices");
853 var themePicker = document.getElementById("theme-picker");
855 function switchThemeButtonState() {{
856 if (themes.style.display === "block") {{
857 themes.style.display = "none";
858 themePicker.style.borderBottomRightRadius = "3px";
859 themePicker.style.borderBottomLeftRadius = "3px";
861 themes.style.display = "block";
862 themePicker.style.borderBottomRightRadius = "0";
863 themePicker.style.borderBottomLeftRadius = "0";
867 function handleThemeButtonsBlur(e) {{
868 var active = document.activeElement;
869 var related = e.relatedTarget;
871 if (active.id !== "themePicker" &&
872 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
874 (related.id !== "themePicker" &&
875 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
876 switchThemeButtonState();
880 themePicker.onclick = switchThemeButtonState;
881 themePicker.onblur = handleThemeButtonsBlur;
882 [{}].forEach(function(item) {{
883 var but = document.createElement('button');
884 but.innerHTML = item;
885 but.onclick = function(el) {{
886 switchTheme(currentTheme, mainTheme, item);
888 but.onblur = handleThemeButtonsBlur;
889 themes.appendChild(but);
892 .map(|s| format!("\"{}\"", s))
893 .collect::<Vec<String>>()
894 .join(",")).as_bytes(),
897 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
898 static_files::MAIN_JS,
899 options.enable_minification)?;
900 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
901 static_files::SETTINGS_JS,
902 options.enable_minification)?;
903 if cx.shared.include_sources {
904 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
905 static_files::sidebar::SOURCE_SCRIPT,
906 options.enable_minification)?;
910 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
911 &format!("var resourcesSuffix = \"{}\";{}",
912 cx.shared.resource_suffix,
913 static_files::STORAGE_JS),
914 options.enable_minification)?;
917 if let Some(ref css) = cx.shared.css_file_extension {
918 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
919 if !options.enable_minification {
920 try_err!(fs::copy(css, out), css);
922 let buffer = try_err!(fs::read_to_string(css), css);
923 write_minify(out, &buffer, options.enable_minification)?;
926 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
927 static_files::NORMALIZE_CSS,
928 options.enable_minification)?;
929 write(cx.dst.join("FiraSans-Regular.woff"),
930 static_files::fira_sans::REGULAR)?;
931 write(cx.dst.join("FiraSans-Medium.woff"),
932 static_files::fira_sans::MEDIUM)?;
933 write(cx.dst.join("FiraSans-LICENSE.txt"),
934 static_files::fira_sans::LICENSE)?;
935 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
936 static_files::source_serif_pro::REGULAR)?;
937 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
938 static_files::source_serif_pro::BOLD)?;
939 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
940 static_files::source_serif_pro::ITALIC)?;
941 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
942 static_files::source_serif_pro::LICENSE)?;
943 write(cx.dst.join("SourceCodePro-Regular.woff"),
944 static_files::source_code_pro::REGULAR)?;
945 write(cx.dst.join("SourceCodePro-Semibold.woff"),
946 static_files::source_code_pro::SEMIBOLD)?;
947 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
948 static_files::source_code_pro::LICENSE)?;
949 write(cx.dst.join("LICENSE-MIT.txt"),
950 static_files::LICENSE_MIT)?;
951 write(cx.dst.join("LICENSE-APACHE.txt"),
952 static_files::LICENSE_APACHE)?;
953 write(cx.dst.join("COPYRIGHT.txt"),
954 static_files::COPYRIGHT)?;
960 for_search_index: bool,
961 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
962 let mut ret = Vec::new();
963 let mut krates = Vec::new();
964 let mut variables = Vec::new();
967 for line in BufReader::new(File::open(path)?).lines() {
969 if for_search_index && line.starts_with("var R") {
970 variables.push(line.clone());
973 if !line.starts_with(key) {
976 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
979 ret.push(line.to_string());
980 krates.push(line[key.len() + 2..].split('"')
982 .map(|s| s.to_owned())
983 .unwrap_or_else(|| String::new()));
986 Ok((ret, krates, variables))
989 fn show_item(item: &IndexItem, krate: &str) -> String {
990 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
991 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
992 if let Some(p) = item.parent_idx {
993 format!(",'parent':{}", p)
999 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
1001 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
1002 let mut w = try_err!(File::create(&dst), &dst);
1003 let mut output = String::with_capacity(100);
1004 for (alias, items) in &cache.aliases {
1005 if items.is_empty() {
1008 output.push_str(&format!("\"{}\":[{}],",
1011 .map(|v| show_item(v, &krate.name))
1012 .collect::<Vec<_>>()
1015 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1017 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1018 for aliases in &all_aliases {
1019 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1023 use std::ffi::OsString;
1028 children: FxHashMap<OsString, Hierarchy>,
1029 elems: FxHashSet<OsString>,
1033 fn new(elem: OsString) -> Hierarchy {
1036 children: FxHashMap::default(),
1037 elems: FxHashSet::default(),
1041 fn to_json_string(&self) -> String {
1042 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1043 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1044 let mut files = self.elems.iter()
1045 .map(|s| format!("\"{}\"",
1047 .expect("invalid osstring conversion")))
1048 .collect::<Vec<_>>();
1049 files.sort_unstable_by(|a, b| a.cmp(b));
1050 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
1051 let dirs = if subs.is_empty() {
1054 format!(",\"dirs\":[{}]", subs)
1056 let files = files.join(",");
1057 let files = if files.is_empty() {
1060 format!(",\"files\":[{}]", files)
1062 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
1063 name=self.elem.to_str().expect("invalid osstring conversion"),
1069 if cx.shared.include_sources {
1070 let mut hierarchy = Hierarchy::new(OsString::new());
1071 for source in cx.shared.local_sources.iter()
1072 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1074 let mut h = &mut hierarchy;
1075 let mut elems = source.components()
1078 Component::Normal(s) => Some(s.to_owned()),
1084 let cur_elem = elems.next().expect("empty file path");
1085 if elems.peek().is_none() {
1086 h.elems.insert(cur_elem);
1089 let e = cur_elem.clone();
1090 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1091 h = h.children.get_mut(&cur_elem).expect("not found child");
1096 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1097 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1100 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1102 hierarchy.to_json_string()));
1104 let mut w = try_err!(File::create(&dst), &dst);
1105 try_err!(writeln!(&mut w,
1106 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1107 all_sources.join("\n")),
1111 // Update the search index
1112 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1113 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1117 all_indexes.push(search_index);
1119 // Sort the indexes by crate so the file will be generated identically even
1120 // with rustdoc running in parallel.
1122 let mut w = try_err!(File::create(&dst), &dst);
1123 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1124 try_err!(write_minify_replacer(&mut w,
1125 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1126 options.enable_minification),
1128 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1130 if options.enable_index_page {
1131 if let Some(index_page) = options.index_page.clone() {
1132 let mut md_opts = options.clone();
1133 md_opts.output = cx.dst.clone();
1134 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1136 crate::markdown::render(index_page, md_opts, diag, cx.edition);
1138 let dst = cx.dst.join("index.html");
1139 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1140 let page = layout::Page {
1141 title: "Index of crates",
1144 static_root_path: cx.shared.static_root_path.deref(),
1145 description: "List of crates",
1146 keywords: BASIC_KEYWORDS,
1147 resource_suffix: &cx.shared.resource_suffix,
1149 static_extra_scripts: &[],
1151 krates.push(krate.name.clone());
1155 let content = format!(
1157 <span class='in-band'>List of all crates</span>\
1158 </h1><ul class='mod'>{}</ul>",
1162 format!("<li><a href=\"{}index.html\">{}</li>",
1165 .collect::<String>());
1166 try_err!(layout::render(&mut w, &cx.shared.layout,
1167 &page, &(""), &content,
1168 cx.shared.css_file_extension.is_some(),
1170 cx.shared.generate_search_filter), &dst);
1171 try_err!(w.flush(), &dst);
1175 // Update the list of all implementors for traits
1176 let dst = cx.dst.join("implementors");
1177 for (&did, imps) in &cache.implementors {
1178 // Private modules can leak through to this phase of rustdoc, which
1179 // could contain implementations for otherwise private types. In some
1180 // rare cases we could find an implementation for an item which wasn't
1181 // indexed, so we just skip this step in that case.
1183 // FIXME: this is a vague explanation for why this can't be a `get`, in
1184 // theory it should be...
1185 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1187 None => match cache.external_paths.get(&did) {
1193 let mut have_impls = false;
1194 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1196 // If the trait and implementation are in the same crate, then
1197 // there's no need to emit information about it (there's inlining
1198 // going on). If they're in different crates then the crate defining
1199 // the trait will be interested in our implementation.
1200 if imp.impl_item.def_id.krate == did.krate { continue }
1201 // If the implementation is from another crate then that crate
1203 if !imp.impl_item.def_id.is_local() { continue }
1205 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1206 as_json(&imp.inner_impl().to_string()),
1207 imp.inner_impl().synthetic,
1208 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1210 implementors.push_str("];");
1212 // Only create a js file if we have impls to add to it. If the trait is
1213 // documented locally though we always create the file to avoid dead
1215 if !have_impls && !cache.paths.contains_key(&did) {
1219 let mut mydst = dst.clone();
1220 for part in &remote_path[..remote_path.len() - 1] {
1223 try_err!(fs::create_dir_all(&mydst), &mydst);
1224 mydst.push(&format!("{}.{}.js",
1225 remote_item_type.css_class(),
1226 remote_path[remote_path.len() - 1]));
1228 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1231 all_implementors.push(implementors);
1232 // Sort the implementors by crate so the file will be generated
1233 // identically even with rustdoc running in parallel.
1234 all_implementors.sort();
1236 let mut f = try_err!(File::create(&mydst), &mydst);
1237 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1238 for implementor in &all_implementors {
1239 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1241 try_err!(writeln!(&mut f, "{}", r"
1242 if (window.register_implementors) {
1243 window.register_implementors(implementors);
1245 window.pending_implementors = implementors;
1248 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1253 fn render_sources(dst: &Path, scx: &mut SharedContext,
1254 krate: clean::Crate) -> Result<clean::Crate, Error> {
1255 info!("emitting source files");
1256 let dst = dst.join("src").join(&krate.name);
1257 try_err!(fs::create_dir_all(&dst), &dst);
1258 let mut folder = SourceCollector {
1262 Ok(folder.fold_crate(krate))
1265 /// Writes the entire contents of a string to a destination, not attempting to
1266 /// catch any errors.
1267 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1268 Ok(try_err!(fs::write(&dst, contents), &dst))
1271 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1272 if enable_minification {
1273 if dst.extension() == Some(&OsStr::new("css")) {
1274 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1275 write(dst, res.as_bytes())
1277 write(dst, minifier::js::minify(contents).as_bytes())
1280 write(dst, contents.as_bytes())
1284 fn write_minify_replacer<W: Write>(
1287 enable_minification: bool,
1288 ) -> io::Result<()> {
1289 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1291 if enable_minification {
1294 let tokens: Tokens<'_> = simple_minify(contents)
1297 // We keep backlines.
1298 minifier::js::clean_token_except(f, &|c: &Token<'_>| {
1299 c.get_char() != Some(ReservedChar::Backline)
1303 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1305 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1306 Token::String(s) => {
1307 let s = &s[1..s.len() -1]; // The quotes are included
1309 Some(Token::Other("E"))
1310 } else if s == "t" {
1311 Some(Token::Other("T"))
1312 } else if s == "u" {
1313 Some(Token::Other("U"))
1322 .collect::<Vec<_>>()
1325 // We add a backline after the newly created variables.
1326 minifier::js::aggregate_strings_into_array_with_separation_filter(
1329 Token::Char(ReservedChar::Backline),
1330 // This closure prevents crates' names from being aggregated.
1332 // The point here is to check if the string is preceded by '[' and
1333 // "searchIndex". If so, it means this is a crate name and that it
1334 // shouldn't be aggregated.
1337 !tokens[pos - 1].is_char(ReservedChar::OpenBracket) ||
1338 tokens[pos - 2].get_other() != Some("searchIndex")
1345 writeln!(dst, "{}", contents)
1349 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1350 /// things like ".." to components which preserve the "top down" hierarchy of a
1351 /// static HTML tree. Each component in the cleaned path will be passed as an
1352 /// argument to `f`. The very last component of the path (ie the file name) will
1353 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1354 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
1358 // make it relative, if possible
1359 let p = p.strip_prefix(src_root).unwrap_or(p);
1361 let mut iter = p.components().peekable();
1363 while let Some(c) = iter.next() {
1364 if !keep_filename && iter.peek().is_none() {
1369 Component::ParentDir => f("up".as_ref()),
1370 Component::Normal(c) => f(c),
1376 /// Attempts to find where an external crate is located, given that we're
1377 /// rendering in to the specified source destination.
1378 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1381 // See if there's documentation generated into the local directory
1382 let local_location = dst.join(&e.name);
1383 if local_location.is_dir() {
1387 if let Some(url) = extern_url {
1388 let mut url = url.to_string();
1389 if !url.ends_with("/") {
1395 // Failing that, see if there's an attribute specifying where to find this
1397 e.attrs.lists(sym::doc)
1398 .filter(|a| a.check_name(sym::html_root_url))
1399 .filter_map(|a| a.value_str())
1401 let mut url = url.to_string();
1402 if !url.ends_with("/") {
1406 }).next().unwrap_or(Unknown) // Well, at least we tried.
1409 impl<'a> DocFolder for SourceCollector<'a> {
1410 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1411 // If we're including source files, and we haven't seen this file yet,
1412 // then we need to render it out to the filesystem.
1413 if self.scx.include_sources
1414 // skip all invalid or macro spans
1415 && item.source.filename.is_real()
1416 // skip non-local items
1417 && item.def_id.is_local() {
1419 // If it turns out that we couldn't read this file, then we probably
1420 // can't read any of the files (generating html output from json or
1421 // something like that), so just don't include sources for the
1422 // entire crate. The other option is maintaining this mapping on a
1423 // per-file basis, but that's probably not worth it...
1425 .include_sources = match self.emit_source(&item.source.filename) {
1428 println!("warning: source code was requested to be rendered, \
1429 but processing `{}` had an error: {}",
1430 item.source.filename, e);
1431 println!(" skipping rendering of source code");
1436 self.fold_item_recur(item)
1440 impl<'a> SourceCollector<'a> {
1441 /// Renders the given filename into its corresponding HTML source file.
1442 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1443 let p = match *filename {
1444 FileName::Real(ref file) => file,
1447 if self.scx.local_sources.contains_key(&**p) {
1448 // We've already emitted this source
1452 let contents = fs::read_to_string(&p)?;
1454 // Remove the utf-8 BOM if any
1455 let contents = if contents.starts_with("\u{feff}") {
1461 // Create the intermediate directories
1462 let mut cur = self.dst.clone();
1463 let mut root_path = String::from("../../");
1464 let mut href = String::new();
1465 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1466 cur.push(component);
1467 root_path.push_str("../");
1468 href.push_str(&component.to_string_lossy());
1471 fs::create_dir_all(&cur)?;
1472 let mut fname = p.file_name()
1473 .expect("source has no filename")
1475 fname.push(".html");
1477 href.push_str(&fname.to_string_lossy());
1479 let mut w = BufWriter::new(File::create(&cur)?);
1480 let title = format!("{} -- source", cur.file_name().expect("failed to get file name")
1481 .to_string_lossy());
1482 let desc = format!("Source to the Rust file `{}`.", filename);
1483 let page = layout::Page {
1485 css_class: "source",
1486 root_path: &root_path,
1487 static_root_path: self.scx.static_root_path.deref(),
1489 keywords: BASIC_KEYWORDS,
1490 resource_suffix: &self.scx.resource_suffix,
1491 extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
1492 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1494 layout::render(&mut w, &self.scx.layout,
1495 &page, &(""), &Source(contents),
1496 self.scx.css_file_extension.is_some(),
1498 self.scx.generate_search_filter)?;
1500 self.scx.local_sources.insert(p.clone(), href);
1505 impl DocFolder for Cache {
1506 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1507 if item.def_id.is_local() {
1508 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1511 // If this is a stripped module,
1512 // we don't want it or its children in the search index.
1513 let orig_stripped_mod = match item.inner {
1514 clean::StrippedItem(box clean::ModuleItem(..)) => {
1515 mem::replace(&mut self.stripped_mod, true)
1517 _ => self.stripped_mod,
1520 // If the impl is from a masked crate or references something from a
1521 // masked crate then remove it completely.
1522 if let clean::ImplItem(ref i) = item.inner {
1523 if self.masked_crates.contains(&item.def_id.krate) ||
1524 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1525 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1530 // Register any generics to their corresponding string. This is used
1531 // when pretty-printing types.
1532 if let Some(generics) = item.inner.generics() {
1533 self.generics(generics);
1536 // Propagate a trait method's documentation to all implementors of the
1538 if let clean::TraitItem(ref t) = item.inner {
1539 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1542 // Collect all the implementors of traits.
1543 if let clean::ImplItem(ref i) = item.inner {
1544 if let Some(did) = i.trait_.def_id() {
1545 if i.blanket_impl.is_none() {
1546 self.implementors.entry(did).or_default().push(Impl {
1547 impl_item: item.clone(),
1553 // Index this method for searching later on.
1554 if let Some(ref s) = item.name {
1555 let (parent, is_inherent_impl_item) = match item.inner {
1556 clean::StrippedItem(..) => ((None, None), false),
1557 clean::AssociatedConstItem(..) |
1558 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1559 // skip associated items in trait impls
1560 ((None, None), false)
1562 clean::AssociatedTypeItem(..) |
1563 clean::TyMethodItem(..) |
1564 clean::StructFieldItem(..) |
1565 clean::VariantItem(..) => {
1566 ((Some(*self.parent_stack.last().unwrap()),
1567 Some(&self.stack[..self.stack.len() - 1])),
1570 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1571 if self.parent_stack.is_empty() {
1572 ((None, None), false)
1574 let last = self.parent_stack.last().unwrap();
1576 let path = match self.paths.get(&did) {
1577 // The current stack not necessarily has correlation
1578 // for where the type was defined. On the other
1579 // hand, `paths` always has the right
1580 // information if present.
1581 Some(&(ref fqp, ItemType::Trait)) |
1582 Some(&(ref fqp, ItemType::Struct)) |
1583 Some(&(ref fqp, ItemType::Union)) |
1584 Some(&(ref fqp, ItemType::Enum)) =>
1585 Some(&fqp[..fqp.len() - 1]),
1586 Some(..) => Some(&*self.stack),
1589 ((Some(*last), path), true)
1592 _ => ((None, Some(&*self.stack)), false)
1596 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1597 debug_assert!(!item.is_stripped());
1599 // A crate has a module at its root, containing all items,
1600 // which should not be indexed. The crate-item itself is
1601 // inserted later on when serializing the search-index.
1602 if item.def_id.index != CRATE_DEF_INDEX {
1603 self.search_index.push(IndexItem {
1605 name: s.to_string(),
1606 path: path.join("::"),
1607 desc: plain_summary_line_short(item.doc_value()),
1610 search_type: get_index_search_type(&item),
1614 (Some(parent), None) if is_inherent_impl_item => {
1615 // We have a parent, but we don't know where they're
1616 // defined yet. Wait for later to index this item.
1617 self.orphan_impl_items.push((parent, item.clone()));
1623 // Keep track of the fully qualified path for this item.
1624 let pushed = match item.name {
1625 Some(ref n) if !n.is_empty() => {
1626 self.stack.push(n.to_string());
1633 clean::StructItem(..) | clean::EnumItem(..) |
1634 clean::TypedefItem(..) | clean::TraitItem(..) |
1635 clean::FunctionItem(..) | clean::ModuleItem(..) |
1636 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1637 clean::ConstantItem(..) | clean::StaticItem(..) |
1638 clean::UnionItem(..) | clean::ForeignTypeItem |
1639 clean::MacroItem(..) | clean::ProcMacroItem(..)
1640 if !self.stripped_mod => {
1641 // Re-exported items mean that the same id can show up twice
1642 // in the rustdoc ast that we're looking at. We know,
1643 // however, that a re-exported item doesn't show up in the
1644 // `public_items` map, so we can skip inserting into the
1645 // paths map if there was already an entry present and we're
1646 // not a public item.
1647 if !self.paths.contains_key(&item.def_id) ||
1648 self.access_levels.is_public(item.def_id)
1650 self.paths.insert(item.def_id,
1651 (self.stack.clone(), item.type_()));
1653 self.add_aliases(&item);
1655 // Link variants to their parent enum because pages aren't emitted
1656 // for each variant.
1657 clean::VariantItem(..) if !self.stripped_mod => {
1658 let mut stack = self.stack.clone();
1660 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1663 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1664 self.add_aliases(&item);
1665 self.paths.insert(item.def_id, (self.stack.clone(),
1672 // Maintain the parent stack
1673 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1674 let parent_pushed = match item.inner {
1675 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1676 clean::StructItem(..) | clean::UnionItem(..) => {
1677 self.parent_stack.push(item.def_id);
1678 self.parent_is_trait_impl = false;
1681 clean::ImplItem(ref i) => {
1682 self.parent_is_trait_impl = i.trait_.is_some();
1684 clean::ResolvedPath{ did, .. } => {
1685 self.parent_stack.push(did);
1689 let prim_did = t.primitive_type().and_then(|t| {
1690 self.primitive_locations.get(&t).cloned()
1694 self.parent_stack.push(did);
1705 // Once we've recursively found all the generics, hoard off all the
1706 // implementations elsewhere.
1707 let ret = self.fold_item_recur(item).and_then(|item| {
1708 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1709 // Figure out the id of this impl. This may map to a
1710 // primitive rather than always to a struct/enum.
1711 // Note: matching twice to restrict the lifetime of the `i` borrow.
1712 let mut dids = FxHashSet::default();
1713 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1715 clean::ResolvedPath { did, .. } |
1716 clean::BorrowedRef {
1717 type_: box clean::ResolvedPath { did, .. }, ..
1722 let did = t.primitive_type().and_then(|t| {
1723 self.primitive_locations.get(&t).cloned()
1726 if let Some(did) = did {
1732 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1733 for bound in generics {
1734 if let Some(did) = bound.def_id() {
1742 let impl_item = Impl {
1745 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1747 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1750 let trait_did = impl_item.trait_did().unwrap();
1751 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1759 if pushed { self.stack.pop().unwrap(); }
1760 if parent_pushed { self.parent_stack.pop().unwrap(); }
1761 self.stripped_mod = orig_stripped_mod;
1762 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1768 fn generics(&mut self, generics: &clean::Generics) {
1769 for param in &generics.params {
1771 clean::GenericParamDefKind::Lifetime => {}
1772 clean::GenericParamDefKind::Type { did, .. } |
1773 clean::GenericParamDefKind::Const { did, .. } => {
1774 self.param_names.insert(did, param.name.clone());
1780 fn add_aliases(&mut self, item: &clean::Item) {
1781 if item.def_id.index == CRATE_DEF_INDEX {
1784 if let Some(ref item_name) = item.name {
1785 let path = self.paths.get(&item.def_id)
1786 .map(|p| p.0[..p.0.len() - 1].join("::"))
1787 .unwrap_or("std".to_owned());
1788 for alias in item.attrs.lists(sym::doc)
1789 .filter(|a| a.check_name(sym::alias))
1790 .filter_map(|a| a.value_str()
1791 .map(|s| s.to_string().replace("\"", "")))
1792 .filter(|v| !v.is_empty())
1793 .collect::<FxHashSet<_>>()
1795 self.aliases.entry(alias)
1796 .or_insert(Vec::with_capacity(1))
1799 name: item_name.to_string(),
1801 desc: plain_summary_line_short(item.doc_value()),
1804 search_type: get_index_search_type(&item),
1811 #[derive(Debug, Eq, PartialEq, Hash)]
1818 fn new(mut url: String, name: String) -> ItemEntry {
1819 while url.starts_with('/') {
1829 impl fmt::Display for ItemEntry {
1830 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1835 impl PartialOrd for ItemEntry {
1836 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1837 Some(self.cmp(other))
1841 impl Ord for ItemEntry {
1842 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1843 self.name.cmp(&other.name)
1849 structs: FxHashSet<ItemEntry>,
1850 enums: FxHashSet<ItemEntry>,
1851 unions: FxHashSet<ItemEntry>,
1852 primitives: FxHashSet<ItemEntry>,
1853 traits: FxHashSet<ItemEntry>,
1854 macros: FxHashSet<ItemEntry>,
1855 functions: FxHashSet<ItemEntry>,
1856 typedefs: FxHashSet<ItemEntry>,
1857 existentials: FxHashSet<ItemEntry>,
1858 statics: FxHashSet<ItemEntry>,
1859 constants: FxHashSet<ItemEntry>,
1860 keywords: FxHashSet<ItemEntry>,
1861 attributes: FxHashSet<ItemEntry>,
1862 derives: FxHashSet<ItemEntry>,
1863 trait_aliases: FxHashSet<ItemEntry>,
1867 fn new() -> AllTypes {
1868 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1870 structs: new_set(100),
1871 enums: new_set(100),
1872 unions: new_set(100),
1873 primitives: new_set(26),
1874 traits: new_set(100),
1875 macros: new_set(100),
1876 functions: new_set(100),
1877 typedefs: new_set(100),
1878 existentials: new_set(100),
1879 statics: new_set(100),
1880 constants: new_set(100),
1881 keywords: new_set(100),
1882 attributes: new_set(100),
1883 derives: new_set(100),
1884 trait_aliases: new_set(100),
1888 fn append(&mut self, item_name: String, item_type: &ItemType) {
1889 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1890 if let Some(name) = url.pop() {
1891 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1893 let name = url.join("::");
1895 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1896 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1897 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1898 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1899 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1900 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1901 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1902 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1903 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1904 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1905 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1906 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1907 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1908 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1915 fn print_entries(f: &mut fmt::Formatter<'_>, e: &FxHashSet<ItemEntry>, title: &str,
1916 class: &str) -> fmt::Result {
1918 let mut e: Vec<&ItemEntry> = e.iter().collect();
1920 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1924 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1929 impl fmt::Display for AllTypes {
1930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1933 <span class='out-of-band'>\
1934 <span id='render-detail'>\
1935 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1936 [<span class='inner'>−</span>]\
1940 <span class='in-band'>List of all items</span>\
1942 print_entries(f, &self.structs, "Structs", "structs")?;
1943 print_entries(f, &self.enums, "Enums", "enums")?;
1944 print_entries(f, &self.unions, "Unions", "unions")?;
1945 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1946 print_entries(f, &self.traits, "Traits", "traits")?;
1947 print_entries(f, &self.macros, "Macros", "macros")?;
1948 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1949 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1950 print_entries(f, &self.functions, "Functions", "functions")?;
1951 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1952 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1953 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1954 print_entries(f, &self.statics, "Statics", "statics")?;
1955 print_entries(f, &self.constants, "Constants", "constants")
1960 struct Settings<'a> {
1961 // (id, explanation, default value)
1962 settings: Vec<(&'static str, &'static str, bool)>,
1967 impl<'a> Settings<'a> {
1968 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1971 ("item-declarations", "Auto-hide item declarations.", true),
1972 ("item-attributes", "Auto-hide item attributes.", true),
1973 ("trait-implementations", "Auto-hide trait implementations documentation",
1975 ("method-docs", "Auto-hide item methods' documentation", false),
1976 ("go-to-only-result", "Directly go to item in search if there is only one result",
1978 ("line-numbers", "Show line numbers on code examples", false),
1986 impl<'a> fmt::Display for Settings<'a> {
1987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1990 <span class='in-band'>Rustdoc settings</span>\
1992 <div class='settings'>{}</div>\
1993 <script src='{}settings{}.js'></script>",
1994 self.settings.iter()
1995 .map(|(id, text, enabled)| {
1996 format!("<div class='setting-line'>\
1997 <label class='toggle'>\
1998 <input type='checkbox' id='{}' {}>\
1999 <span class='slider'></span>\
2002 </div>", id, if *enabled { " checked" } else { "" }, text)
2004 .collect::<String>(),
2011 fn derive_id(&self, id: String) -> String {
2012 let mut map = self.id_map.borrow_mut();
2016 /// String representation of how to get back to the root path of the 'doc/'
2017 /// folder in terms of a relative URL.
2018 fn root_path(&self) -> String {
2019 "../".repeat(self.current.len())
2022 /// Recurse in the directory structure and change the "root path" to make
2023 /// sure it always points to the top (relatively).
2024 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2025 F: FnOnce(&mut Context) -> T,
2028 panic!("Unexpected empty destination: {:?}", self.current);
2030 let prev = self.dst.clone();
2032 self.current.push(s);
2034 info!("Recursing into {}", self.dst.display());
2038 info!("Recursed; leaving {}", self.dst.display());
2040 // Go back to where we were at
2042 self.current.pop().unwrap();
2047 /// Main method for rendering a crate.
2049 /// This currently isn't parallelized, but it'd be pretty easy to add
2050 /// parallelization to this function.
2051 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2052 let mut item = match krate.module.take() {
2054 None => return Ok(()),
2056 let final_file = self.dst.join(&krate.name)
2058 let settings_file = self.dst.join("settings.html");
2060 let crate_name = krate.name.clone();
2061 item.name = Some(krate.name);
2063 let mut all = AllTypes::new();
2066 // Render the crate documentation
2067 let mut work = vec![(self.clone(), item)];
2069 while let Some((mut cx, item)) = work.pop() {
2070 cx.item(item, &mut all, |cx, item| {
2071 work.push((cx.clone(), item))
2076 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2077 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2078 if !root_path.ends_with('/') {
2079 root_path.push('/');
2081 let mut page = layout::Page {
2082 title: "List of all items in this crate",
2085 static_root_path: self.shared.static_root_path.deref(),
2086 description: "List of all items in this crate",
2087 keywords: BASIC_KEYWORDS,
2088 resource_suffix: &self.shared.resource_suffix,
2090 static_extra_scripts: &[],
2092 let sidebar = if let Some(ref version) = cache().crate_version {
2093 format!("<p class='location'>Crate {}</p>\
2094 <div class='block version'>\
2097 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2098 crate_name, version)
2102 try_err!(layout::render(&mut w, &self.shared.layout,
2103 &page, &sidebar, &all,
2104 self.shared.css_file_extension.is_some(),
2105 &self.shared.themes,
2106 self.shared.generate_search_filter),
2109 // Generating settings page.
2110 let settings = Settings::new(self.shared.static_root_path.deref().unwrap_or("./"),
2111 &self.shared.resource_suffix);
2112 page.title = "Rustdoc settings";
2113 page.description = "Settings of Rustdoc";
2114 page.root_path = "./";
2116 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2117 let mut themes = self.shared.themes.clone();
2118 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2119 themes.push(PathBuf::from("settings.css"));
2120 let layout = self.shared.layout.clone();
2121 try_err!(layout::render(&mut w, &layout,
2122 &page, &sidebar, &settings,
2123 self.shared.css_file_extension.is_some(),
2125 self.shared.generate_search_filter),
2131 fn render_item(&self,
2132 writer: &mut dyn io::Write,
2136 // A little unfortunate that this is done like this, but it sure
2137 // does make formatting *a lot* nicer.
2138 CURRENT_LOCATION_KEY.with(|slot| {
2139 *slot.borrow_mut() = self.current.clone();
2142 let mut title = if it.is_primitive() || it.is_keyword() {
2143 // No need to include the namespace for primitive types and keywords
2146 self.current.join("::")
2149 if !title.is_empty() {
2150 title.push_str("::");
2152 title.push_str(it.name.as_ref().unwrap());
2154 title.push_str(" - Rust");
2155 let tyname = it.type_().css_class();
2156 let desc = if it.is_crate() {
2157 format!("API documentation for the Rust `{}` crate.",
2158 self.shared.layout.krate)
2160 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2161 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2163 let keywords = make_item_keywords(it);
2164 let page = layout::Page {
2166 root_path: &self.root_path(),
2167 static_root_path: self.shared.static_root_path.deref(),
2170 keywords: &keywords,
2171 resource_suffix: &self.shared.resource_suffix,
2173 static_extra_scripts: &[],
2177 self.id_map.borrow_mut().reset();
2178 self.id_map.borrow_mut().populate(initial_ids());
2181 if !self.render_redirect_pages {
2182 layout::render(writer, &self.shared.layout, &page,
2183 &Sidebar{ cx: self, item: it },
2184 &Item{ cx: self, item: it },
2185 self.shared.css_file_extension.is_some(),
2186 &self.shared.themes,
2187 self.shared.generate_search_filter)?;
2189 let mut url = self.root_path();
2190 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2191 for name in &names[..names.len() - 1] {
2195 url.push_str(&item_path(ty, names.last().unwrap()));
2196 layout::redirect(writer, &url)?;
2202 /// Non-parallelized version of rendering an item. This will take the input
2203 /// item, render its contents, and then invoke the specified closure with
2204 /// all sub-items which need to be rendered.
2206 /// The rendering driver uses this closure to queue up more work.
2207 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2208 where F: FnMut(&mut Context, clean::Item),
2210 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2211 // if they contain impls for public types. These modules can also
2212 // contain items such as publicly re-exported structures.
2214 // External crates will provide links to these structures, so
2215 // these modules are recursed into, but not rendered normally
2216 // (a flag on the context).
2217 if !self.render_redirect_pages {
2218 self.render_redirect_pages = item.is_stripped();
2222 // modules are special because they add a namespace. We also need to
2223 // recurse into the items of the module as well.
2224 let name = item.name.as_ref().unwrap().to_string();
2225 let mut item = Some(item);
2226 self.recurse(name, |this| {
2227 let item = item.take().unwrap();
2229 let mut buf = Vec::new();
2230 this.render_item(&mut buf, &item, false).unwrap();
2231 // buf will be empty if the module is stripped and there is no redirect for it
2232 if !buf.is_empty() {
2233 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2234 let joint_dst = this.dst.join("index.html");
2235 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2238 let m = match item.inner {
2239 clean::StrippedItem(box clean::ModuleItem(m)) |
2240 clean::ModuleItem(m) => m,
2244 // Render sidebar-items.js used throughout this module.
2245 if !this.render_redirect_pages {
2246 let items = this.build_sidebar_items(&m);
2247 let js_dst = this.dst.join("sidebar-items.js");
2248 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2249 try_err!(write!(&mut js_out, "initSidebarItems({});",
2250 as_json(&items)), &js_dst);
2253 for item in m.items {
2259 } else if item.name.is_some() {
2260 let mut buf = Vec::new();
2261 self.render_item(&mut buf, &item, true).unwrap();
2262 // buf will be empty if the item is stripped and there is no redirect for it
2263 if !buf.is_empty() {
2264 let name = item.name.as_ref().unwrap();
2265 let item_type = item.type_();
2266 let file_name = &item_path(item_type, name);
2267 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2268 let joint_dst = self.dst.join(file_name);
2269 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2271 if !self.render_redirect_pages {
2272 all.append(full_path(self, &item), &item_type);
2274 if self.shared.generate_redirect_pages {
2275 // Redirect from a sane URL using the namespace to Rustdoc's
2276 // URL for the page.
2277 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2278 let redir_dst = self.dst.join(redir_name);
2279 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2282 let mut redirect_out = BufWriter::new(redirect_out);
2283 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2286 // If the item is a macro, redirect from the old macro URL (with !)
2287 // to the new one (without).
2288 if item_type == ItemType::Macro {
2289 let redir_name = format!("{}.{}!.html", item_type, name);
2290 let redir_dst = self.dst.join(redir_name);
2291 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2292 let mut redirect_out = BufWriter::new(redirect_out);
2293 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2300 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2301 // BTreeMap instead of HashMap to get a sorted output
2302 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2303 for item in &m.items {
2304 if item.is_stripped() { continue }
2306 let short = item.type_().css_class();
2307 let myname = match item.name {
2309 Some(ref s) => s.to_string(),
2311 let short = short.to_string();
2312 map.entry(short).or_default()
2313 .push((myname, Some(plain_summary_line(item.doc_value()))));
2316 if self.shared.sort_modules_alphabetically {
2317 for (_, items) in &mut map {
2326 /// Generates a url appropriate for an `href` attribute back to the source of
2329 /// The url generated, when clicked, will redirect the browser back to the
2330 /// original source code.
2332 /// If `None` is returned, then a source link couldn't be generated. This
2333 /// may happen, for example, with externally inlined items where the source
2334 /// of their crate documentation isn't known.
2335 fn src_href(&self) -> Option<String> {
2336 let mut root = self.cx.root_path();
2338 let cache = cache();
2339 let mut path = String::new();
2341 // We can safely ignore macros from other libraries
2342 let file = match self.item.source.filename {
2343 FileName::Real(ref path) => path,
2347 let (krate, path) = if self.item.def_id.is_local() {
2348 if let Some(path) = self.cx.shared.local_sources.get(file) {
2349 (&self.cx.shared.layout.krate, path)
2354 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2355 (ref name, ref src, Local) => (name, src),
2356 (ref name, ref src, Remote(ref s)) => {
2357 root = s.to_string();
2360 (_, _, Unknown) => return None,
2363 clean_srcpath(&src_root, file, false, |component| {
2364 path.push_str(&component.to_string_lossy());
2367 let mut fname = file.file_name().expect("source has no filename")
2369 fname.push(".html");
2370 path.push_str(&fname.to_string_lossy());
2374 let lines = if self.item.source.loline == self.item.source.hiline {
2375 self.item.source.loline.to_string()
2377 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2379 Some(format!("{root}src/{krate}/{path}#{lines}",
2380 root = Escape(&root),
2387 fn wrap_into_docblock<F>(w: &mut fmt::Formatter<'_>,
2388 f: F) -> fmt::Result
2389 where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result {
2390 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2395 impl<'a> fmt::Display for Item<'a> {
2396 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2397 debug_assert!(!self.item.is_stripped());
2398 // Write the breadcrumb trail header for the top
2399 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2400 if let Some(version) = self.item.stable_since() {
2401 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2405 "<span id='render-detail'>\
2406 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2407 title=\"collapse all docs\">\
2408 [<span class='inner'>−</span>]\
2414 // When this item is part of a `pub use` in a downstream crate, the
2415 // [src] link in the downstream documentation will actually come back to
2416 // this page, and this link will be auto-clicked. The `id` attribute is
2417 // used to find the link to auto-click.
2418 if self.cx.shared.include_sources && !self.item.is_primitive() {
2419 if let Some(l) = self.src_href() {
2420 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2421 l, "goto source code")?;
2425 write!(fmt, "</span>")?; // out-of-band
2426 write!(fmt, "<span class='in-band'>")?;
2427 match self.item.inner {
2428 clean::ModuleItem(ref m) => if m.is_crate {
2429 write!(fmt, "Crate ")?;
2431 write!(fmt, "Module ")?;
2433 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2434 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2435 clean::StructItem(..) => write!(fmt, "Struct ")?,
2436 clean::UnionItem(..) => write!(fmt, "Union ")?,
2437 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2438 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2439 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2440 clean::ProcMacroItem(ref mac) => match mac.kind {
2441 MacroKind::Bang => write!(fmt, "Macro ")?,
2442 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2443 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2444 MacroKind::ProcMacroStub => unreachable!(),
2446 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2447 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2448 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2449 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2450 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2451 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2452 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2454 // We don't generate pages for any other type.
2458 if !self.item.is_primitive() && !self.item.is_keyword() {
2459 let cur = &self.cx.current;
2460 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2461 for (i, component) in cur.iter().enumerate().take(amt) {
2462 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2463 "../".repeat(cur.len() - i - 1),
2467 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2468 self.item.type_(), self.item.name.as_ref().unwrap())?;
2470 write!(fmt, "</span></h1>")?; // in-band
2472 match self.item.inner {
2473 clean::ModuleItem(ref m) =>
2474 item_module(fmt, self.cx, self.item, &m.items),
2475 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2476 item_function(fmt, self.cx, self.item, f),
2477 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2478 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2479 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2480 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2481 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2482 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2483 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2484 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2485 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2486 item_static(fmt, self.cx, self.item, i),
2487 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2488 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2489 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2490 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2491 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2493 // We don't generate pages for any other type.
2500 fn item_path(ty: ItemType, name: &str) -> String {
2502 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2503 _ => format!("{}.{}.html", ty.css_class(), name),
2507 fn full_path(cx: &Context, item: &clean::Item) -> String {
2508 let mut s = cx.current.join("::");
2510 s.push_str(item.name.as_ref().unwrap());
2514 fn shorter<'a>(s: Option<&'a str>) -> String {
2516 Some(s) => s.lines()
2517 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2519 (*line).chars().any(|chr|{
2520 !chr.is_whitespace()
2522 }).collect::<Vec<_>>().join("\n"),
2523 None => String::new()
2528 fn plain_summary_line(s: Option<&str>) -> String {
2529 let line = shorter(s).replace("\n", " ");
2530 markdown::plain_summary_line_full(&line[..], false)
2534 fn plain_summary_line_short(s: Option<&str>) -> String {
2535 let line = shorter(s).replace("\n", " ");
2536 markdown::plain_summary_line_full(&line[..], true)
2539 fn document(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item) -> fmt::Result {
2540 if let Some(ref name) = item.name {
2541 info!("Documenting {}", name);
2543 document_stability(w, cx, item, false)?;
2544 document_full(w, item, cx, "", false)?;
2548 /// Render md_text as markdown.
2549 fn render_markdown(w: &mut fmt::Formatter<'_>,
2552 links: Vec<(String, String)>,
2556 let mut ids = cx.id_map.borrow_mut();
2557 write!(w, "<div class='docblock{}'>{}{}</div>",
2558 if is_hidden { " hidden" } else { "" },
2560 Markdown(md_text, &links, RefCell::new(&mut ids),
2561 cx.codes, cx.edition))
2565 w: &mut fmt::Formatter<'_>,
2568 link: AssocItemLink<'_>,
2569 prefix: &str, is_hidden: bool
2571 if let Some(s) = item.doc_value() {
2572 let markdown = if s.contains('\n') {
2573 format!("{} [Read more]({})",
2574 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2576 plain_summary_line(Some(s))
2578 render_markdown(w, cx, &markdown, 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_full(w: &mut fmt::Formatter<'_>, item: &clean::Item,
2588 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2589 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2590 debug!("Doc block: =====\n{}\n=====", s);
2591 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2592 } else if !prefix.is_empty() {
2593 write!(w, "<div class='docblock{}'>{}</div>",
2594 if is_hidden { " hidden" } else { "" },
2600 fn document_stability(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
2601 is_hidden: bool) -> fmt::Result {
2602 let stabilities = short_stability(item, cx);
2603 if !stabilities.is_empty() {
2604 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2605 for stability in stabilities {
2606 write!(w, "{}", stability)?;
2608 write!(w, "</div>")?;
2613 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2614 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2617 fn document_non_exhaustive(w: &mut fmt::Formatter<'_>, item: &clean::Item) -> fmt::Result {
2618 if item.is_non_exhaustive() {
2619 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2620 if item.is_struct() {
2622 } else if item.is_enum() {
2624 } else if item.is_variant() {
2631 if item.is_struct() {
2632 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2633 Therefore, non-exhaustive structs cannot be constructed in external crates \
2634 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2635 matched against without a wildcard <code>..</code>; and \
2636 struct update syntax will not work.")?;
2637 } else if item.is_enum() {
2638 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2639 Therefore, when matching against variants of non-exhaustive enums, an \
2640 extra wildcard arm must be added to account for any future variants.")?;
2641 } else if item.is_variant() {
2642 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
2643 Therefore, non-exhaustive enum variants cannot be constructed in external \
2644 crates and cannot be matched against.")?;
2646 write!(w, "This type will require a wildcard arm in any match statements or \
2650 write!(w, "</div>")?;
2656 fn name_key(name: &str) -> (&str, u64, usize) {
2657 let end = name.bytes()
2658 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2660 // find number at end
2661 let split = name[0..end].bytes()
2662 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2664 // count leading zeroes
2666 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2668 // sort leading zeroes last
2669 let num_zeroes = after_zeroes - split;
2671 match name[split..end].parse() {
2672 Ok(n) => (&name[..split], n, num_zeroes),
2673 Err(_) => (name, 0, num_zeroes),
2677 fn item_module(w: &mut fmt::Formatter<'_>, cx: &Context,
2678 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2679 document(w, cx, item)?;
2681 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2683 // the order of item types in the listing
2684 fn reorder(ty: ItemType) -> u8 {
2686 ItemType::ExternCrate => 0,
2687 ItemType::Import => 1,
2688 ItemType::Primitive => 2,
2689 ItemType::Module => 3,
2690 ItemType::Macro => 4,
2691 ItemType::Struct => 5,
2692 ItemType::Enum => 6,
2693 ItemType::Constant => 7,
2694 ItemType::Static => 8,
2695 ItemType::Trait => 9,
2696 ItemType::Function => 10,
2697 ItemType::Typedef => 12,
2698 ItemType::Union => 13,
2703 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2704 let ty1 = i1.type_();
2705 let ty2 = i2.type_();
2707 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2709 let s1 = i1.stability.as_ref().map(|s| s.level);
2710 let s2 = i2.stability.as_ref().map(|s| s.level);
2712 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2713 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2716 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2717 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2718 name_key(lhs).cmp(&name_key(rhs))
2721 if cx.shared.sort_modules_alphabetically {
2722 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2724 // This call is to remove re-export duplicates in cases such as:
2729 // pub trait Double { fn foo(); }
2733 // pub use foo::bar::*;
2737 // `Double` will appear twice in the generated docs.
2739 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2740 // can be identical even if the elements are different (mostly in imports).
2741 // So in case this is an import, we keep everything by adding a "unique id"
2742 // (which is the position in the vector).
2743 indices.dedup_by_key(|i| (items[*i].def_id,
2744 if items[*i].name.as_ref().is_some() {
2745 Some(full_path(cx, &items[*i]))
2750 if items[*i].is_import() {
2756 debug!("{:?}", indices);
2757 let mut curty = None;
2758 for &idx in &indices {
2759 let myitem = &items[idx];
2760 if myitem.is_stripped() {
2764 let myty = Some(myitem.type_());
2765 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2766 // Put `extern crate` and `use` re-exports in the same section.
2768 } else if myty != curty {
2769 if curty.is_some() {
2770 write!(w, "</table>")?;
2773 let (short, name) = item_ty_to_strs(&myty.unwrap());
2774 write!(w, "<h2 id='{id}' class='section-header'>\
2775 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2776 id = cx.derive_id(short.to_owned()), name = name)?;
2779 match myitem.inner {
2780 clean::ExternCrateItem(ref name, ref src) => {
2781 use crate::html::format::HRef;
2785 write!(w, "<tr><td><code>{}extern crate {} as {};",
2786 VisSpace(&myitem.visibility),
2787 HRef::new(myitem.def_id, src),
2791 write!(w, "<tr><td><code>{}extern crate {};",
2792 VisSpace(&myitem.visibility),
2793 HRef::new(myitem.def_id, name))?
2796 write!(w, "</code></td></tr>")?;
2799 clean::ImportItem(ref import) => {
2800 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2801 VisSpace(&myitem.visibility), *import)?;
2805 if myitem.name.is_none() { continue }
2807 let unsafety_flag = match myitem.inner {
2808 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2809 if func.header.unsafety == hir::Unsafety::Unsafe => {
2810 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2815 let stab = myitem.stability_class();
2816 let add = if stab.is_some() {
2822 let doc_value = myitem.doc_value().unwrap_or("");
2824 <tr class='{stab}{add}module-item'>\
2825 <td><a class=\"{class}\" href=\"{href}\" \
2826 title='{title}'>{name}</a>{unsafety_flag}</td>\
2827 <td class='docblock-short'>{stab_tags}{docs}</td>\
2829 name = *myitem.name.as_ref().unwrap(),
2830 stab_tags = stability_tags(myitem),
2831 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2832 class = myitem.type_(),
2834 stab = stab.unwrap_or_else(|| String::new()),
2835 unsafety_flag = unsafety_flag,
2836 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2837 title = [full_path(cx, myitem), myitem.type_().to_string()]
2839 .filter_map(|s| if !s.is_empty() {
2844 .collect::<Vec<_>>()
2851 if curty.is_some() {
2852 write!(w, "</table>")?;
2857 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2859 fn stability_tags(item: &clean::Item) -> String {
2860 let mut tags = String::new();
2862 fn tag_html(class: &str, contents: &str) -> String {
2863 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2866 // The trailing space after each tag is to space it properly against the rest of the docs.
2867 if item.deprecation().is_some() {
2868 let mut message = "Deprecated";
2869 if let Some(ref stab) = item.stability {
2870 if let Some(ref depr) = stab.deprecation {
2871 if let Some(ref since) = depr.since {
2872 if !stability::deprecation_in_effect(&since) {
2873 message = "Deprecation planned";
2878 tags += &tag_html("deprecated", message);
2881 if let Some(stab) = item
2884 .filter(|s| s.level == stability::Unstable)
2886 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2887 tags += &tag_html("internal", "Internal");
2889 tags += &tag_html("unstable", "Experimental");
2893 if let Some(ref cfg) = item.attrs.cfg {
2894 tags += &tag_html("portability", &cfg.render_short_html());
2900 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2902 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2903 let mut stability = vec![];
2904 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2906 if let Some(Deprecation { note, since }) = &item.deprecation() {
2907 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2908 // but only display the future-deprecation messages for #[rustc_deprecated].
2909 let mut message = if let Some(since) = since {
2910 format!("Deprecated since {}", Escape(since))
2912 String::from("Deprecated")
2914 if let Some(ref stab) = item.stability {
2915 if let Some(ref depr) = stab.deprecation {
2916 if let Some(ref since) = depr.since {
2917 if !stability::deprecation_in_effect(&since) {
2918 message = format!("Deprecating in {}", Escape(&since));
2924 if let Some(note) = note {
2925 let mut ids = cx.id_map.borrow_mut();
2926 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes, cx.edition);
2927 message.push_str(&format!(": {}", html));
2929 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2932 if let Some(stab) = item
2935 .filter(|stab| stab.level == stability::Unstable)
2937 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2939 let mut message = if is_rustc_private {
2940 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2942 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2946 if let Some(feature) = stab.feature.as_ref() {
2947 let mut feature = format!("<code>{}</code>", Escape(&feature));
2948 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2949 feature.push_str(&format!(
2950 " <a href=\"{url}{issue}\">#{issue}</a>",
2956 message.push_str(&format!(" ({})", feature));
2959 if let Some(unstable_reason) = &stab.unstable_reason {
2960 // Provide a more informative message than the compiler help.
2961 let unstable_reason = if is_rustc_private {
2962 "This crate is being loaded from the sysroot, a permanently unstable location \
2963 for private compiler dependencies. It is not intended for general use. Prefer \
2964 using a public version of this crate from \
2965 [crates.io](https://crates.io) via [`Cargo.toml`]\
2966 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2971 let mut ids = cx.id_map.borrow_mut();
2973 "<details><summary>{}</summary>{}</details>",
2975 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes, cx.edition)
2979 let class = if is_rustc_private {
2984 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2987 if let Some(ref cfg) = item.attrs.cfg {
2988 stability.push(format!(
2989 "<div class='stab portability'>{}</div>",
2990 cfg.render_long_html()
2997 fn item_constant(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2998 c: &clean::Constant) -> fmt::Result {
2999 write!(w, "<pre class='rust const'>")?;
3000 render_attributes(w, it, false)?;
3001 write!(w, "{vis}const \
3002 {name}: {typ}</pre>",
3003 vis = VisSpace(&it.visibility),
3004 name = it.name.as_ref().unwrap(),
3009 fn item_static(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3010 s: &clean::Static) -> fmt::Result {
3011 write!(w, "<pre class='rust static'>")?;
3012 render_attributes(w, it, false)?;
3013 write!(w, "{vis}static {mutability}\
3014 {name}: {typ}</pre>",
3015 vis = VisSpace(&it.visibility),
3016 mutability = MutableSpace(s.mutability),
3017 name = it.name.as_ref().unwrap(),
3022 fn item_function(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3023 f: &clean::Function) -> fmt::Result {
3024 let header_len = format!(
3025 "{}{}{}{}{:#}fn {}{:#}",
3026 VisSpace(&it.visibility),
3027 ConstnessSpace(f.header.constness),
3028 UnsafetySpace(f.header.unsafety),
3029 AsyncSpace(f.header.asyncness),
3030 AbiSpace(f.header.abi),
3031 it.name.as_ref().unwrap(),
3034 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
3035 render_attributes(w, it, false)?;
3037 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
3038 {name}{generics}{decl}{where_clause}</pre>",
3039 vis = VisSpace(&it.visibility),
3040 constness = ConstnessSpace(f.header.constness),
3041 unsafety = UnsafetySpace(f.header.unsafety),
3042 asyncness = AsyncSpace(f.header.asyncness),
3043 abi = AbiSpace(f.header.abi),
3044 name = it.name.as_ref().unwrap(),
3045 generics = f.generics,
3046 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
3051 asyncness: f.header.asyncness,
3056 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter<'_>,
3057 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
3058 // If there's already another implementor that has the same abbridged name, use the
3059 // full path, for example in `std::iter::ExactSizeIterator`
3060 let use_absolute = match implementor.inner_impl().for_ {
3061 clean::ResolvedPath { ref path, is_generic: false, .. } |
3062 clean::BorrowedRef {
3063 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3065 } => implementor_dups[path.last_name()].1,
3068 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3069 implementor.impl_item.stable_since(), false, Some(use_absolute), false)?;
3073 fn render_impls(cx: &Context, w: &mut fmt::Formatter<'_>,
3075 containing_item: &clean::Item) -> fmt::Result {
3077 let did = i.trait_did().unwrap();
3078 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3079 render_impl(w, cx, i, assoc_link,
3080 RenderMode::Normal, containing_item.stable_since(), true, None, false)?;
3085 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3086 let mut bounds = String::new();
3087 if !t_bounds.is_empty() {
3089 bounds.push_str(": ");
3091 for (i, p) in t_bounds.iter().enumerate() {
3093 bounds.push_str(" + ");
3095 bounds.push_str(&(*p).to_string());
3101 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3102 let lhs = format!("{}", lhs.inner_impl());
3103 let rhs = format!("{}", rhs.inner_impl());
3105 // lhs and rhs are formatted as HTML, which may be unnecessary
3106 name_key(&lhs).cmp(&name_key(&rhs))
3110 w: &mut fmt::Formatter<'_>,
3115 let bounds = bounds(&t.bounds, false);
3116 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3117 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3118 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3119 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3121 // Output the trait definition
3122 wrap_into_docblock(w, |w| {
3123 write!(w, "<pre class='rust trait'>")?;
3124 render_attributes(w, it, true)?;
3125 write!(w, "{}{}{}trait {}{}{}",
3126 VisSpace(&it.visibility),
3127 UnsafetySpace(t.unsafety),
3128 if t.is_auto { "auto " } else { "" },
3129 it.name.as_ref().unwrap(),
3133 if !t.generics.where_predicates.is_empty() {
3134 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3139 if t.items.is_empty() {
3140 write!(w, "{{ }}")?;
3142 // FIXME: we should be using a derived_id for the Anchors here
3145 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3148 if !types.is_empty() && !consts.is_empty() {
3152 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3155 if !consts.is_empty() && !required.is_empty() {
3158 for (pos, m) in required.iter().enumerate() {
3159 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3162 if pos < required.len() - 1 {
3163 write!(w, "<div class='item-spacer'></div>")?;
3166 if !required.is_empty() && !provided.is_empty() {
3169 for (pos, m) in provided.iter().enumerate() {
3170 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3172 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3173 write!(w, ",\n {{ ... }}\n")?;
3176 write!(w, " {{ ... }}\n")?;
3179 if pos < provided.len() - 1 {
3180 write!(w, "<div class='item-spacer'></div>")?;
3188 // Trait documentation
3189 document(w, cx, it)?;
3191 fn write_small_section_header(
3192 w: &mut fmt::Formatter<'_>,
3195 extra_content: &str,
3198 <h2 id='{0}' class='small-section-header'>\
3199 {1}<a href='#{0}' class='anchor'></a>\
3200 </h2>{2}", id, title, extra_content)
3203 fn write_loading_content(w: &mut fmt::Formatter<'_>, extra_content: &str) -> fmt::Result {
3204 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3207 fn trait_item(w: &mut fmt::Formatter<'_>, cx: &Context, m: &clean::Item, t: &clean::Item)
3209 let name = m.name.as_ref().unwrap();
3210 let item_type = m.type_();
3211 let id = cx.derive_id(format!("{}.{}", item_type, name));
3212 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3213 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3214 extra = render_spotlight_traits(m)?,
3217 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3218 write!(w, "</code>")?;
3219 render_stability_since(w, m, t)?;
3220 write!(w, "</h3>")?;
3221 document(w, cx, m)?;
3225 if !types.is_empty() {
3226 write_small_section_header(w, "associated-types", "Associated Types",
3227 "<div class='methods'>")?;
3229 trait_item(w, cx, *t, it)?;
3231 write_loading_content(w, "</div>")?;
3234 if !consts.is_empty() {
3235 write_small_section_header(w, "associated-const", "Associated Constants",
3236 "<div class='methods'>")?;
3238 trait_item(w, cx, *t, it)?;
3240 write_loading_content(w, "</div>")?;
3243 // Output the documentation for each function individually
3244 if !required.is_empty() {
3245 write_small_section_header(w, "required-methods", "Required methods",
3246 "<div class='methods'>")?;
3247 for m in &required {
3248 trait_item(w, cx, *m, it)?;
3250 write_loading_content(w, "</div>")?;
3252 if !provided.is_empty() {
3253 write_small_section_header(w, "provided-methods", "Provided methods",
3254 "<div class='methods'>")?;
3255 for m in &provided {
3256 trait_item(w, cx, *m, it)?;
3258 write_loading_content(w, "</div>")?;
3261 // If there are methods directly on this trait object, render them here.
3262 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3264 let cache = cache();
3266 let mut synthetic_types = Vec::new();
3268 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3269 // The DefId is for the first Type found with that name. The bool is
3270 // if any Types with the same name but different DefId have been found.
3271 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3272 for implementor in implementors {
3273 match implementor.inner_impl().for_ {
3274 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3275 clean::BorrowedRef {
3276 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3279 let &mut (prev_did, ref mut has_duplicates) =
3280 implementor_dups.entry(path.last_name()).or_insert((did, false));
3281 if prev_did != did {
3282 *has_duplicates = true;
3289 let (local, foreign) = implementors.iter()
3290 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3291 .map_or(true, |d| cache.paths.contains_key(&d)));
3294 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3295 .partition(|i| i.inner_impl().synthetic);
3297 synthetic.sort_by(compare_impl);
3298 concrete.sort_by(compare_impl);
3300 if !foreign.is_empty() {
3301 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3303 for implementor in foreign {
3304 let assoc_link = AssocItemLink::GotoSource(
3305 implementor.impl_item.def_id,
3306 &implementor.inner_impl().provided_trait_methods
3308 render_impl(w, cx, &implementor, assoc_link,
3309 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3312 write_loading_content(w, "")?;
3315 write_small_section_header(w, "implementors", "Implementors",
3316 "<div class='item-list' id='implementors-list'>")?;
3317 for implementor in concrete {
3318 render_implementor(cx, implementor, w, &implementor_dups)?;
3320 write_loading_content(w, "</div>")?;
3323 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3324 "<div class='item-list' id='synthetic-implementors-list'>")?;
3325 for implementor in synthetic {
3326 synthetic_types.extend(
3327 collect_paths_for_type(implementor.inner_impl().for_.clone())
3329 render_implementor(cx, implementor, w, &implementor_dups)?;
3331 write_loading_content(w, "</div>")?;
3334 // even without any implementations to write in, we still want the heading and list, so the
3335 // implementors javascript file pulled in below has somewhere to write the impls into
3336 write_small_section_header(w, "implementors", "Implementors",
3337 "<div class='item-list' id='implementors-list'>")?;
3338 write_loading_content(w, "</div>")?;
3341 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3342 "<div class='item-list' id='synthetic-implementors-list'>")?;
3343 write_loading_content(w, "</div>")?;
3346 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3347 as_json(&synthetic_types))?;
3349 write!(w, r#"<script type="text/javascript" async
3350 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3352 root_path = vec![".."; cx.current.len()].join("/"),
3353 path = if it.def_id.is_local() {
3354 cx.current.join("/")
3356 let (ref path, _) = cache.external_paths[&it.def_id];
3357 path[..path.len() - 1].join("/")
3359 ty = it.type_().css_class(),
3360 name = *it.name.as_ref().unwrap())?;
3364 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
3365 use crate::html::item_type::ItemType::*;
3367 let name = it.name.as_ref().unwrap();
3368 let ty = match it.type_() {
3369 Typedef | AssociatedType => AssociatedType,
3373 let anchor = format!("#{}.{}", ty, name);
3375 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3376 AssocItemLink::Anchor(None) => anchor,
3377 AssocItemLink::GotoSource(did, _) => {
3378 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3383 fn assoc_const(w: &mut fmt::Formatter<'_>,
3386 _default: Option<&String>,
3387 link: AssocItemLink<'_>,
3388 extra: &str) -> fmt::Result {
3389 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3391 VisSpace(&it.visibility),
3392 naive_assoc_href(it, link),
3393 it.name.as_ref().unwrap(),
3398 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3399 bounds: &[clean::GenericBound],
3400 default: Option<&clean::Type>,
3401 link: AssocItemLink<'_>,
3402 extra: &str) -> fmt::Result {
3403 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
3405 naive_assoc_href(it, link),
3406 it.name.as_ref().unwrap())?;
3407 if !bounds.is_empty() {
3408 write!(w, ": {}", GenericBounds(bounds))?
3410 if let Some(default) = default {
3411 write!(w, " = {}", default)?;
3416 fn render_stability_since_raw<'a, T: fmt::Write>(
3418 ver: Option<&'a str>,
3419 containing_ver: Option<&'a str>,
3421 if let Some(v) = ver {
3422 if containing_ver != ver && v.len() > 0 {
3423 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)?
3429 fn render_stability_since(w: &mut fmt::Formatter<'_>,
3431 containing_item: &clean::Item) -> fmt::Result {
3432 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3435 fn render_assoc_item(w: &mut fmt::Formatter<'_>,
3437 link: AssocItemLink<'_>,
3438 parent: ItemType) -> fmt::Result {
3439 fn method(w: &mut fmt::Formatter<'_>,
3441 header: hir::FnHeader,
3442 g: &clean::Generics,
3444 link: AssocItemLink<'_>,
3447 let name = meth.name.as_ref().unwrap();
3448 let anchor = format!("#{}.{}", meth.type_(), name);
3449 let href = match link {
3450 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3451 AssocItemLink::Anchor(None) => anchor,
3452 AssocItemLink::GotoSource(did, provided_methods) => {
3453 // We're creating a link from an impl-item to the corresponding
3454 // trait-item and need to map the anchored type accordingly.
3455 let ty = if provided_methods.contains(name) {
3461 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3464 let mut header_len = format!(
3465 "{}{}{}{}{}{:#}fn {}{:#}",
3466 VisSpace(&meth.visibility),
3467 ConstnessSpace(header.constness),
3468 UnsafetySpace(header.unsafety),
3469 AsyncSpace(header.asyncness),
3470 DefaultSpace(meth.is_default()),
3471 AbiSpace(header.abi),
3475 let (indent, end_newline) = if parent == ItemType::Trait {
3481 render_attributes(w, meth, false)?;
3482 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3483 {generics}{decl}{where_clause}",
3484 if parent == ItemType::Trait { " " } else { "" },
3485 VisSpace(&meth.visibility),
3486 ConstnessSpace(header.constness),
3487 UnsafetySpace(header.unsafety),
3488 AsyncSpace(header.asyncness),
3489 DefaultSpace(meth.is_default()),
3490 AbiSpace(header.abi),
3498 asyncness: header.asyncness,
3500 where_clause = WhereClause {
3507 clean::StrippedItem(..) => Ok(()),
3508 clean::TyMethodItem(ref m) => {
3509 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3511 clean::MethodItem(ref m) => {
3512 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3514 clean::AssociatedConstItem(ref ty, ref default) => {
3515 assoc_const(w, item, ty, default.as_ref(), link,
3516 if parent == ItemType::Trait { " " } else { "" })
3518 clean::AssociatedTypeItem(ref bounds, ref default) => {
3519 assoc_type(w, item, bounds, default.as_ref(), link,
3520 if parent == ItemType::Trait { " " } else { "" })
3522 _ => panic!("render_assoc_item called on non-associated-item")
3526 fn item_struct(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3527 s: &clean::Struct) -> fmt::Result {
3528 wrap_into_docblock(w, |w| {
3529 write!(w, "<pre class='rust struct'>")?;
3530 render_attributes(w, it, true)?;
3541 document(w, cx, it)?;
3542 let mut fields = s.fields.iter().filter_map(|f| {
3544 clean::StructFieldItem(ref ty) => Some((f, ty)),
3548 if let doctree::Plain = s.struct_type {
3549 if fields.peek().is_some() {
3550 write!(w, "<h2 id='fields' class='fields small-section-header'>
3551 Fields{}<a href='#fields' class='anchor'></a></h2>",
3552 document_non_exhaustive_header(it))?;
3553 document_non_exhaustive(w, it)?;
3554 for (field, ty) in fields {
3555 let id = cx.derive_id(format!("{}.{}",
3556 ItemType::StructField,
3557 field.name.as_ref().unwrap()));
3558 let ns_id = cx.derive_id(format!("{}.{}",
3559 field.name.as_ref().unwrap(),
3560 ItemType::StructField.name_space()));
3561 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3562 <a href=\"#{id}\" class=\"anchor field\"></a>\
3563 <code id=\"{ns_id}\">{name}: {ty}</code>\
3565 item_type = ItemType::StructField,
3568 name = field.name.as_ref().unwrap(),
3570 document(w, cx, field)?;
3574 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3577 fn item_union(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3578 s: &clean::Union) -> fmt::Result {
3579 wrap_into_docblock(w, |w| {
3580 write!(w, "<pre class='rust union'>")?;
3581 render_attributes(w, it, true)?;
3591 document(w, cx, it)?;
3592 let mut fields = s.fields.iter().filter_map(|f| {
3594 clean::StructFieldItem(ref ty) => Some((f, ty)),
3598 if fields.peek().is_some() {
3599 write!(w, "<h2 id='fields' class='fields small-section-header'>
3600 Fields<a href='#fields' class='anchor'></a></h2>")?;
3601 for (field, ty) in fields {
3602 let name = field.name.as_ref().expect("union field name");
3603 let id = format!("{}.{}", ItemType::StructField, name);
3604 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3605 <a href=\"#{id}\" class=\"anchor field\"></a>\
3606 <code>{name}: {ty}</code>\
3610 shortty = ItemType::StructField,
3612 if let Some(stability_class) = field.stability_class() {
3613 write!(w, "<span class='stab {stab}'></span>",
3614 stab = stability_class)?;
3616 document(w, cx, field)?;
3619 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3622 fn item_enum(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3623 e: &clean::Enum) -> fmt::Result {
3624 wrap_into_docblock(w, |w| {
3625 write!(w, "<pre class='rust enum'>")?;
3626 render_attributes(w, it, true)?;
3627 write!(w, "{}enum {}{}{}",
3628 VisSpace(&it.visibility),
3629 it.name.as_ref().unwrap(),
3631 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3632 if e.variants.is_empty() && !e.variants_stripped {
3633 write!(w, " {{}}")?;
3635 write!(w, " {{\n")?;
3636 for v in &e.variants {
3638 let name = v.name.as_ref().unwrap();
3640 clean::VariantItem(ref var) => {
3642 clean::VariantKind::CLike => write!(w, "{}", name)?,
3643 clean::VariantKind::Tuple(ref tys) => {
3644 write!(w, "{}(", name)?;
3645 for (i, ty) in tys.iter().enumerate() {
3647 write!(w, ", ")?
3649 write!(w, "{}", *ty)?;
3653 clean::VariantKind::Struct(ref s) => {
3669 if e.variants_stripped {
3670 write!(w, " // some variants omitted\n")?;
3677 document(w, cx, it)?;
3678 if !e.variants.is_empty() {
3679 write!(w, "<h2 id='variants' class='variants small-section-header'>
3680 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3681 document_non_exhaustive_header(it))?;
3682 document_non_exhaustive(w, it)?;
3683 for variant in &e.variants {
3684 let id = cx.derive_id(format!("{}.{}",
3686 variant.name.as_ref().unwrap()));
3687 let ns_id = cx.derive_id(format!("{}.{}",
3688 variant.name.as_ref().unwrap(),
3689 ItemType::Variant.name_space()));
3690 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3691 <a href=\"#{id}\" class=\"anchor field\"></a>\
3692 <code id='{ns_id}'>{name}",
3695 name = variant.name.as_ref().unwrap())?;
3696 if let clean::VariantItem(ref var) = variant.inner {
3697 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3699 for (i, ty) in tys.iter().enumerate() {
3701 write!(w, ", ")?;
3703 write!(w, "{}", *ty)?;
3708 write!(w, "</code></span>")?;
3709 document(w, cx, variant)?;
3710 document_non_exhaustive(w, variant)?;
3712 use crate::clean::{Variant, VariantKind};
3713 if let clean::VariantItem(Variant {
3714 kind: VariantKind::Struct(ref s)
3715 }) = variant.inner {
3716 let variant_id = cx.derive_id(format!("{}.{}.fields",
3718 variant.name.as_ref().unwrap()));
3719 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3721 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3722 name = variant.name.as_ref().unwrap())?;
3723 for field in &s.fields {
3724 use crate::clean::StructFieldItem;
3725 if let StructFieldItem(ref ty) = field.inner {
3726 let id = cx.derive_id(format!("variant.{}.field.{}",
3727 variant.name.as_ref().unwrap(),
3728 field.name.as_ref().unwrap()));
3729 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3730 variant.name.as_ref().unwrap(),
3731 ItemType::Variant.name_space(),
3732 field.name.as_ref().unwrap(),
3733 ItemType::StructField.name_space()));
3734 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3735 <a href=\"#{id}\" class=\"anchor field\"></a>\
3736 <code id='{ns_id}'>{f}: {t}\
3740 f = field.name.as_ref().unwrap(),
3742 document(w, cx, field)?;
3745 write!(w, "</div></span>")?;
3747 render_stability_since(w, variant, it)?;
3750 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3754 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3755 let path = attr.path.to_string();
3759 } else if let Some(v) = attr.value_str() {
3760 Some(format!("{} = {:?}", path, v.as_str()))
3761 } else if let Some(values) = attr.meta_item_list() {
3762 let display: Vec<_> = values.iter().filter_map(|attr| {
3763 attr.meta_item().and_then(|mi| render_attribute(mi))
3766 if display.len() > 0 {
3767 Some(format!("{}({})", path, display.join(", ")))
3776 const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
3783 sym::unsafe_destructor_blind_to_params,
3787 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3788 // left padding. For example:
3790 // #[foo] <----- "top" attribute
3792 // #[bar] <---- not "top" attribute
3795 fn render_attributes(w: &mut dyn fmt::Write, it: &clean::Item, top: bool) -> fmt::Result {
3796 let mut attrs = String::new();
3798 for attr in &it.attrs.other_attrs {
3799 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
3802 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3803 attrs.push_str(&format!("#[{}]\n", s));
3806 if attrs.len() > 0 {
3807 write!(w, "<div class=\"docblock attributes{}\">{}</div>",
3808 if top { " top-attr" } else { "" }, &attrs)?;
3813 fn render_struct(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3814 g: Option<&clean::Generics>,
3815 ty: doctree::StructType,
3816 fields: &[clean::Item],
3818 structhead: bool) -> fmt::Result {
3820 VisSpace(&it.visibility),
3821 if structhead {"struct "} else {""},
3822 it.name.as_ref().unwrap())?;
3823 if let Some(g) = g {
3828 if let Some(g) = g {
3829 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3831 let mut has_visible_fields = false;
3833 for field in fields {
3834 if let clean::StructFieldItem(ref ty) = field.inner {
3835 write!(w, "\n{} {}{}: {},",
3837 VisSpace(&field.visibility),
3838 field.name.as_ref().unwrap(),
3840 has_visible_fields = true;
3844 if has_visible_fields {
3845 if it.has_stripped_fields().unwrap() {
3846 write!(w, "\n{} // some fields omitted", tab)?;
3848 write!(w, "\n{}", tab)?;
3849 } else if it.has_stripped_fields().unwrap() {
3850 // If there are no visible fields we can just display
3851 // `{ /* fields omitted */ }` to save space.
3852 write!(w, " /* fields omitted */ ")?;
3858 for (i, field) in fields.iter().enumerate() {
3863 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3866 clean::StructFieldItem(ref ty) => {
3867 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3873 if let Some(g) = g {
3874 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3879 // Needed for PhantomData.
3880 if let Some(g) = g {
3881 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3889 fn render_union(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3890 g: Option<&clean::Generics>,
3891 fields: &[clean::Item],
3893 structhead: bool) -> fmt::Result {
3895 VisSpace(&it.visibility),
3896 if structhead {"union "} else {""},
3897 it.name.as_ref().unwrap())?;
3898 if let Some(g) = g {
3899 write!(w, "{}", g)?;
3900 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3903 write!(w, " {{\n{}", tab)?;
3904 for field in fields {
3905 if let clean::StructFieldItem(ref ty) = field.inner {
3906 write!(w, " {}{}: {},\n{}",
3907 VisSpace(&field.visibility),
3908 field.name.as_ref().unwrap(),
3914 if it.has_stripped_fields().unwrap() {
3915 write!(w, " // some fields omitted\n{}", tab)?;
3921 #[derive(Copy, Clone)]
3922 enum AssocItemLink<'a> {
3923 Anchor(Option<&'a str>),
3924 GotoSource(DefId, &'a FxHashSet<String>),
3927 impl<'a> AssocItemLink<'a> {
3928 fn anchor(&self, id: &'a String) -> Self {
3930 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3931 ref other => *other,
3936 enum AssocItemRender<'a> {
3938 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3941 #[derive(Copy, Clone, PartialEq)]
3944 ForDeref { mut_: bool },
3947 fn render_assoc_items(w: &mut fmt::Formatter<'_>,
3949 containing_item: &clean::Item,
3951 what: AssocItemRender<'_>) -> fmt::Result {
3953 let v = match c.impls.get(&it) {
3955 None => return Ok(()),
3957 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3958 i.inner_impl().trait_.is_none()
3960 if !non_trait.is_empty() {
3961 let render_mode = match what {
3962 AssocItemRender::All => {
3964 <h2 id='methods' class='small-section-header'>\
3965 Methods<a href='#methods' class='anchor'></a>\
3970 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3972 <h2 id='deref-methods' class='small-section-header'>\
3973 Methods from {}<Target = {}>\
3974 <a href='#deref-methods' class='anchor'></a>\
3977 RenderMode::ForDeref { mut_: deref_mut_ }
3980 for i in &non_trait {
3981 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3982 containing_item.stable_since(), true, None, false)?;
3985 if let AssocItemRender::DerefFor { .. } = what {
3988 if !traits.is_empty() {
3989 let deref_impl = traits.iter().find(|t| {
3990 t.inner_impl().trait_.def_id() == c.deref_trait_did
3992 if let Some(impl_) = deref_impl {
3993 let has_deref_mut = traits.iter().find(|t| {
3994 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3996 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3999 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
4001 .partition(|t| t.inner_impl().synthetic);
4002 let (blanket_impl, concrete) = concrete
4004 .partition(|t| t.inner_impl().blanket_impl.is_some());
4006 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
4008 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
4009 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4010 render_impls(self.0, fmt, &self.1, self.2)
4014 let impls = RendererStruct(cx, concrete, containing_item).to_string();
4015 if !impls.is_empty() {
4017 <h2 id='implementations' class='small-section-header'>\
4018 Trait Implementations<a href='#implementations' class='anchor'></a>\
4020 <div id='implementations-list'>{}</div>", impls)?;
4023 if !synthetic.is_empty() {
4025 <h2 id='synthetic-implementations' class='small-section-header'>\
4026 Auto Trait Implementations\
4027 <a href='#synthetic-implementations' class='anchor'></a>\
4029 <div id='synthetic-implementations-list'>\
4031 render_impls(cx, w, &synthetic, containing_item)?;
4032 write!(w, "</div>")?;
4035 if !blanket_impl.is_empty() {
4037 <h2 id='blanket-implementations' class='small-section-header'>\
4038 Blanket Implementations\
4039 <a href='#blanket-implementations' class='anchor'></a>\
4041 <div id='blanket-implementations-list'>\
4043 render_impls(cx, w, &blanket_impl, containing_item)?;
4044 write!(w, "</div>")?;
4050 fn render_deref_methods(w: &mut fmt::Formatter<'_>, cx: &Context, impl_: &Impl,
4051 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
4052 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
4053 let target = impl_.inner_impl().items.iter().filter_map(|item| {
4055 clean::TypedefItem(ref t, true) => Some(&t.type_),
4058 }).next().expect("Expected associated type binding");
4059 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
4060 deref_mut_: deref_mut };
4061 if let Some(did) = target.def_id() {
4062 render_assoc_items(w, cx, container_item, did, what)
4064 if let Some(prim) = target.primitive_type() {
4065 if let Some(&did) = cache().primitive_locations.get(&prim) {
4066 render_assoc_items(w, cx, container_item, did, what)?;
4073 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
4074 let self_type_opt = match item.inner {
4075 clean::MethodItem(ref method) => method.decl.self_type(),
4076 clean::TyMethodItem(ref method) => method.decl.self_type(),
4080 if let Some(self_ty) = self_type_opt {
4081 let (by_mut_ref, by_box, by_value) = match self_ty {
4082 SelfTy::SelfBorrowed(_, mutability) |
4083 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4084 (mutability == Mutability::Mutable, false, false)
4086 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4087 (false, Some(did) == cache().owned_box_did, false)
4089 SelfTy::SelfValue => (false, false, true),
4090 _ => (false, false, false),
4093 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4099 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4100 let mut out = String::new();
4103 clean::FunctionItem(clean::Function { ref decl, .. }) |
4104 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4105 clean::MethodItem(clean::Method { ref decl, .. }) |
4106 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4107 out = spotlight_decl(decl)?;
4115 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4116 let mut out = String::new();
4117 let mut trait_ = String::new();
4119 if let Some(did) = decl.output.def_id() {
4121 if let Some(impls) = c.impls.get(&did) {
4123 let impl_ = i.inner_impl();
4124 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4127 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4128 <code class=\"content\">",
4130 trait_.push_str(&impl_.for_.to_string());
4133 //use the "where" class here to make it small
4134 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4135 let t_did = impl_.trait_.def_id().unwrap();
4136 for it in &impl_.items {
4137 if let clean::TypedefItem(ref tydef, _) = it.inner {
4138 out.push_str("<span class=\"where fmt-newline\"> ");
4139 assoc_type(&mut out, it, &[],
4141 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
4143 out.push_str(";</span>");
4151 if !out.is_empty() {
4152 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4153 <span class='tooltiptext'>Important traits for {}</span></div>\
4154 <div class=\"content hidden\">",
4156 out.push_str("</code></div></div>");
4162 fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
4163 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
4164 use_absolute: Option<bool>, is_on_foreign_type: bool) -> fmt::Result {
4165 if render_mode == RenderMode::Normal {
4166 let id = cx.derive_id(match i.inner_impl().trait_ {
4167 Some(ref t) => if is_on_foreign_type {
4168 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
4170 format!("impl-{}", small_url_encode(&format!("{:#}", t)))
4172 None => "impl".to_string(),
4174 if let Some(use_absolute) = use_absolute {
4175 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4176 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4178 for it in &i.inner_impl().items {
4179 if let clean::TypedefItem(ref tydef, _) = it.inner {
4180 write!(w, "<span class=\"where fmt-newline\"> ")?;
4181 assoc_type(w, it, &vec![], Some(&tydef.type_),
4182 AssocItemLink::Anchor(None),
4184 write!(w, ";</span>")?;
4188 write!(w, "</code>")?;
4190 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4194 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4195 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4196 render_stability_since_raw(w, since, outer_version)?;
4197 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4198 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4199 l, "goto source code")?;
4201 write!(w, "</h3>")?;
4202 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4203 let mut ids = cx.id_map.borrow_mut();
4204 write!(w, "<div class='docblock'>{}</div>",
4205 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids),
4206 cx.codes, cx.edition))?;
4210 fn doc_impl_item(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
4211 link: AssocItemLink<'_>, render_mode: RenderMode,
4212 is_default_item: bool, outer_version: Option<&str>,
4213 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4214 let item_type = item.type_();
4215 let name = item.name.as_ref().unwrap();
4217 let render_method_item: bool = match render_mode {
4218 RenderMode::Normal => true,
4219 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4222 let (is_hidden, extra_class) = if trait_.is_none() ||
4223 item.doc_value().is_some() ||
4224 item.inner.is_associated() {
4230 clean::MethodItem(clean::Method { ref decl, .. }) |
4231 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4232 // Only render when the method is not static or we allow static methods
4233 if render_method_item {
4234 let id = cx.derive_id(format!("{}.{}", item_type, name));
4235 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4236 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4237 write!(w, "{}", spotlight_decl(decl)?)?;
4238 write!(w, "<code id='{}'>", ns_id)?;
4239 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4240 write!(w, "</code>")?;
4241 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4242 if let Some(l) = (Item { cx, item }).src_href() {
4243 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4244 l, "goto source code")?;
4246 write!(w, "</h4>")?;
4249 clean::TypedefItem(ref tydef, _) => {
4250 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4251 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4252 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4253 write!(w, "<code id='{}'>", ns_id)?;
4254 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "")?;
4255 write!(w, "</code></h4>")?;
4257 clean::AssociatedConstItem(ref ty, ref default) => {
4258 let id = cx.derive_id(format!("{}.{}", item_type, name));
4259 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4260 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4261 write!(w, "<code id='{}'>", ns_id)?;
4262 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "")?;
4263 write!(w, "</code>")?;
4264 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4265 if let Some(l) = (Item { cx, item }).src_href() {
4266 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4267 l, "goto source code")?;
4269 write!(w, "</h4>")?;
4271 clean::AssociatedTypeItem(ref bounds, ref default) => {
4272 let id = cx.derive_id(format!("{}.{}", item_type, name));
4273 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4274 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4275 write!(w, "<code id='{}'>", ns_id)?;
4276 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "")?;
4277 write!(w, "</code></h4>")?;
4279 clean::StrippedItem(..) => return Ok(()),
4280 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4283 if render_method_item || render_mode == RenderMode::Normal {
4284 if !is_default_item {
4285 if let Some(t) = trait_ {
4286 // The trait item may have been stripped so we might not
4287 // find any documentation or stability for it.
4288 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4289 // We need the stability of the item from the trait
4290 // because impls can't have a stability.
4291 document_stability(w, cx, it, is_hidden)?;
4292 if item.doc_value().is_some() {
4293 document_full(w, item, cx, "", is_hidden)?;
4294 } else if show_def_docs {
4295 // In case the item isn't documented,
4296 // provide short documentation from the trait.
4297 document_short(w, cx, it, link, "", is_hidden)?;
4301 document_stability(w, cx, item, is_hidden)?;
4303 document_full(w, item, cx, "", is_hidden)?;
4307 document_stability(w, cx, item, is_hidden)?;
4309 document_short(w, cx, item, link, "", is_hidden)?;
4316 let traits = &cache().traits;
4317 let trait_ = i.trait_did().map(|did| &traits[&did]);
4319 write!(w, "<div class='impl-items'>")?;
4320 for trait_item in &i.inner_impl().items {
4321 doc_impl_item(w, cx, trait_item, link, render_mode,
4322 false, outer_version, trait_, show_def_docs)?;
4325 fn render_default_items(w: &mut fmt::Formatter<'_>,
4329 render_mode: RenderMode,
4330 outer_version: Option<&str>,
4331 show_def_docs: bool) -> fmt::Result {
4332 for trait_item in &t.items {
4333 let n = trait_item.name.clone();
4334 if i.items.iter().find(|m| m.name == n).is_some() {
4337 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4338 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4340 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4341 outer_version, None, show_def_docs)?;
4346 // If we've implemented a trait, then also emit documentation for all
4347 // default items which weren't overridden in the implementation block.
4348 if let Some(t) = trait_ {
4349 render_default_items(w, cx, t, &i.inner_impl(),
4350 render_mode, outer_version, show_def_docs)?;
4352 write!(w, "</div>")?;
4357 fn item_existential(
4358 w: &mut fmt::Formatter<'_>,
4361 t: &clean::Existential,
4363 write!(w, "<pre class='rust existential'>")?;
4364 render_attributes(w, it, false)?;
4365 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4366 it.name.as_ref().unwrap(),
4368 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4369 bounds = bounds(&t.bounds, false))?;
4371 document(w, cx, it)?;
4373 // Render any items associated directly to this alias, as otherwise they
4374 // won't be visible anywhere in the docs. It would be nice to also show
4375 // associated items from the aliased type (see discussion in #32077), but
4376 // we need #14072 to make sense of the generics.
4377 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4380 fn item_trait_alias(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4381 t: &clean::TraitAlias) -> fmt::Result {
4382 write!(w, "<pre class='rust trait-alias'>")?;
4383 render_attributes(w, it, false)?;
4384 write!(w, "trait {}{}{} = {};</pre>",
4385 it.name.as_ref().unwrap(),
4387 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4388 bounds(&t.bounds, true))?;
4390 document(w, cx, it)?;
4392 // Render any items associated directly to this alias, as otherwise they
4393 // won't be visible anywhere in the docs. It would be nice to also show
4394 // associated items from the aliased type (see discussion in #32077), but
4395 // we need #14072 to make sense of the generics.
4396 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4399 fn item_typedef(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4400 t: &clean::Typedef) -> fmt::Result {
4401 write!(w, "<pre class='rust typedef'>")?;
4402 render_attributes(w, it, false)?;
4403 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4404 it.name.as_ref().unwrap(),
4406 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4409 document(w, cx, it)?;
4411 // Render any items associated directly to this alias, as otherwise they
4412 // won't be visible anywhere in the docs. It would be nice to also show
4413 // associated items from the aliased type (see discussion in #32077), but
4414 // we need #14072 to make sense of the generics.
4415 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4418 fn item_foreign_type(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item) -> fmt::Result {
4419 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4420 render_attributes(w, it, false)?;
4423 " {}type {};\n}}</pre>",
4424 VisSpace(&it.visibility),
4425 it.name.as_ref().unwrap(),
4428 document(w, cx, it)?;
4430 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4433 impl<'a> fmt::Display for Sidebar<'a> {
4434 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4437 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4439 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4440 || it.is_enum() || it.is_mod() || it.is_typedef() {
4441 write!(fmt, "<p class='location'>{}{}</p>",
4443 clean::StructItem(..) => "Struct ",
4444 clean::TraitItem(..) => "Trait ",
4445 clean::PrimitiveItem(..) => "Primitive Type ",
4446 clean::UnionItem(..) => "Union ",
4447 clean::EnumItem(..) => "Enum ",
4448 clean::TypedefItem(..) => "Type Definition ",
4449 clean::ForeignTypeItem => "Foreign Type ",
4450 clean::ModuleItem(..) => if it.is_crate() {
4457 it.name.as_ref().unwrap())?;
4461 if let Some(ref version) = cache().crate_version {
4463 "<div class='block version'>\
4470 write!(fmt, "<div class=\"sidebar-elems\">")?;
4472 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4473 it.name.as_ref().expect("crates always have a name"))?;
4476 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4477 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4478 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4479 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4480 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4481 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4482 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4483 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4487 // The sidebar is designed to display sibling functions, modules and
4488 // other miscellaneous information. since there are lots of sibling
4489 // items (and that causes quadratic growth in large modules),
4490 // we refactor common parts into a shared JavaScript file per module.
4491 // still, we don't move everything into JS because we want to preserve
4492 // as much HTML as possible in order to allow non-JS-enabled browsers
4493 // to navigate the documentation (though slightly inefficiently).
4495 write!(fmt, "<p class='location'>")?;
4496 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4498 write!(fmt, "::<wbr>")?;
4500 write!(fmt, "<a href='{}index.html'>{}</a>",
4501 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4504 write!(fmt, "</p>")?;
4506 // Sidebar refers to the enclosing module, not this module.
4507 let relpath = if it.is_mod() { "../" } else { "" };
4509 "<script>window.sidebarCurrent = {{\
4514 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4515 ty = it.type_().css_class(),
4518 // There is no sidebar-items.js beyond the crate root path
4519 // FIXME maybe dynamic crate loading can be merged here
4521 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4524 // Closes sidebar-elems div.
4525 write!(fmt, "</div>")?;
4531 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4532 if used_links.insert(url.clone()) {
4536 while used_links.insert(format!("{}-{}", url, add)) == false {
4539 format!("{}-{}", url, add)
4545 used_links: &mut FxHashSet<String>,
4547 i.items.iter().filter_map(|item| {
4549 // Maybe check with clean::Visibility::Public as well?
4550 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4551 if !for_deref || should_render_item(item, false) {
4552 Some(format!("<a href=\"#{}\">{}</a>",
4553 get_next_url(used_links, format!("method.{}", name)),
4561 }).collect::<Vec<_>>()
4564 // The point is to url encode any potential character from a type with genericity.
4565 fn small_url_encode(s: &str) -> String {
4566 s.replace("<", "%3C")
4567 .replace(">", "%3E")
4568 .replace(" ", "%20")
4569 .replace("?", "%3F")
4570 .replace("'", "%27")
4571 .replace("&", "%26")
4572 .replace(",", "%2C")
4573 .replace(":", "%3A")
4574 .replace(";", "%3B")
4575 .replace("[", "%5B")
4576 .replace("]", "%5D")
4577 .replace("\"", "%22")
4580 fn sidebar_assoc_items(it: &clean::Item) -> String {
4581 let mut out = String::new();
4583 if let Some(v) = c.impls.get(&it.def_id) {
4584 let mut used_links = FxHashSet::default();
4587 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4588 let mut ret = v.iter()
4589 .filter(|i| i.inner_impl().trait_.is_none())
4590 .flat_map(move |i| get_methods(i.inner_impl(),
4592 &mut used_links_bor.borrow_mut()))
4593 .collect::<Vec<_>>();
4594 // We want links' order to be reproducible so we don't use unstable sort.
4596 if !ret.is_empty() {
4597 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4598 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4602 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4603 if let Some(impl_) = v.iter()
4604 .filter(|i| i.inner_impl().trait_.is_some())
4605 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4606 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4608 clean::TypedefItem(ref t, true) => Some(&t.type_),
4612 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4613 c.primitive_locations.get(&prim).cloned()
4614 })).and_then(|did| c.impls.get(&did));
4615 if let Some(impls) = inner_impl {
4616 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4617 out.push_str(&format!("Methods from {}<Target={}>",
4618 Escape(&format!("{:#}",
4619 impl_.inner_impl().trait_.as_ref().unwrap())),
4620 Escape(&format!("{:#}", target))));
4621 out.push_str("</a>");
4622 let mut ret = impls.iter()
4623 .filter(|i| i.inner_impl().trait_.is_none())
4624 .flat_map(|i| get_methods(i.inner_impl(),
4627 .collect::<Vec<_>>();
4628 // We want links' order to be reproducible so we don't use unstable sort.
4630 if !ret.is_empty() {
4631 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4637 let format_impls = |impls: Vec<&Impl>| {
4638 let mut links = FxHashSet::default();
4640 let mut ret = impls.iter()
4642 let is_negative_impl = is_negative_impl(i.inner_impl());
4643 if let Some(ref i) = i.inner_impl().trait_ {
4644 let i_display = format!("{:#}", i);
4645 let out = Escape(&i_display);
4646 let encoded = small_url_encode(&format!("{:#}", i));
4647 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4649 if is_negative_impl { "!" } else { "" },
4651 if links.insert(generated.clone()) {
4660 .collect::<Vec<String>>();
4665 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4667 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4668 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4670 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4672 let concrete_format = format_impls(concrete);
4673 let synthetic_format = format_impls(synthetic);
4674 let blanket_format = format_impls(blanket_impl);
4676 if !concrete_format.is_empty() {
4677 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4678 Trait Implementations</a>");
4679 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4682 if !synthetic_format.is_empty() {
4683 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4684 Auto Trait Implementations</a>");
4685 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4688 if !blanket_format.is_empty() {
4689 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4690 Blanket Implementations</a>");
4691 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4699 fn sidebar_struct(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4700 s: &clean::Struct) -> fmt::Result {
4701 let mut sidebar = String::new();
4702 let fields = get_struct_fields_name(&s.fields);
4704 if !fields.is_empty() {
4705 if let doctree::Plain = s.struct_type {
4706 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4707 <div class=\"sidebar-links\">{}</div>", fields));
4711 sidebar.push_str(&sidebar_assoc_items(it));
4713 if !sidebar.is_empty() {
4714 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4719 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4720 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_, for_))
4723 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4725 clean::ItemEnum::ImplItem(ref i) => {
4726 if let Some(ref trait_) = i.trait_ {
4727 Some((format!("{:#}", i.for_), get_id_for_impl_on_foreign_type(&i.for_, trait_)))
4736 fn is_negative_impl(i: &clean::Impl) -> bool {
4737 i.polarity == Some(clean::ImplPolarity::Negative)
4740 fn sidebar_trait(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4741 t: &clean::Trait) -> fmt::Result {
4742 let mut sidebar = String::new();
4748 Some(ref name) if m.is_associated_type() => {
4749 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4755 .collect::<String>();
4756 let consts = t.items
4760 Some(ref name) if m.is_associated_const() => {
4761 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4767 .collect::<String>();
4768 let mut required = t.items
4772 Some(ref name) if m.is_ty_method() => {
4773 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4779 .collect::<Vec<String>>();
4780 let mut provided = t.items
4784 Some(ref name) if m.is_method() => {
4785 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4790 .collect::<Vec<String>>();
4792 if !types.is_empty() {
4793 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4794 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4797 if !consts.is_empty() {
4798 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4799 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4802 if !required.is_empty() {
4804 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4805 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4806 required.join("")));
4808 if !provided.is_empty() {
4810 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4811 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4812 provided.join("")));
4817 if let Some(implementors) = c.implementors.get(&it.def_id) {
4818 let mut res = implementors.iter()
4819 .filter(|i| i.inner_impl().for_.def_id()
4820 .map_or(false, |d| !c.paths.contains_key(&d)))
4822 match extract_for_impl_name(&i.impl_item) {
4823 Some((ref name, ref id)) => {
4824 Some(format!("<a href=\"#{}\">{}</a>",
4831 .collect::<Vec<String>>();
4832 if !res.is_empty() {
4834 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4835 Implementations on Foreign Types</a><div \
4836 class=\"sidebar-links\">{}</div>",
4841 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4843 sidebar.push_str("<a class=\"sidebar-title\" \
4844 href=\"#synthetic-implementors\">Auto Implementors</a>");
4847 sidebar.push_str(&sidebar_assoc_items(it));
4849 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4852 fn sidebar_primitive(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4853 _p: &clean::PrimitiveType) -> fmt::Result {
4854 let sidebar = sidebar_assoc_items(it);
4856 if !sidebar.is_empty() {
4857 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4862 fn sidebar_typedef(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4863 _t: &clean::Typedef) -> fmt::Result {
4864 let sidebar = sidebar_assoc_items(it);
4866 if !sidebar.is_empty() {
4867 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4872 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4874 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4879 .filter_map(|f| match f.name {
4880 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4881 {name}</a>", name=name)),
4887 fn sidebar_union(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4888 u: &clean::Union) -> fmt::Result {
4889 let mut sidebar = String::new();
4890 let fields = get_struct_fields_name(&u.fields);
4892 if !fields.is_empty() {
4893 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4894 <div class=\"sidebar-links\">{}</div>", fields));
4897 sidebar.push_str(&sidebar_assoc_items(it));
4899 if !sidebar.is_empty() {
4900 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4905 fn sidebar_enum(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4906 e: &clean::Enum) -> fmt::Result {
4907 let mut sidebar = String::new();
4909 let variants = e.variants.iter()
4910 .filter_map(|v| match v.name {
4911 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4912 </a>", name = name)),
4915 .collect::<String>();
4916 if !variants.is_empty() {
4917 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4918 <div class=\"sidebar-links\">{}</div>", variants));
4921 sidebar.push_str(&sidebar_assoc_items(it));
4923 if !sidebar.is_empty() {
4924 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4929 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4931 ItemType::ExternCrate |
4932 ItemType::Import => ("reexports", "Re-exports"),
4933 ItemType::Module => ("modules", "Modules"),
4934 ItemType::Struct => ("structs", "Structs"),
4935 ItemType::Union => ("unions", "Unions"),
4936 ItemType::Enum => ("enums", "Enums"),
4937 ItemType::Function => ("functions", "Functions"),
4938 ItemType::Typedef => ("types", "Type Definitions"),
4939 ItemType::Static => ("statics", "Statics"),
4940 ItemType::Constant => ("constants", "Constants"),
4941 ItemType::Trait => ("traits", "Traits"),
4942 ItemType::Impl => ("impls", "Implementations"),
4943 ItemType::TyMethod => ("tymethods", "Type Methods"),
4944 ItemType::Method => ("methods", "Methods"),
4945 ItemType::StructField => ("fields", "Struct Fields"),
4946 ItemType::Variant => ("variants", "Variants"),
4947 ItemType::Macro => ("macros", "Macros"),
4948 ItemType::Primitive => ("primitives", "Primitive Types"),
4949 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4950 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4951 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4952 ItemType::Keyword => ("keywords", "Keywords"),
4953 ItemType::Existential => ("existentials", "Existentials"),
4954 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4955 ItemType::ProcDerive => ("derives", "Derive Macros"),
4956 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4960 fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item,
4961 items: &[clean::Item]) -> fmt::Result {
4962 let mut sidebar = String::new();
4964 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4965 it.type_() == ItemType::Import) {
4966 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4968 name = "Re-exports"));
4971 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4972 // to print its headings
4973 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4974 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4975 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4976 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4977 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4978 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4979 let (short, name) = item_ty_to_strs(&myty);
4980 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4986 if !sidebar.is_empty() {
4987 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4992 fn sidebar_foreign_type(fmt: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
4993 let sidebar = sidebar_assoc_items(it);
4994 if !sidebar.is_empty() {
4995 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
5000 impl<'a> fmt::Display for Source<'a> {
5001 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5002 let Source(s) = *self;
5003 let lines = s.lines().count();
5005 let mut tmp = lines;
5010 write!(fmt, "<pre class=\"line-numbers\">")?;
5011 for i in 1..=lines {
5012 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
5014 write!(fmt, "</pre>")?;
5016 highlight::render_with_highlighting(s, None, None, None))?;
5021 fn item_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
5022 t: &clean::Macro) -> fmt::Result {
5023 wrap_into_docblock(w, |w| {
5024 w.write_str(&highlight::render_with_highlighting(&t.source,
5032 fn item_proc_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
5035 let name = it.name.as_ref().expect("proc-macros always have names");
5037 MacroKind::Bang => {
5038 write!(w, "<pre class='rust macro'>")?;
5039 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
5040 write!(w, "</pre>")?;
5042 MacroKind::Attr => {
5043 write!(w, "<pre class='rust attr'>")?;
5044 write!(w, "#[{}]", name)?;
5045 write!(w, "</pre>")?;
5047 MacroKind::Derive => {
5048 write!(w, "<pre class='rust derive'>")?;
5049 write!(w, "#[derive({})]", name)?;
5050 if !m.helpers.is_empty() {
5051 writeln!(w, "\n{{")?;
5052 writeln!(w, " // Attributes available to this derive:")?;
5053 for attr in &m.helpers {
5054 writeln!(w, " #[{}]", attr)?;
5058 write!(w, "</pre>")?;
5065 fn item_primitive(w: &mut fmt::Formatter<'_>, cx: &Context,
5067 _p: &clean::PrimitiveType) -> fmt::Result {
5068 document(w, cx, it)?;
5069 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
5072 fn item_keyword(w: &mut fmt::Formatter<'_>, cx: &Context,
5074 _p: &str) -> fmt::Result {
5078 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
5080 fn make_item_keywords(it: &clean::Item) -> String {
5081 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
5084 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
5085 let (all_types, ret_types) = match item.inner {
5086 clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
5087 clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
5088 clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
5092 let inputs = all_types.iter().map(|arg| {
5093 get_index_type(&arg)
5094 }).filter(|a| a.name.is_some()).collect();
5095 let output = ret_types.iter().map(|arg| {
5096 get_index_type(&arg)
5097 }).filter(|a| a.name.is_some()).collect::<Vec<_>>();
5098 let output = if output.is_empty() {
5104 Some(IndexItemFunctionType { inputs, output })
5107 fn get_index_type(clean_type: &clean::Type) -> Type {
5109 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5110 generics: get_generics(clean_type),
5115 /// Returns a list of all paths used in the type.
5116 /// This is used to help deduplicate imported impls
5117 /// for reexported types. If any of the contained
5118 /// types are re-exported, we don't use the corresponding
5119 /// entry from the js file, as inlining will have already
5120 /// picked up the impl
5121 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5122 let mut out = Vec::new();
5123 let mut visited = FxHashSet::default();
5124 let mut work = VecDeque::new();
5125 let cache = cache();
5127 work.push_back(first_ty);
5129 while let Some(ty) = work.pop_front() {
5130 if !visited.insert(ty.clone()) {
5135 clean::Type::ResolvedPath { did, .. } => {
5136 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5137 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5141 out.push(path.join("::"));
5147 clean::Type::Tuple(tys) => {
5148 work.extend(tys.into_iter());
5150 clean::Type::Slice(ty) => {
5151 work.push_back(*ty);
5153 clean::Type::Array(ty, _) => {
5154 work.push_back(*ty);
5156 clean::Type::Unique(ty) => {
5157 work.push_back(*ty);
5159 clean::Type::RawPointer(_, ty) => {
5160 work.push_back(*ty);
5162 clean::Type::BorrowedRef { type_, .. } => {
5163 work.push_back(*type_);
5165 clean::Type::QPath { self_type, trait_, .. } => {
5166 work.push_back(*self_type);
5167 work.push_back(*trait_);
5175 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5177 clean::ResolvedPath { ref path, .. } => {
5178 let segments = &path.segments;
5179 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5180 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5181 clean_type, accept_generic
5183 Some(path_segment.name.clone())
5185 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5186 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5187 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5188 // FIXME: add all from clean::Type.
5193 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5194 clean_type.generics()
5196 let r = types.iter()
5197 .filter_map(|t| get_index_type_name(t, false))
5198 .map(|s| s.to_ascii_lowercase())
5199 .collect::<Vec<_>>();
5208 pub fn cache() -> Arc<Cache> {
5209 CACHE_KEY.with(|c| c.borrow().clone())
5214 fn test_name_key() {
5215 assert_eq!(name_key("0"), ("", 0, 1));
5216 assert_eq!(name_key("123"), ("", 123, 0));
5217 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5218 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5219 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5220 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5221 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5222 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5227 fn test_name_sorting() {
5228 let names = ["Apple",
5230 "Fruit", "Fruit0", "Fruit00",
5231 "Fruit1", "Fruit01",
5232 "Fruit2", "Fruit02",
5237 let mut sorted = names.to_owned();
5238 sorted.sort_by_key(|&s| name_key(s));
5239 assert_eq!(names, sorted);