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::ext::base::MacroKind;
51 use syntax::source_map::FileName;
52 use syntax::feature_gate::UnstableFeatures;
53 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
54 use rustc::middle::privacy::AccessLevels;
55 use rustc::middle::stability;
57 use rustc::util::nodemap::{FxHashMap, FxHashSet};
58 use rustc_data_structures::flock;
60 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
61 use crate::config::RenderOptions;
63 use crate::fold::DocFolder;
64 use crate::html::escape::Escape;
65 use crate::html::format::{AsyncSpace, ConstnessSpace};
66 use crate::html::format::{GenericBounds, WhereClause, href, AbiSpace, DefaultSpace};
67 use crate::html::format::{VisSpace, Function, UnsafetySpace, MutableSpace};
68 use crate::html::format::fmt_impl_for_trait_page;
69 use crate::html::item_type::ItemType;
70 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
71 use crate::html::{highlight, layout, static_files};
75 /// A pair of name and its optional document.
76 pub type NameDoc = (String, Option<String>);
78 pub struct SlashChecker<'a>(pub &'a str);
80 impl<'a> Display for SlashChecker<'a> {
81 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
82 if !self.0.ends_with("/") && !self.0.is_empty() {
83 write!(f, "{}/", self.0)
85 write!(f, "{}", self.0)
90 /// Major driving force in all rustdoc rendering. This contains information
91 /// about where in the tree-like hierarchy rendering is occurring and controls
92 /// how the current page is being rendered.
94 /// It is intended that this context is a lightweight object which can be fairly
95 /// easily cloned because it is cloned per work-job (about once per item in the
99 /// Current hierarchy of components leading down to what's currently being
101 pub current: Vec<String>,
102 /// The current destination folder of where HTML artifacts should be placed.
103 /// This changes as the context descends into the module hierarchy.
105 /// A flag, which when `true`, will render pages which redirect to the
106 /// real location of an item. This is used to allow external links to
107 /// publicly reused items to redirect to the right location.
108 pub render_redirect_pages: bool,
109 pub codes: ErrorCodes,
110 /// The map used to ensure all generated 'id=' attributes are unique.
111 id_map: Rc<RefCell<IdMap>>,
112 pub shared: Arc<SharedContext>,
115 struct SharedContext {
116 /// The path to the crate root source minus the file name.
117 /// Used for simplifying paths to the highlighted source code files.
118 pub src_root: PathBuf,
119 /// This describes the layout of each page, and is not modified after
120 /// creation of the context (contains info like the favicon and added html).
121 pub layout: layout::Layout,
122 /// This flag indicates whether `[src]` links should be generated or not. If
123 /// the source files are present in the html rendering, then this will be
125 pub include_sources: bool,
126 /// The local file sources we've emitted and their respective url-paths.
127 pub local_sources: FxHashMap<PathBuf, String>,
128 /// All the passes that were run on this crate.
129 pub passes: FxHashSet<String>,
130 /// The base-URL of the issue tracker for when an item has been tagged with
132 pub issue_tracker_base_url: Option<String>,
133 /// The given user css file which allow to customize the generated
134 /// documentation theme.
135 pub css_file_extension: Option<PathBuf>,
136 /// The directories that have already been created in this doc run. Used to reduce the number
137 /// of spurious `create_dir_all` calls.
138 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
139 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
140 /// should be ordered alphabetically or in order of appearance (in the source code).
141 pub sort_modules_alphabetically: bool,
142 /// Additional themes to be added to the generated docs.
143 pub themes: Vec<PathBuf>,
144 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
146 pub resource_suffix: String,
147 /// Optional path string to be used to load static files on output pages. If not set, uses
148 /// combinations of `../` to reach the documentation root.
149 pub static_root_path: Option<String>,
150 /// If false, the `select` element to have search filtering by crates on rendered docs
151 /// won't be generated.
152 pub generate_search_filter: bool,
153 /// Option disabled by default to generate files used by RLS and some other tools.
154 pub generate_redirect_pages: bool,
158 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
159 let mut dirs = self.created_dirs.borrow_mut();
160 if !dirs.contains(dst) {
161 fs::create_dir_all(dst)?;
162 dirs.insert(dst.to_path_buf());
170 /// Returns `true` if the `collapse-docs` pass was run on this crate.
171 pub fn was_collapsed(&self) -> bool {
172 self.passes.contains("collapse-docs")
175 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
176 /// `collapsed_doc_value` of the given item.
177 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
178 if self.was_collapsed() {
179 item.collapsed_doc_value().map(|s| s.into())
181 item.doc_value().map(|s| s.into())
186 /// Indicates where an external crate can be found.
187 pub enum ExternalLocation {
188 /// Remote URL root of the external crate
190 /// This external crate can be found in the local doc/ folder
192 /// The external crate could not be found.
196 /// Metadata about implementations for a type or trait.
197 #[derive(Clone, Debug)]
199 pub impl_item: clean::Item,
203 fn inner_impl(&self) -> &clean::Impl {
204 match self.impl_item.inner {
205 clean::ImplItem(ref impl_) => impl_,
206 _ => panic!("non-impl item found in impl")
210 fn trait_did(&self) -> Option<DefId> {
211 self.inner_impl().trait_.def_id()
218 pub error: io::Error,
221 impl error::Error for Error {
222 fn description(&self) -> &str {
223 self.error.description()
227 impl Display for Error {
228 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
229 write!(f, "\"{}\": {}", self.file.display(), self.error)
234 pub fn new(e: io::Error, file: &Path) -> Error {
236 file: file.to_path_buf(),
242 macro_rules! try_none {
243 ($e:expr, $file:expr) => ({
247 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
253 macro_rules! try_err {
254 ($e:expr, $file:expr) => ({
257 Err(e) => return Err(Error::new(e, $file)),
262 /// This cache is used to store information about the `clean::Crate` being
263 /// rendered in order to provide more useful documentation. This contains
264 /// information like all implementors of a trait, all traits a type implements,
265 /// documentation for all known traits, etc.
267 /// This structure purposefully does not implement `Clone` because it's intended
268 /// to be a fairly large and expensive structure to clone. Instead this adheres
269 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
270 /// rendering threads.
273 /// Mapping of typaram ids to the name of the type parameter. This is used
274 /// when pretty-printing a type (so pretty-printing doesn't have to
275 /// painfully maintain a context like this)
276 pub param_names: FxHashMap<DefId, String>,
278 /// Maps a type ID to all known implementations for that type. This is only
279 /// recognized for intra-crate `ResolvedPath` types, and is used to print
280 /// out extra documentation on the page of an enum/struct.
282 /// The values of the map are a list of implementations and documentation
283 /// found on that implementation.
284 pub impls: FxHashMap<DefId, Vec<Impl>>,
286 /// Maintains a mapping of local crate `NodeId`s to the fully qualified name
287 /// and "short type description" of that node. This is used when generating
288 /// URLs when a type is being linked to. External paths are not located in
289 /// this map because the `External` type itself has all the information
291 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
293 /// Similar to `paths`, but only holds external paths. This is only used for
294 /// generating explicit hyperlinks to other crates.
295 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
297 /// Maps local `DefId`s of exported types to fully qualified paths.
298 /// Unlike 'paths', this mapping ignores any renames that occur
299 /// due to 'use' statements.
301 /// This map is used when writing out the special 'implementors'
302 /// javascript file. By using the exact path that the type
303 /// is declared with, we ensure that each path will be identical
304 /// to the path used if the corresponding type is inlined. By
305 /// doing this, we can detect duplicate impls on a trait page, and only display
306 /// the impl for the inlined type.
307 pub exact_paths: FxHashMap<DefId, Vec<String>>,
309 /// This map contains information about all known traits of this crate.
310 /// Implementations of a crate should inherit the documentation of the
311 /// parent trait if no extra documentation is specified, and default methods
312 /// should show up in documentation about trait implementations.
313 pub traits: FxHashMap<DefId, clean::Trait>,
315 /// When rendering traits, it's often useful to be able to list all
316 /// implementors of the trait, and this mapping is exactly, that: a mapping
317 /// of trait ids to the list of known implementors of the trait
318 pub implementors: FxHashMap<DefId, Vec<Impl>>,
320 /// Cache of where external crate documentation can be found.
321 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
323 /// Cache of where documentation for primitives can be found.
324 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
326 // Note that external items for which `doc(hidden)` applies to are shown as
327 // non-reachable while local items aren't. This is because we're reusing
328 // the access levels from the privacy check pass.
329 pub access_levels: AccessLevels<DefId>,
331 /// The version of the crate being documented, if given from the `--crate-version` flag.
332 pub crate_version: Option<String>,
334 // Private fields only used when initially crawling a crate to build a cache
337 parent_stack: Vec<DefId>,
338 parent_is_trait_impl: bool,
339 search_index: Vec<IndexItem>,
341 deref_trait_did: Option<DefId>,
342 deref_mut_trait_did: Option<DefId>,
343 owned_box_did: Option<DefId>,
344 masked_crates: FxHashSet<CrateNum>,
346 // In rare case where a structure is defined in one module but implemented
347 // in another, if the implementing module is parsed before defining module,
348 // then the fully qualified name of the structure isn't presented in `paths`
349 // yet when its implementation methods are being indexed. Caches such methods
350 // and their parent id here and indexes them at the end of crate parsing.
351 orphan_impl_items: Vec<(DefId, clean::Item)>,
353 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
354 // even though the trait itself is not exported. This can happen if a trait
355 // was defined in function/expression scope, since the impl will be picked
356 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
357 // crawl. In order to prevent crashes when looking for spotlight traits or
358 // when gathering trait documentation on a type, hold impls here while
359 // folding and add them to the cache later on if we find the trait.
360 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
362 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
363 /// we need the alias element to have an array of items.
364 aliases: FxHashMap<String, Vec<IndexItem>>,
367 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
368 /// Later on moved into `CACHE_KEY`.
370 pub struct RenderInfo {
371 pub inlined: FxHashSet<DefId>,
372 pub external_paths: crate::core::ExternalPaths,
373 pub external_param_names: FxHashMap<DefId, String>,
374 pub exact_paths: FxHashMap<DefId, Vec<String>>,
375 pub access_levels: AccessLevels<DefId>,
376 pub deref_trait_did: Option<DefId>,
377 pub deref_mut_trait_did: Option<DefId>,
378 pub owned_box_did: Option<DefId>,
381 /// Helper struct to render all source code to HTML pages
382 struct SourceCollector<'a> {
383 scx: &'a mut SharedContext,
385 /// Root destination to place all HTML output into
389 /// Wrapper struct to render the source code of a file. This will do things like
390 /// adding line numbers to the left-hand side.
391 struct Source<'a>(&'a str);
393 // Helper structs for rendering items/sidebars and carrying along contextual
396 #[derive(Copy, Clone)]
399 item: &'a clean::Item,
402 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
404 /// Struct representing one entry in the JS search index. These are all emitted
405 /// by hand to a large JS file at the end of cache-creation.
412 parent: Option<DefId>,
413 parent_idx: Option<usize>,
414 search_type: Option<IndexItemFunctionType>,
417 impl ToJson for IndexItem {
418 fn to_json(&self) -> Json {
419 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
421 let mut data = Vec::with_capacity(6);
422 data.push((self.ty as usize).to_json());
423 data.push(self.name.to_json());
424 data.push(self.path.to_json());
425 data.push(self.desc.to_json());
426 data.push(self.parent_idx.to_json());
427 data.push(self.search_type.to_json());
433 /// A type used for the search index.
436 name: Option<String>,
437 generics: Option<Vec<String>>,
440 impl ToJson for Type {
441 fn to_json(&self) -> Json {
444 let mut data = Vec::with_capacity(2);
445 data.push(name.to_json());
446 if let Some(ref generics) = self.generics {
447 data.push(generics.to_json());
456 /// Full type of functions/methods in the search index.
458 struct IndexItemFunctionType {
460 output: Option<Vec<Type>>,
463 impl ToJson for IndexItemFunctionType {
464 fn to_json(&self) -> Json {
465 // If we couldn't figure out a type, just write `null`.
466 let mut iter = self.inputs.iter();
467 if match self.output {
468 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
469 None => iter.any(|ref i| i.name.is_none()),
473 let mut data = Vec::with_capacity(2);
474 data.push(self.inputs.to_json());
475 if let Some(ref output) = self.output {
476 if output.len() > 1 {
477 data.push(output.to_json());
479 data.push(output[0].to_json());
487 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
488 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
490 pub fn initial_ids() -> Vec<String> {
502 "synthetic-implementors",
504 "synthetic-implementors-list",
508 ].into_iter().map(|id| (String::from(*id))).collect()
511 /// Generates the documentation for `crate` into the directory `dst`
512 pub fn run(mut krate: clean::Crate,
513 options: RenderOptions,
514 passes: FxHashSet<String>,
515 renderinfo: RenderInfo,
516 diag: &errors::Handler) -> Result<(), Error> {
517 // need to save a copy of the options for rendering the index page
518 let md_opts = options.clone();
524 sort_modules_alphabetically,
527 extern_html_root_urls,
530 generate_search_filter,
531 generate_redirect_pages,
535 let src_root = match krate.src {
536 FileName::Real(ref p) => match p.parent() {
537 Some(p) => p.to_path_buf(),
538 None => PathBuf::new(),
542 let mut scx = SharedContext {
545 include_sources: true,
546 local_sources: Default::default(),
547 issue_tracker_base_url: None,
548 layout: layout::Layout {
550 favicon: String::new(),
552 krate: krate.name.clone(),
554 css_file_extension: extension_css,
555 created_dirs: Default::default(),
556 sort_modules_alphabetically,
560 generate_search_filter,
561 generate_redirect_pages,
564 // If user passed in `--playground-url` arg, we fill in crate name here
565 if let Some(url) = playground_url {
566 markdown::PLAYGROUND.with(|slot| {
567 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
571 // Crawl the crate attributes looking for attributes which control how we're
572 // going to emit HTML
573 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
574 for attr in attrs.lists("doc") {
575 match (attr.name_or_empty().get(), attr.value_str()) {
576 ("html_favicon_url", Some(s)) => {
577 scx.layout.favicon = s.to_string();
579 ("html_logo_url", Some(s)) => {
580 scx.layout.logo = s.to_string();
582 ("html_playground_url", Some(s)) => {
583 markdown::PLAYGROUND.with(|slot| {
584 let name = krate.name.clone();
585 *slot.borrow_mut() = Some((Some(name), s.to_string()));
588 ("issue_tracker_base_url", Some(s)) => {
589 scx.issue_tracker_base_url = Some(s.to_string());
591 ("html_no_source", None) if attr.is_word() => {
592 scx.include_sources = false;
599 try_err!(fs::create_dir_all(&dst), &dst);
600 krate = render_sources(&dst, &mut scx, krate)?;
604 render_redirect_pages: false,
605 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
606 id_map: Rc::new(RefCell::new(id_map)),
607 shared: Arc::new(scx),
610 // Crawl the crate to build various caches used for the output
614 external_param_names,
622 let external_paths = external_paths.into_iter()
623 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
626 let mut cache = Cache {
627 impls: Default::default(),
630 paths: Default::default(),
631 implementors: Default::default(),
633 parent_stack: Vec::new(),
634 search_index: Vec::new(),
635 parent_is_trait_impl: false,
636 extern_locations: Default::default(),
637 primitive_locations: Default::default(),
640 crate_version: krate.version.take(),
641 orphan_impl_items: Vec::new(),
642 orphan_trait_impls: Vec::new(),
643 traits: krate.external_traits.lock().replace(Default::default()),
647 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
648 param_names: external_param_names,
649 aliases: Default::default(),
652 // Cache where all our extern crates are located
653 for &(n, ref e) in &krate.externs {
654 let src_root = match e.src {
655 FileName::Real(ref p) => match p.parent() {
656 Some(p) => p.to_path_buf(),
657 None => PathBuf::new(),
661 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
662 cache.extern_locations.insert(n, (e.name.clone(), src_root,
663 extern_location(e, extern_url, &cx.dst)));
665 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
666 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
669 // Cache where all known primitives have their documentation located.
671 // Favor linking to as local extern as possible, so iterate all crates in
672 // reverse topological order.
673 for &(_, ref e) in krate.externs.iter().rev() {
674 for &(def_id, prim, _) in &e.primitives {
675 cache.primitive_locations.insert(prim, def_id);
678 for &(def_id, prim, _) in &krate.primitives {
679 cache.primitive_locations.insert(prim, def_id);
682 cache.stack.push(krate.name.clone());
683 krate = cache.fold_crate(krate);
685 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
686 if cache.traits.contains_key(&trait_did) {
688 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
693 // Build our search index
694 let index = build_index(&krate, &mut cache);
696 // Freeze the cache now that the index has been built. Put an Arc into TLS
697 // for future parallelization opportunities
698 let cache = Arc::new(cache);
699 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
700 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
702 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
704 // And finally render the whole crate's documentation
708 /// Builds the search index from the collected metadata
709 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
710 let mut nodeid_to_pathid = FxHashMap::default();
711 let mut crate_items = Vec::with_capacity(cache.search_index.len());
712 let mut crate_paths = Vec::<Json>::new();
714 let Cache { ref mut search_index,
715 ref orphan_impl_items,
716 ref mut paths, .. } = *cache;
718 // Attach all orphan items to the type's definition if the type
719 // has since been learned.
720 for &(did, ref item) in orphan_impl_items {
721 if let Some(&(ref fqp, _)) = paths.get(&did) {
722 search_index.push(IndexItem {
724 name: item.name.clone().unwrap(),
725 path: fqp[..fqp.len() - 1].join("::"),
726 desc: plain_summary_line_short(item.doc_value()),
729 search_type: get_index_search_type(&item),
734 // Reduce `NodeId` in paths into smaller sequential numbers,
735 // and prune the paths that do not appear in the index.
736 let mut lastpath = String::new();
737 let mut lastpathid = 0usize;
739 for item in search_index {
740 item.parent_idx = item.parent.map(|nodeid| {
741 if nodeid_to_pathid.contains_key(&nodeid) {
742 *nodeid_to_pathid.get(&nodeid).unwrap()
744 let pathid = lastpathid;
745 nodeid_to_pathid.insert(nodeid, pathid);
748 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
749 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
754 // Omit the parent path if it is same to that of the prior item.
755 if lastpath == item.path {
758 lastpath = item.path.clone();
760 crate_items.push(item.to_json());
763 let crate_doc = krate.module.as_ref().map(|module| {
764 plain_summary_line_short(module.doc_value())
765 }).unwrap_or(String::new());
767 let mut crate_data = BTreeMap::new();
768 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
769 crate_data.insert("i".to_owned(), Json::Array(crate_items));
770 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
772 // Collect the index into a string
773 format!("searchIndex[{}] = {};",
774 as_json(&krate.name),
775 Json::Object(crate_data))
780 krate: &clean::Crate,
782 search_index: String,
783 options: &RenderOptions,
784 diag: &errors::Handler,
785 ) -> Result<(), Error> {
786 // Write out the shared files. Note that these are shared among all rustdoc
787 // docs placed in the output directory, so this needs to be a synchronized
788 // operation with respect to all other rustdocs running around.
789 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
791 // Add all the static files. These may already exist, but we just
792 // overwrite them anyway to make sure that they're fresh and up-to-date.
794 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
795 static_files::RUSTDOC_CSS,
796 options.enable_minification)?;
797 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
798 static_files::SETTINGS_CSS,
799 options.enable_minification)?;
800 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
801 static_files::NOSCRIPT_CSS,
802 options.enable_minification)?;
804 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
805 // then we'll run over the "official" styles.
806 let mut themes: FxHashSet<String> = FxHashSet::default();
808 for entry in &cx.shared.themes {
809 let content = try_err!(fs::read(&entry), &entry);
810 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
811 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
812 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
813 content.as_slice())?;
814 themes.insert(theme.to_owned());
817 if (*cx.shared).layout.logo.is_empty() {
818 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
819 static_files::RUST_LOGO)?;
821 if (*cx.shared).layout.favicon.is_empty() {
822 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
823 static_files::RUST_FAVICON)?;
825 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
826 static_files::BRUSH_SVG)?;
827 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
828 static_files::WHEEL_SVG)?;
829 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
830 static_files::DOWN_ARROW_SVG)?;
831 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
832 static_files::themes::LIGHT,
833 options.enable_minification)?;
834 themes.insert("light".to_owned());
835 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
836 static_files::themes::DARK,
837 options.enable_minification)?;
838 themes.insert("dark".to_owned());
840 let mut themes: Vec<&String> = themes.iter().collect();
842 // To avoid theme switch latencies as much as possible, we put everything theme related
843 // at the beginning of the html files into another js file.
844 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
846 r#"var themes = document.getElementById("theme-choices");
847 var themePicker = document.getElementById("theme-picker");
849 function switchThemeButtonState() {{
850 if (themes.style.display === "block") {{
851 themes.style.display = "none";
852 themePicker.style.borderBottomRightRadius = "3px";
853 themePicker.style.borderBottomLeftRadius = "3px";
855 themes.style.display = "block";
856 themePicker.style.borderBottomRightRadius = "0";
857 themePicker.style.borderBottomLeftRadius = "0";
861 function handleThemeButtonsBlur(e) {{
862 var active = document.activeElement;
863 var related = e.relatedTarget;
865 if (active.id !== "themePicker" &&
866 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
868 (related.id !== "themePicker" &&
869 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
870 switchThemeButtonState();
874 themePicker.onclick = switchThemeButtonState;
875 themePicker.onblur = handleThemeButtonsBlur;
876 [{}].forEach(function(item) {{
877 var but = document.createElement('button');
878 but.innerHTML = item;
879 but.onclick = function(el) {{
880 switchTheme(currentTheme, mainTheme, item);
882 but.onblur = handleThemeButtonsBlur;
883 themes.appendChild(but);
886 .map(|s| format!("\"{}\"", s))
887 .collect::<Vec<String>>()
888 .join(",")).as_bytes(),
891 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
892 static_files::MAIN_JS,
893 options.enable_minification)?;
894 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
895 static_files::SETTINGS_JS,
896 options.enable_minification)?;
897 if cx.shared.include_sources {
898 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
899 static_files::sidebar::SOURCE_SCRIPT,
900 options.enable_minification)?;
904 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
905 &format!("var resourcesSuffix = \"{}\";{}",
906 cx.shared.resource_suffix,
907 static_files::STORAGE_JS),
908 options.enable_minification)?;
911 if let Some(ref css) = cx.shared.css_file_extension {
912 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
913 if !options.enable_minification {
914 try_err!(fs::copy(css, out), css);
916 let buffer = try_err!(fs::read_to_string(css), css);
917 write_minify(out, &buffer, options.enable_minification)?;
920 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
921 static_files::NORMALIZE_CSS,
922 options.enable_minification)?;
923 write(cx.dst.join("FiraSans-Regular.woff"),
924 static_files::fira_sans::REGULAR)?;
925 write(cx.dst.join("FiraSans-Medium.woff"),
926 static_files::fira_sans::MEDIUM)?;
927 write(cx.dst.join("FiraSans-LICENSE.txt"),
928 static_files::fira_sans::LICENSE)?;
929 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
930 static_files::source_serif_pro::REGULAR)?;
931 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
932 static_files::source_serif_pro::BOLD)?;
933 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
934 static_files::source_serif_pro::ITALIC)?;
935 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
936 static_files::source_serif_pro::LICENSE)?;
937 write(cx.dst.join("SourceCodePro-Regular.woff"),
938 static_files::source_code_pro::REGULAR)?;
939 write(cx.dst.join("SourceCodePro-Semibold.woff"),
940 static_files::source_code_pro::SEMIBOLD)?;
941 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
942 static_files::source_code_pro::LICENSE)?;
943 write(cx.dst.join("LICENSE-MIT.txt"),
944 static_files::LICENSE_MIT)?;
945 write(cx.dst.join("LICENSE-APACHE.txt"),
946 static_files::LICENSE_APACHE)?;
947 write(cx.dst.join("COPYRIGHT.txt"),
948 static_files::COPYRIGHT)?;
954 for_search_index: bool,
955 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
956 let mut ret = Vec::new();
957 let mut krates = Vec::new();
958 let mut variables = Vec::new();
961 for line in BufReader::new(File::open(path)?).lines() {
963 if for_search_index && line.starts_with("var R") {
964 variables.push(line.clone());
967 if !line.starts_with(key) {
970 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
973 ret.push(line.to_string());
974 krates.push(line[key.len() + 2..].split('"')
976 .map(|s| s.to_owned())
977 .unwrap_or_else(|| String::new()));
980 Ok((ret, krates, variables))
983 fn show_item(item: &IndexItem, krate: &str) -> String {
984 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
985 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
986 if let Some(p) = item.parent_idx {
987 format!(",'parent':{}", p)
993 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
995 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
996 let mut w = try_err!(File::create(&dst), &dst);
997 let mut output = String::with_capacity(100);
998 for (alias, items) in &cache.aliases {
999 if items.is_empty() {
1002 output.push_str(&format!("\"{}\":[{}],",
1005 .map(|v| show_item(v, &krate.name))
1006 .collect::<Vec<_>>()
1009 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1011 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1012 for aliases in &all_aliases {
1013 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1017 use std::ffi::OsString;
1022 children: FxHashMap<OsString, Hierarchy>,
1023 elems: FxHashSet<OsString>,
1027 fn new(elem: OsString) -> Hierarchy {
1030 children: FxHashMap::default(),
1031 elems: FxHashSet::default(),
1035 fn to_json_string(&self) -> String {
1036 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1037 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1038 let mut files = self.elems.iter()
1039 .map(|s| format!("\"{}\"",
1041 .expect("invalid osstring conversion")))
1042 .collect::<Vec<_>>();
1043 files.sort_unstable_by(|a, b| a.cmp(b));
1044 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
1045 let dirs = if subs.is_empty() {
1048 format!(",\"dirs\":[{}]", subs)
1050 let files = files.join(",");
1051 let files = if files.is_empty() {
1054 format!(",\"files\":[{}]", files)
1056 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
1057 name=self.elem.to_str().expect("invalid osstring conversion"),
1063 if cx.shared.include_sources {
1064 let mut hierarchy = Hierarchy::new(OsString::new());
1065 for source in cx.shared.local_sources.iter()
1066 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1068 let mut h = &mut hierarchy;
1069 let mut elems = source.components()
1072 Component::Normal(s) => Some(s.to_owned()),
1078 let cur_elem = elems.next().expect("empty file path");
1079 if elems.peek().is_none() {
1080 h.elems.insert(cur_elem);
1083 let e = cur_elem.clone();
1084 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1085 h = h.children.get_mut(&cur_elem).expect("not found child");
1090 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1091 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1094 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1096 hierarchy.to_json_string()));
1098 let mut w = try_err!(File::create(&dst), &dst);
1099 try_err!(writeln!(&mut w,
1100 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1101 all_sources.join("\n")),
1105 // Update the search index
1106 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1107 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1111 all_indexes.push(search_index);
1113 // Sort the indexes by crate so the file will be generated identically even
1114 // with rustdoc running in parallel.
1116 let mut w = try_err!(File::create(&dst), &dst);
1117 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1118 try_err!(write_minify_replacer(&mut w,
1119 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1120 options.enable_minification),
1122 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1124 if options.enable_index_page {
1125 if let Some(index_page) = options.index_page.clone() {
1126 let mut md_opts = options.clone();
1127 md_opts.output = cx.dst.clone();
1128 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1130 crate::markdown::render(index_page, md_opts, diag);
1132 let dst = cx.dst.join("index.html");
1133 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1134 let page = layout::Page {
1135 title: "Index of crates",
1138 static_root_path: cx.shared.static_root_path.deref(),
1139 description: "List of crates",
1140 keywords: BASIC_KEYWORDS,
1141 resource_suffix: &cx.shared.resource_suffix,
1143 static_extra_scripts: &[],
1145 krates.push(krate.name.clone());
1149 let content = format!(
1151 <span class='in-band'>List of all crates</span>\
1152 </h1><ul class='mod'>{}</ul>",
1156 format!("<li><a href=\"{}index.html\">{}</li>",
1159 .collect::<String>());
1160 try_err!(layout::render(&mut w, &cx.shared.layout,
1161 &page, &(""), &content,
1162 cx.shared.css_file_extension.is_some(),
1164 cx.shared.generate_search_filter), &dst);
1165 try_err!(w.flush(), &dst);
1169 // Update the list of all implementors for traits
1170 let dst = cx.dst.join("implementors");
1171 for (&did, imps) in &cache.implementors {
1172 // Private modules can leak through to this phase of rustdoc, which
1173 // could contain implementations for otherwise private types. In some
1174 // rare cases we could find an implementation for an item which wasn't
1175 // indexed, so we just skip this step in that case.
1177 // FIXME: this is a vague explanation for why this can't be a `get`, in
1178 // theory it should be...
1179 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1181 None => match cache.external_paths.get(&did) {
1187 let mut have_impls = false;
1188 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1190 // If the trait and implementation are in the same crate, then
1191 // there's no need to emit information about it (there's inlining
1192 // going on). If they're in different crates then the crate defining
1193 // the trait will be interested in our implementation.
1194 if imp.impl_item.def_id.krate == did.krate { continue }
1195 // If the implementation is from another crate then that crate
1197 if !imp.impl_item.def_id.is_local() { continue }
1199 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1200 as_json(&imp.inner_impl().to_string()),
1201 imp.inner_impl().synthetic,
1202 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1204 implementors.push_str("];");
1206 // Only create a js file if we have impls to add to it. If the trait is
1207 // documented locally though we always create the file to avoid dead
1209 if !have_impls && !cache.paths.contains_key(&did) {
1213 let mut mydst = dst.clone();
1214 for part in &remote_path[..remote_path.len() - 1] {
1217 try_err!(fs::create_dir_all(&mydst), &mydst);
1218 mydst.push(&format!("{}.{}.js",
1219 remote_item_type.css_class(),
1220 remote_path[remote_path.len() - 1]));
1222 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1225 all_implementors.push(implementors);
1226 // Sort the implementors by crate so the file will be generated
1227 // identically even with rustdoc running in parallel.
1228 all_implementors.sort();
1230 let mut f = try_err!(File::create(&mydst), &mydst);
1231 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1232 for implementor in &all_implementors {
1233 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1235 try_err!(writeln!(&mut f, "{}", r"
1236 if (window.register_implementors) {
1237 window.register_implementors(implementors);
1239 window.pending_implementors = implementors;
1242 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1247 fn render_sources(dst: &Path, scx: &mut SharedContext,
1248 krate: clean::Crate) -> Result<clean::Crate, Error> {
1249 info!("emitting source files");
1250 let dst = dst.join("src").join(&krate.name);
1251 try_err!(fs::create_dir_all(&dst), &dst);
1252 let mut folder = SourceCollector {
1256 Ok(folder.fold_crate(krate))
1259 /// Writes the entire contents of a string to a destination, not attempting to
1260 /// catch any errors.
1261 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1262 Ok(try_err!(fs::write(&dst, contents), &dst))
1265 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1266 if enable_minification {
1267 if dst.extension() == Some(&OsStr::new("css")) {
1268 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1269 write(dst, res.as_bytes())
1271 write(dst, minifier::js::minify(contents).as_bytes())
1274 write(dst, contents.as_bytes())
1278 fn write_minify_replacer<W: Write>(
1281 enable_minification: bool,
1282 ) -> io::Result<()> {
1283 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1285 if enable_minification {
1288 let tokens: Tokens<'_> = simple_minify(contents)
1291 // We keep backlines.
1292 minifier::js::clean_token_except(f, &|c: &Token<'_>| {
1293 c.get_char() != Some(ReservedChar::Backline)
1297 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1299 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1300 Token::String(s) => {
1301 let s = &s[1..s.len() -1]; // The quotes are included
1303 Some(Token::Other("E"))
1304 } else if s == "t" {
1305 Some(Token::Other("T"))
1306 } else if s == "u" {
1307 Some(Token::Other("U"))
1316 .collect::<Vec<_>>()
1319 // We add a backline after the newly created variables.
1320 minifier::js::aggregate_strings_into_array_with_separation_filter(
1323 Token::Char(ReservedChar::Backline),
1324 // This closure prevents crates' names from being aggregated.
1326 // The point here is to check if the string is preceded by '[' and
1327 // "searchIndex". If so, it means this is a crate name and that it
1328 // shouldn't be aggregated.
1331 !tokens[pos - 1].is_char(ReservedChar::OpenBracket) ||
1332 tokens[pos - 2].get_other() != Some("searchIndex")
1339 writeln!(dst, "{}", contents)
1343 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1344 /// things like ".." to components which preserve the "top down" hierarchy of a
1345 /// static HTML tree. Each component in the cleaned path will be passed as an
1346 /// argument to `f`. The very last component of the path (ie the file name) will
1347 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1348 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
1352 // make it relative, if possible
1353 let p = p.strip_prefix(src_root).unwrap_or(p);
1355 let mut iter = p.components().peekable();
1357 while let Some(c) = iter.next() {
1358 if !keep_filename && iter.peek().is_none() {
1363 Component::ParentDir => f("up".as_ref()),
1364 Component::Normal(c) => f(c),
1370 /// Attempts to find where an external crate is located, given that we're
1371 /// rendering in to the specified source destination.
1372 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1375 // See if there's documentation generated into the local directory
1376 let local_location = dst.join(&e.name);
1377 if local_location.is_dir() {
1381 if let Some(url) = extern_url {
1382 let mut url = url.to_string();
1383 if !url.ends_with("/") {
1389 // Failing that, see if there's an attribute specifying where to find this
1391 e.attrs.lists("doc")
1392 .filter(|a| a.check_name("html_root_url"))
1393 .filter_map(|a| a.value_str())
1395 let mut url = url.to_string();
1396 if !url.ends_with("/") {
1400 }).next().unwrap_or(Unknown) // Well, at least we tried.
1403 impl<'a> DocFolder for SourceCollector<'a> {
1404 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1405 // If we're including source files, and we haven't seen this file yet,
1406 // then we need to render it out to the filesystem.
1407 if self.scx.include_sources
1408 // skip all invalid or macro spans
1409 && item.source.filename.is_real()
1410 // skip non-local items
1411 && item.def_id.is_local() {
1413 // If it turns out that we couldn't read this file, then we probably
1414 // can't read any of the files (generating html output from json or
1415 // something like that), so just don't include sources for the
1416 // entire crate. The other option is maintaining this mapping on a
1417 // per-file basis, but that's probably not worth it...
1419 .include_sources = match self.emit_source(&item.source.filename) {
1422 println!("warning: source code was requested to be rendered, \
1423 but processing `{}` had an error: {}",
1424 item.source.filename, e);
1425 println!(" skipping rendering of source code");
1430 self.fold_item_recur(item)
1434 impl<'a> SourceCollector<'a> {
1435 /// Renders the given filename into its corresponding HTML source file.
1436 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1437 let p = match *filename {
1438 FileName::Real(ref file) => file,
1441 if self.scx.local_sources.contains_key(&**p) {
1442 // We've already emitted this source
1446 let contents = fs::read_to_string(&p)?;
1448 // Remove the utf-8 BOM if any
1449 let contents = if contents.starts_with("\u{feff}") {
1455 // Create the intermediate directories
1456 let mut cur = self.dst.clone();
1457 let mut root_path = String::from("../../");
1458 let mut href = String::new();
1459 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1460 cur.push(component);
1461 root_path.push_str("../");
1462 href.push_str(&component.to_string_lossy());
1465 fs::create_dir_all(&cur)?;
1466 let mut fname = p.file_name()
1467 .expect("source has no filename")
1469 fname.push(".html");
1471 href.push_str(&fname.to_string_lossy());
1473 let mut w = BufWriter::new(File::create(&cur)?);
1474 let title = format!("{} -- source", cur.file_name().expect("failed to get file name")
1475 .to_string_lossy());
1476 let desc = format!("Source to the Rust file `{}`.", filename);
1477 let page = layout::Page {
1479 css_class: "source",
1480 root_path: &root_path,
1481 static_root_path: self.scx.static_root_path.deref(),
1483 keywords: BASIC_KEYWORDS,
1484 resource_suffix: &self.scx.resource_suffix,
1485 extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
1486 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1488 layout::render(&mut w, &self.scx.layout,
1489 &page, &(""), &Source(contents),
1490 self.scx.css_file_extension.is_some(),
1492 self.scx.generate_search_filter)?;
1494 self.scx.local_sources.insert(p.clone(), href);
1499 impl DocFolder for Cache {
1500 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1501 if item.def_id.is_local() {
1502 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1505 // If this is a stripped module,
1506 // we don't want it or its children in the search index.
1507 let orig_stripped_mod = match item.inner {
1508 clean::StrippedItem(box clean::ModuleItem(..)) => {
1509 mem::replace(&mut self.stripped_mod, true)
1511 _ => self.stripped_mod,
1514 // If the impl is from a masked crate or references something from a
1515 // masked crate then remove it completely.
1516 if let clean::ImplItem(ref i) = item.inner {
1517 if self.masked_crates.contains(&item.def_id.krate) ||
1518 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1519 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1524 // Register any generics to their corresponding string. This is used
1525 // when pretty-printing types.
1526 if let Some(generics) = item.inner.generics() {
1527 self.generics(generics);
1530 // Propagate a trait method's documentation to all implementors of the
1532 if let clean::TraitItem(ref t) = item.inner {
1533 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1536 // Collect all the implementors of traits.
1537 if let clean::ImplItem(ref i) = item.inner {
1538 if let Some(did) = i.trait_.def_id() {
1539 if i.blanket_impl.is_none() {
1540 self.implementors.entry(did).or_default().push(Impl {
1541 impl_item: item.clone(),
1547 // Index this method for searching later on.
1548 if let Some(ref s) = item.name {
1549 let (parent, is_inherent_impl_item) = match item.inner {
1550 clean::StrippedItem(..) => ((None, None), false),
1551 clean::AssociatedConstItem(..) |
1552 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1553 // skip associated items in trait impls
1554 ((None, None), false)
1556 clean::AssociatedTypeItem(..) |
1557 clean::TyMethodItem(..) |
1558 clean::StructFieldItem(..) |
1559 clean::VariantItem(..) => {
1560 ((Some(*self.parent_stack.last().unwrap()),
1561 Some(&self.stack[..self.stack.len() - 1])),
1564 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1565 if self.parent_stack.is_empty() {
1566 ((None, None), false)
1568 let last = self.parent_stack.last().unwrap();
1570 let path = match self.paths.get(&did) {
1571 // The current stack not necessarily has correlation
1572 // for where the type was defined. On the other
1573 // hand, `paths` always has the right
1574 // information if present.
1575 Some(&(ref fqp, ItemType::Trait)) |
1576 Some(&(ref fqp, ItemType::Struct)) |
1577 Some(&(ref fqp, ItemType::Union)) |
1578 Some(&(ref fqp, ItemType::Enum)) =>
1579 Some(&fqp[..fqp.len() - 1]),
1580 Some(..) => Some(&*self.stack),
1583 ((Some(*last), path), true)
1586 _ => ((None, Some(&*self.stack)), false)
1590 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1591 debug_assert!(!item.is_stripped());
1593 // A crate has a module at its root, containing all items,
1594 // which should not be indexed. The crate-item itself is
1595 // inserted later on when serializing the search-index.
1596 if item.def_id.index != CRATE_DEF_INDEX {
1597 self.search_index.push(IndexItem {
1599 name: s.to_string(),
1600 path: path.join("::"),
1601 desc: plain_summary_line_short(item.doc_value()),
1604 search_type: get_index_search_type(&item),
1608 (Some(parent), None) if is_inherent_impl_item => {
1609 // We have a parent, but we don't know where they're
1610 // defined yet. Wait for later to index this item.
1611 self.orphan_impl_items.push((parent, item.clone()));
1617 // Keep track of the fully qualified path for this item.
1618 let pushed = match item.name {
1619 Some(ref n) if !n.is_empty() => {
1620 self.stack.push(n.to_string());
1627 clean::StructItem(..) | clean::EnumItem(..) |
1628 clean::TypedefItem(..) | clean::TraitItem(..) |
1629 clean::FunctionItem(..) | clean::ModuleItem(..) |
1630 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1631 clean::ConstantItem(..) | clean::StaticItem(..) |
1632 clean::UnionItem(..) | clean::ForeignTypeItem |
1633 clean::MacroItem(..) | clean::ProcMacroItem(..)
1634 if !self.stripped_mod => {
1635 // Re-exported items mean that the same id can show up twice
1636 // in the rustdoc ast that we're looking at. We know,
1637 // however, that a re-exported item doesn't show up in the
1638 // `public_items` map, so we can skip inserting into the
1639 // paths map if there was already an entry present and we're
1640 // not a public item.
1641 if !self.paths.contains_key(&item.def_id) ||
1642 self.access_levels.is_public(item.def_id)
1644 self.paths.insert(item.def_id,
1645 (self.stack.clone(), item.type_()));
1647 self.add_aliases(&item);
1649 // Link variants to their parent enum because pages aren't emitted
1650 // for each variant.
1651 clean::VariantItem(..) if !self.stripped_mod => {
1652 let mut stack = self.stack.clone();
1654 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1657 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1658 self.add_aliases(&item);
1659 self.paths.insert(item.def_id, (self.stack.clone(),
1666 // Maintain the parent stack
1667 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1668 let parent_pushed = match item.inner {
1669 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1670 clean::StructItem(..) | clean::UnionItem(..) => {
1671 self.parent_stack.push(item.def_id);
1672 self.parent_is_trait_impl = false;
1675 clean::ImplItem(ref i) => {
1676 self.parent_is_trait_impl = i.trait_.is_some();
1678 clean::ResolvedPath{ did, .. } => {
1679 self.parent_stack.push(did);
1683 let prim_did = t.primitive_type().and_then(|t| {
1684 self.primitive_locations.get(&t).cloned()
1688 self.parent_stack.push(did);
1699 // Once we've recursively found all the generics, hoard off all the
1700 // implementations elsewhere.
1701 let ret = self.fold_item_recur(item).and_then(|item| {
1702 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1703 // Figure out the id of this impl. This may map to a
1704 // primitive rather than always to a struct/enum.
1705 // Note: matching twice to restrict the lifetime of the `i` borrow.
1706 let mut dids = FxHashSet::default();
1707 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1709 clean::ResolvedPath { did, .. } |
1710 clean::BorrowedRef {
1711 type_: box clean::ResolvedPath { did, .. }, ..
1716 let did = t.primitive_type().and_then(|t| {
1717 self.primitive_locations.get(&t).cloned()
1720 if let Some(did) = did {
1726 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1727 for bound in generics {
1728 if let Some(did) = bound.def_id() {
1736 let impl_item = Impl {
1739 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1741 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1744 let trait_did = impl_item.trait_did().unwrap();
1745 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1753 if pushed { self.stack.pop().unwrap(); }
1754 if parent_pushed { self.parent_stack.pop().unwrap(); }
1755 self.stripped_mod = orig_stripped_mod;
1756 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1762 fn generics(&mut self, generics: &clean::Generics) {
1763 for param in &generics.params {
1765 clean::GenericParamDefKind::Lifetime => {}
1766 clean::GenericParamDefKind::Type { did, .. } |
1767 clean::GenericParamDefKind::Const { did, .. } => {
1768 self.param_names.insert(did, param.name.clone());
1774 fn add_aliases(&mut self, item: &clean::Item) {
1775 if item.def_id.index == CRATE_DEF_INDEX {
1778 if let Some(ref item_name) = item.name {
1779 let path = self.paths.get(&item.def_id)
1780 .map(|p| p.0[..p.0.len() - 1].join("::"))
1781 .unwrap_or("std".to_owned());
1782 for alias in item.attrs.lists("doc")
1783 .filter(|a| a.check_name("alias"))
1784 .filter_map(|a| a.value_str()
1785 .map(|s| s.to_string().replace("\"", "")))
1786 .filter(|v| !v.is_empty())
1787 .collect::<FxHashSet<_>>()
1789 self.aliases.entry(alias)
1790 .or_insert(Vec::with_capacity(1))
1793 name: item_name.to_string(),
1795 desc: plain_summary_line_short(item.doc_value()),
1798 search_type: get_index_search_type(&item),
1805 #[derive(Debug, Eq, PartialEq, Hash)]
1812 fn new(mut url: String, name: String) -> ItemEntry {
1813 while url.starts_with('/') {
1823 impl fmt::Display for ItemEntry {
1824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1829 impl PartialOrd for ItemEntry {
1830 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1831 Some(self.cmp(other))
1835 impl Ord for ItemEntry {
1836 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1837 self.name.cmp(&other.name)
1843 structs: FxHashSet<ItemEntry>,
1844 enums: FxHashSet<ItemEntry>,
1845 unions: FxHashSet<ItemEntry>,
1846 primitives: FxHashSet<ItemEntry>,
1847 traits: FxHashSet<ItemEntry>,
1848 macros: FxHashSet<ItemEntry>,
1849 functions: FxHashSet<ItemEntry>,
1850 typedefs: FxHashSet<ItemEntry>,
1851 existentials: FxHashSet<ItemEntry>,
1852 statics: FxHashSet<ItemEntry>,
1853 constants: FxHashSet<ItemEntry>,
1854 keywords: FxHashSet<ItemEntry>,
1855 attributes: FxHashSet<ItemEntry>,
1856 derives: FxHashSet<ItemEntry>,
1857 trait_aliases: FxHashSet<ItemEntry>,
1861 fn new() -> AllTypes {
1862 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1864 structs: new_set(100),
1865 enums: new_set(100),
1866 unions: new_set(100),
1867 primitives: new_set(26),
1868 traits: new_set(100),
1869 macros: new_set(100),
1870 functions: new_set(100),
1871 typedefs: new_set(100),
1872 existentials: new_set(100),
1873 statics: new_set(100),
1874 constants: new_set(100),
1875 keywords: new_set(100),
1876 attributes: new_set(100),
1877 derives: new_set(100),
1878 trait_aliases: new_set(100),
1882 fn append(&mut self, item_name: String, item_type: &ItemType) {
1883 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1884 if let Some(name) = url.pop() {
1885 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1887 let name = url.join("::");
1889 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1890 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1891 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1892 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1893 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1894 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1895 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1896 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1897 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1898 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1899 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1900 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1901 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1902 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1909 fn print_entries(f: &mut fmt::Formatter<'_>, e: &FxHashSet<ItemEntry>, title: &str,
1910 class: &str) -> fmt::Result {
1912 let mut e: Vec<&ItemEntry> = e.iter().collect();
1914 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1918 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1923 impl fmt::Display for AllTypes {
1924 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1927 <span class='out-of-band'>\
1928 <span id='render-detail'>\
1929 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1930 [<span class='inner'>−</span>]\
1934 <span class='in-band'>List of all items</span>\
1936 print_entries(f, &self.structs, "Structs", "structs")?;
1937 print_entries(f, &self.enums, "Enums", "enums")?;
1938 print_entries(f, &self.unions, "Unions", "unions")?;
1939 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1940 print_entries(f, &self.traits, "Traits", "traits")?;
1941 print_entries(f, &self.macros, "Macros", "macros")?;
1942 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1943 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1944 print_entries(f, &self.functions, "Functions", "functions")?;
1945 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1946 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1947 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1948 print_entries(f, &self.statics, "Statics", "statics")?;
1949 print_entries(f, &self.constants, "Constants", "constants")
1954 struct Settings<'a> {
1955 // (id, explanation, default value)
1956 settings: Vec<(&'static str, &'static str, bool)>,
1961 impl<'a> Settings<'a> {
1962 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1965 ("item-declarations", "Auto-hide item declarations.", true),
1966 ("item-attributes", "Auto-hide item attributes.", true),
1967 ("trait-implementations", "Auto-hide trait implementations documentation",
1969 ("method-docs", "Auto-hide item methods' documentation", false),
1970 ("go-to-only-result", "Directly go to item in search if there is only one result",
1972 ("line-numbers", "Show line numbers on code examples", false),
1980 impl<'a> fmt::Display for Settings<'a> {
1981 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1984 <span class='in-band'>Rustdoc settings</span>\
1986 <div class='settings'>{}</div>\
1987 <script src='{}settings{}.js'></script>",
1988 self.settings.iter()
1989 .map(|(id, text, enabled)| {
1990 format!("<div class='setting-line'>\
1991 <label class='toggle'>\
1992 <input type='checkbox' id='{}' {}>\
1993 <span class='slider'></span>\
1996 </div>", id, if *enabled { " checked" } else { "" }, text)
1998 .collect::<String>(),
2005 fn derive_id(&self, id: String) -> String {
2006 let mut map = self.id_map.borrow_mut();
2010 /// String representation of how to get back to the root path of the 'doc/'
2011 /// folder in terms of a relative URL.
2012 fn root_path(&self) -> String {
2013 "../".repeat(self.current.len())
2016 /// Recurse in the directory structure and change the "root path" to make
2017 /// sure it always points to the top (relatively).
2018 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2019 F: FnOnce(&mut Context) -> T,
2022 panic!("Unexpected empty destination: {:?}", self.current);
2024 let prev = self.dst.clone();
2026 self.current.push(s);
2028 info!("Recursing into {}", self.dst.display());
2032 info!("Recursed; leaving {}", self.dst.display());
2034 // Go back to where we were at
2036 self.current.pop().unwrap();
2041 /// Main method for rendering a crate.
2043 /// This currently isn't parallelized, but it'd be pretty easy to add
2044 /// parallelization to this function.
2045 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2046 let mut item = match krate.module.take() {
2048 None => return Ok(()),
2050 let final_file = self.dst.join(&krate.name)
2052 let settings_file = self.dst.join("settings.html");
2054 let crate_name = krate.name.clone();
2055 item.name = Some(krate.name);
2057 let mut all = AllTypes::new();
2060 // Render the crate documentation
2061 let mut work = vec![(self.clone(), item)];
2063 while let Some((mut cx, item)) = work.pop() {
2064 cx.item(item, &mut all, |cx, item| {
2065 work.push((cx.clone(), item))
2070 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2071 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2072 if !root_path.ends_with('/') {
2073 root_path.push('/');
2075 let mut page = layout::Page {
2076 title: "List of all items in this crate",
2079 static_root_path: self.shared.static_root_path.deref(),
2080 description: "List of all items in this crate",
2081 keywords: BASIC_KEYWORDS,
2082 resource_suffix: &self.shared.resource_suffix,
2084 static_extra_scripts: &[],
2086 let sidebar = if let Some(ref version) = cache().crate_version {
2087 format!("<p class='location'>Crate {}</p>\
2088 <div class='block version'>\
2091 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2092 crate_name, version)
2096 try_err!(layout::render(&mut w, &self.shared.layout,
2097 &page, &sidebar, &all,
2098 self.shared.css_file_extension.is_some(),
2099 &self.shared.themes,
2100 self.shared.generate_search_filter),
2103 // Generating settings page.
2104 let settings = Settings::new(self.shared.static_root_path.deref().unwrap_or("./"),
2105 &self.shared.resource_suffix);
2106 page.title = "Rustdoc settings";
2107 page.description = "Settings of Rustdoc";
2108 page.root_path = "./";
2110 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2111 let mut themes = self.shared.themes.clone();
2112 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2113 themes.push(PathBuf::from("settings.css"));
2114 let layout = self.shared.layout.clone();
2115 try_err!(layout::render(&mut w, &layout,
2116 &page, &sidebar, &settings,
2117 self.shared.css_file_extension.is_some(),
2119 self.shared.generate_search_filter),
2125 fn render_item(&self,
2126 writer: &mut dyn io::Write,
2130 // A little unfortunate that this is done like this, but it sure
2131 // does make formatting *a lot* nicer.
2132 CURRENT_LOCATION_KEY.with(|slot| {
2133 *slot.borrow_mut() = self.current.clone();
2136 let mut title = if it.is_primitive() || it.is_keyword() {
2137 // No need to include the namespace for primitive types and keywords
2140 self.current.join("::")
2143 if !title.is_empty() {
2144 title.push_str("::");
2146 title.push_str(it.name.as_ref().unwrap());
2148 title.push_str(" - Rust");
2149 let tyname = it.type_().css_class();
2150 let desc = if it.is_crate() {
2151 format!("API documentation for the Rust `{}` crate.",
2152 self.shared.layout.krate)
2154 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2155 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2157 let keywords = make_item_keywords(it);
2158 let page = layout::Page {
2160 root_path: &self.root_path(),
2161 static_root_path: self.shared.static_root_path.deref(),
2164 keywords: &keywords,
2165 resource_suffix: &self.shared.resource_suffix,
2167 static_extra_scripts: &[],
2171 self.id_map.borrow_mut().reset();
2172 self.id_map.borrow_mut().populate(initial_ids());
2175 if !self.render_redirect_pages {
2176 layout::render(writer, &self.shared.layout, &page,
2177 &Sidebar{ cx: self, item: it },
2178 &Item{ cx: self, item: it },
2179 self.shared.css_file_extension.is_some(),
2180 &self.shared.themes,
2181 self.shared.generate_search_filter)?;
2183 let mut url = self.root_path();
2184 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2185 for name in &names[..names.len() - 1] {
2189 url.push_str(&item_path(ty, names.last().unwrap()));
2190 layout::redirect(writer, &url)?;
2196 /// Non-parallelized version of rendering an item. This will take the input
2197 /// item, render its contents, and then invoke the specified closure with
2198 /// all sub-items which need to be rendered.
2200 /// The rendering driver uses this closure to queue up more work.
2201 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2202 where F: FnMut(&mut Context, clean::Item),
2204 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2205 // if they contain impls for public types. These modules can also
2206 // contain items such as publicly re-exported structures.
2208 // External crates will provide links to these structures, so
2209 // these modules are recursed into, but not rendered normally
2210 // (a flag on the context).
2211 if !self.render_redirect_pages {
2212 self.render_redirect_pages = item.is_stripped();
2216 // modules are special because they add a namespace. We also need to
2217 // recurse into the items of the module as well.
2218 let name = item.name.as_ref().unwrap().to_string();
2219 let mut item = Some(item);
2220 self.recurse(name, |this| {
2221 let item = item.take().unwrap();
2223 let mut buf = Vec::new();
2224 this.render_item(&mut buf, &item, false).unwrap();
2225 // buf will be empty if the module is stripped and there is no redirect for it
2226 if !buf.is_empty() {
2227 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2228 let joint_dst = this.dst.join("index.html");
2229 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2232 let m = match item.inner {
2233 clean::StrippedItem(box clean::ModuleItem(m)) |
2234 clean::ModuleItem(m) => m,
2238 // Render sidebar-items.js used throughout this module.
2239 if !this.render_redirect_pages {
2240 let items = this.build_sidebar_items(&m);
2241 let js_dst = this.dst.join("sidebar-items.js");
2242 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2243 try_err!(write!(&mut js_out, "initSidebarItems({});",
2244 as_json(&items)), &js_dst);
2247 for item in m.items {
2253 } else if item.name.is_some() {
2254 let mut buf = Vec::new();
2255 self.render_item(&mut buf, &item, true).unwrap();
2256 // buf will be empty if the item is stripped and there is no redirect for it
2257 if !buf.is_empty() {
2258 let name = item.name.as_ref().unwrap();
2259 let item_type = item.type_();
2260 let file_name = &item_path(item_type, name);
2261 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2262 let joint_dst = self.dst.join(file_name);
2263 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2265 if !self.render_redirect_pages {
2266 all.append(full_path(self, &item), &item_type);
2268 if self.shared.generate_redirect_pages {
2269 // Redirect from a sane URL using the namespace to Rustdoc's
2270 // URL for the page.
2271 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2272 let redir_dst = self.dst.join(redir_name);
2273 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2276 let mut redirect_out = BufWriter::new(redirect_out);
2277 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2280 // If the item is a macro, redirect from the old macro URL (with !)
2281 // to the new one (without).
2282 if item_type == ItemType::Macro {
2283 let redir_name = format!("{}.{}!.html", item_type, name);
2284 let redir_dst = self.dst.join(redir_name);
2285 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2286 let mut redirect_out = BufWriter::new(redirect_out);
2287 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2294 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2295 // BTreeMap instead of HashMap to get a sorted output
2296 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2297 for item in &m.items {
2298 if item.is_stripped() { continue }
2300 let short = item.type_().css_class();
2301 let myname = match item.name {
2303 Some(ref s) => s.to_string(),
2305 let short = short.to_string();
2306 map.entry(short).or_default()
2307 .push((myname, Some(plain_summary_line(item.doc_value()))));
2310 if self.shared.sort_modules_alphabetically {
2311 for (_, items) in &mut map {
2320 /// Generates a url appropriate for an `href` attribute back to the source of
2323 /// The url generated, when clicked, will redirect the browser back to the
2324 /// original source code.
2326 /// If `None` is returned, then a source link couldn't be generated. This
2327 /// may happen, for example, with externally inlined items where the source
2328 /// of their crate documentation isn't known.
2329 fn src_href(&self) -> Option<String> {
2330 let mut root = self.cx.root_path();
2332 let cache = cache();
2333 let mut path = String::new();
2335 // We can safely ignore macros from other libraries
2336 let file = match self.item.source.filename {
2337 FileName::Real(ref path) => path,
2341 let (krate, path) = if self.item.def_id.is_local() {
2342 if let Some(path) = self.cx.shared.local_sources.get(file) {
2343 (&self.cx.shared.layout.krate, path)
2348 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2349 (ref name, ref src, Local) => (name, src),
2350 (ref name, ref src, Remote(ref s)) => {
2351 root = s.to_string();
2354 (_, _, Unknown) => return None,
2357 clean_srcpath(&src_root, file, false, |component| {
2358 path.push_str(&component.to_string_lossy());
2361 let mut fname = file.file_name().expect("source has no filename")
2363 fname.push(".html");
2364 path.push_str(&fname.to_string_lossy());
2368 let lines = if self.item.source.loline == self.item.source.hiline {
2369 self.item.source.loline.to_string()
2371 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2373 Some(format!("{root}src/{krate}/{path}#{lines}",
2374 root = Escape(&root),
2381 fn wrap_into_docblock<F>(w: &mut fmt::Formatter<'_>,
2382 f: F) -> fmt::Result
2383 where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result {
2384 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2389 impl<'a> fmt::Display for Item<'a> {
2390 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2391 debug_assert!(!self.item.is_stripped());
2392 // Write the breadcrumb trail header for the top
2393 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2394 if let Some(version) = self.item.stable_since() {
2395 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2399 "<span id='render-detail'>\
2400 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2401 title=\"collapse all docs\">\
2402 [<span class='inner'>−</span>]\
2408 // When this item is part of a `pub use` in a downstream crate, the
2409 // [src] link in the downstream documentation will actually come back to
2410 // this page, and this link will be auto-clicked. The `id` attribute is
2411 // used to find the link to auto-click.
2412 if self.cx.shared.include_sources && !self.item.is_primitive() {
2413 if let Some(l) = self.src_href() {
2414 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2415 l, "goto source code")?;
2419 write!(fmt, "</span>")?; // out-of-band
2420 write!(fmt, "<span class='in-band'>")?;
2421 match self.item.inner {
2422 clean::ModuleItem(ref m) => if m.is_crate {
2423 write!(fmt, "Crate ")?;
2425 write!(fmt, "Module ")?;
2427 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2428 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2429 clean::StructItem(..) => write!(fmt, "Struct ")?,
2430 clean::UnionItem(..) => write!(fmt, "Union ")?,
2431 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2432 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2433 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2434 clean::ProcMacroItem(ref mac) => match mac.kind {
2435 MacroKind::Bang => write!(fmt, "Macro ")?,
2436 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2437 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2438 MacroKind::ProcMacroStub => unreachable!(),
2440 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2441 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2442 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2443 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2444 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2445 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2446 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2448 // We don't generate pages for any other type.
2452 if !self.item.is_primitive() && !self.item.is_keyword() {
2453 let cur = &self.cx.current;
2454 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2455 for (i, component) in cur.iter().enumerate().take(amt) {
2456 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2457 "../".repeat(cur.len() - i - 1),
2461 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2462 self.item.type_(), self.item.name.as_ref().unwrap())?;
2464 write!(fmt, "</span></h1>")?; // in-band
2466 match self.item.inner {
2467 clean::ModuleItem(ref m) =>
2468 item_module(fmt, self.cx, self.item, &m.items),
2469 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2470 item_function(fmt, self.cx, self.item, f),
2471 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2472 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2473 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2474 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2475 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2476 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2477 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2478 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2479 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2480 item_static(fmt, self.cx, self.item, i),
2481 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2482 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2483 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2484 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2485 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2487 // We don't generate pages for any other type.
2494 fn item_path(ty: ItemType, name: &str) -> String {
2496 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2497 _ => format!("{}.{}.html", ty.css_class(), name),
2501 fn full_path(cx: &Context, item: &clean::Item) -> String {
2502 let mut s = cx.current.join("::");
2504 s.push_str(item.name.as_ref().unwrap());
2508 fn shorter<'a>(s: Option<&'a str>) -> String {
2510 Some(s) => s.lines()
2511 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2513 (*line).chars().any(|chr|{
2514 !chr.is_whitespace()
2516 }).collect::<Vec<_>>().join("\n"),
2517 None => String::new()
2522 fn plain_summary_line(s: Option<&str>) -> String {
2523 let line = shorter(s).replace("\n", " ");
2524 markdown::plain_summary_line_full(&line[..], false)
2528 fn plain_summary_line_short(s: Option<&str>) -> String {
2529 let line = shorter(s).replace("\n", " ");
2530 markdown::plain_summary_line_full(&line[..], true)
2533 fn document(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item) -> fmt::Result {
2534 if let Some(ref name) = item.name {
2535 info!("Documenting {}", name);
2537 document_stability(w, cx, item, false)?;
2538 document_full(w, item, cx, "", false)?;
2542 /// Render md_text as markdown.
2543 fn render_markdown(w: &mut fmt::Formatter<'_>,
2546 links: Vec<(String, String)>,
2550 let mut ids = cx.id_map.borrow_mut();
2551 write!(w, "<div class='docblock{}'>{}{}</div>",
2552 if is_hidden { " hidden" } else { "" },
2554 Markdown(md_text, &links, RefCell::new(&mut ids),
2559 w: &mut fmt::Formatter<'_>,
2562 link: AssocItemLink<'_>,
2563 prefix: &str, is_hidden: bool
2565 if let Some(s) = item.doc_value() {
2566 let markdown = if s.contains('\n') {
2567 format!("{} [Read more]({})",
2568 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2570 plain_summary_line(Some(s))
2572 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2573 } else if !prefix.is_empty() {
2574 write!(w, "<div class='docblock{}'>{}</div>",
2575 if is_hidden { " hidden" } else { "" },
2581 fn document_full(w: &mut fmt::Formatter<'_>, item: &clean::Item,
2582 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2583 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2584 debug!("Doc block: =====\n{}\n=====", s);
2585 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2586 } else if !prefix.is_empty() {
2587 write!(w, "<div class='docblock{}'>{}</div>",
2588 if is_hidden { " hidden" } else { "" },
2594 fn document_stability(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
2595 is_hidden: bool) -> fmt::Result {
2596 let stabilities = short_stability(item, cx);
2597 if !stabilities.is_empty() {
2598 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2599 for stability in stabilities {
2600 write!(w, "{}", stability)?;
2602 write!(w, "</div>")?;
2607 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2608 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2611 fn document_non_exhaustive(w: &mut fmt::Formatter<'_>, item: &clean::Item) -> fmt::Result {
2612 if item.is_non_exhaustive() {
2613 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2614 if item.is_struct() {
2616 } else if item.is_enum() {
2618 } else if item.is_variant() {
2625 if item.is_struct() {
2626 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2627 Therefore, non-exhaustive structs cannot be constructed in external crates \
2628 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2629 matched against without a wildcard <code>..</code>; and \
2630 struct update syntax will not work.")?;
2631 } else if item.is_enum() {
2632 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2633 Therefore, when matching against variants of non-exhaustive enums, an \
2634 extra wildcard arm must be added to account for any future variants.")?;
2635 } else if item.is_variant() {
2636 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
2637 Therefore, non-exhaustive enum variants cannot be constructed in external \
2638 crates and cannot be matched against.")?;
2640 write!(w, "This type will require a wildcard arm in any match statements or \
2644 write!(w, "</div>")?;
2650 fn name_key(name: &str) -> (&str, u64, usize) {
2651 let end = name.bytes()
2652 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2654 // find number at end
2655 let split = name[0..end].bytes()
2656 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2658 // count leading zeroes
2660 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2662 // sort leading zeroes last
2663 let num_zeroes = after_zeroes - split;
2665 match name[split..end].parse() {
2666 Ok(n) => (&name[..split], n, num_zeroes),
2667 Err(_) => (name, 0, num_zeroes),
2671 fn item_module(w: &mut fmt::Formatter<'_>, cx: &Context,
2672 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2673 document(w, cx, item)?;
2675 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2677 // the order of item types in the listing
2678 fn reorder(ty: ItemType) -> u8 {
2680 ItemType::ExternCrate => 0,
2681 ItemType::Import => 1,
2682 ItemType::Primitive => 2,
2683 ItemType::Module => 3,
2684 ItemType::Macro => 4,
2685 ItemType::Struct => 5,
2686 ItemType::Enum => 6,
2687 ItemType::Constant => 7,
2688 ItemType::Static => 8,
2689 ItemType::Trait => 9,
2690 ItemType::Function => 10,
2691 ItemType::Typedef => 12,
2692 ItemType::Union => 13,
2697 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2698 let ty1 = i1.type_();
2699 let ty2 = i2.type_();
2701 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2703 let s1 = i1.stability.as_ref().map(|s| s.level);
2704 let s2 = i2.stability.as_ref().map(|s| s.level);
2706 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2707 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2710 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2711 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2712 name_key(lhs).cmp(&name_key(rhs))
2715 if cx.shared.sort_modules_alphabetically {
2716 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2718 // This call is to remove re-export duplicates in cases such as:
2723 // pub trait Double { fn foo(); }
2727 // pub use foo::bar::*;
2731 // `Double` will appear twice in the generated docs.
2733 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2734 // can be identical even if the elements are different (mostly in imports).
2735 // So in case this is an import, we keep everything by adding a "unique id"
2736 // (which is the position in the vector).
2737 indices.dedup_by_key(|i| (items[*i].def_id,
2738 if items[*i].name.as_ref().is_some() {
2739 Some(full_path(cx, &items[*i]))
2744 if items[*i].is_import() {
2750 debug!("{:?}", indices);
2751 let mut curty = None;
2752 for &idx in &indices {
2753 let myitem = &items[idx];
2754 if myitem.is_stripped() {
2758 let myty = Some(myitem.type_());
2759 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2760 // Put `extern crate` and `use` re-exports in the same section.
2762 } else if myty != curty {
2763 if curty.is_some() {
2764 write!(w, "</table>")?;
2767 let (short, name) = item_ty_to_strs(&myty.unwrap());
2768 write!(w, "<h2 id='{id}' class='section-header'>\
2769 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2770 id = cx.derive_id(short.to_owned()), name = name)?;
2773 match myitem.inner {
2774 clean::ExternCrateItem(ref name, ref src) => {
2775 use crate::html::format::HRef;
2779 write!(w, "<tr><td><code>{}extern crate {} as {};",
2780 VisSpace(&myitem.visibility),
2781 HRef::new(myitem.def_id, src),
2785 write!(w, "<tr><td><code>{}extern crate {};",
2786 VisSpace(&myitem.visibility),
2787 HRef::new(myitem.def_id, name))?
2790 write!(w, "</code></td></tr>")?;
2793 clean::ImportItem(ref import) => {
2794 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2795 VisSpace(&myitem.visibility), *import)?;
2799 if myitem.name.is_none() { continue }
2801 let unsafety_flag = match myitem.inner {
2802 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2803 if func.header.unsafety == hir::Unsafety::Unsafe => {
2804 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2809 let stab = myitem.stability_class();
2810 let add = if stab.is_some() {
2816 let doc_value = myitem.doc_value().unwrap_or("");
2818 <tr class='{stab}{add}module-item'>\
2819 <td><a class=\"{class}\" href=\"{href}\" \
2820 title='{title}'>{name}</a>{unsafety_flag}</td>\
2821 <td class='docblock-short'>{stab_tags}{docs}</td>\
2823 name = *myitem.name.as_ref().unwrap(),
2824 stab_tags = stability_tags(myitem),
2825 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2826 class = myitem.type_(),
2828 stab = stab.unwrap_or_else(|| String::new()),
2829 unsafety_flag = unsafety_flag,
2830 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2831 title = [full_path(cx, myitem), myitem.type_().to_string()]
2833 .filter_map(|s| if !s.is_empty() {
2838 .collect::<Vec<_>>()
2845 if curty.is_some() {
2846 write!(w, "</table>")?;
2851 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2853 fn stability_tags(item: &clean::Item) -> String {
2854 let mut tags = String::new();
2856 fn tag_html(class: &str, contents: &str) -> String {
2857 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2860 // The trailing space after each tag is to space it properly against the rest of the docs.
2861 if item.deprecation().is_some() {
2862 let mut message = "Deprecated";
2863 if let Some(ref stab) = item.stability {
2864 if let Some(ref depr) = stab.deprecation {
2865 if let Some(ref since) = depr.since {
2866 if !stability::deprecation_in_effect(&since) {
2867 message = "Deprecation planned";
2872 tags += &tag_html("deprecated", message);
2875 if let Some(stab) = item
2878 .filter(|s| s.level == stability::Unstable)
2880 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2881 tags += &tag_html("internal", "Internal");
2883 tags += &tag_html("unstable", "Experimental");
2887 if let Some(ref cfg) = item.attrs.cfg {
2888 tags += &tag_html("portability", &cfg.render_short_html());
2894 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2896 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2897 let mut stability = vec![];
2898 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2900 if let Some(Deprecation { note, since }) = &item.deprecation() {
2901 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2902 // but only display the future-deprecation messages for #[rustc_deprecated].
2903 let mut message = if let Some(since) = since {
2904 format!("Deprecated since {}", Escape(since))
2906 String::from("Deprecated")
2908 if let Some(ref stab) = item.stability {
2909 if let Some(ref depr) = stab.deprecation {
2910 if let Some(ref since) = depr.since {
2911 if !stability::deprecation_in_effect(&since) {
2912 message = format!("Deprecating in {}", Escape(&since));
2918 if let Some(note) = note {
2919 let mut ids = cx.id_map.borrow_mut();
2920 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2921 message.push_str(&format!(": {}", html));
2923 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2926 if let Some(stab) = item
2929 .filter(|stab| stab.level == stability::Unstable)
2931 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2933 let mut message = if is_rustc_private {
2934 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2936 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2940 if let Some(feature) = stab.feature.as_ref() {
2941 let mut feature = format!("<code>{}</code>", Escape(&feature));
2942 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2943 feature.push_str(&format!(
2944 " <a href=\"{url}{issue}\">#{issue}</a>",
2950 message.push_str(&format!(" ({})", feature));
2953 if let Some(unstable_reason) = &stab.unstable_reason {
2954 // Provide a more informative message than the compiler help.
2955 let unstable_reason = if is_rustc_private {
2956 "This crate is being loaded from the sysroot, a permanently unstable location \
2957 for private compiler dependencies. It is not intended for general use. Prefer \
2958 using a public version of this crate from \
2959 [crates.io](https://crates.io) via [`Cargo.toml`]\
2960 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2965 let mut ids = cx.id_map.borrow_mut();
2967 "<details><summary>{}</summary>{}</details>",
2969 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2973 let class = if is_rustc_private {
2978 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2981 if let Some(ref cfg) = item.attrs.cfg {
2982 stability.push(format!(
2983 "<div class='stab portability'>{}</div>",
2984 cfg.render_long_html()
2991 fn item_constant(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
2992 c: &clean::Constant) -> fmt::Result {
2993 write!(w, "<pre class='rust const'>")?;
2994 render_attributes(w, it)?;
2995 write!(w, "{vis}const \
2996 {name}: {typ}</pre>",
2997 vis = VisSpace(&it.visibility),
2998 name = it.name.as_ref().unwrap(),
3003 fn item_static(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3004 s: &clean::Static) -> fmt::Result {
3005 write!(w, "<pre class='rust static'>")?;
3006 render_attributes(w, it)?;
3007 write!(w, "{vis}static {mutability}\
3008 {name}: {typ}</pre>",
3009 vis = VisSpace(&it.visibility),
3010 mutability = MutableSpace(s.mutability),
3011 name = it.name.as_ref().unwrap(),
3016 fn item_function(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3017 f: &clean::Function) -> fmt::Result {
3018 let header_len = format!(
3019 "{}{}{}{}{:#}fn {}{:#}",
3020 VisSpace(&it.visibility),
3021 ConstnessSpace(f.header.constness),
3022 UnsafetySpace(f.header.unsafety),
3023 AsyncSpace(f.header.asyncness),
3024 AbiSpace(f.header.abi),
3025 it.name.as_ref().unwrap(),
3028 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
3029 render_attributes(w, it)?;
3031 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
3032 {name}{generics}{decl}{where_clause}</pre>",
3033 vis = VisSpace(&it.visibility),
3034 constness = ConstnessSpace(f.header.constness),
3035 unsafety = UnsafetySpace(f.header.unsafety),
3036 asyncness = AsyncSpace(f.header.asyncness),
3037 abi = AbiSpace(f.header.abi),
3038 name = it.name.as_ref().unwrap(),
3039 generics = f.generics,
3040 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
3045 asyncness: f.header.asyncness,
3050 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter<'_>,
3051 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
3052 // If there's already another implementor that has the same abbridged name, use the
3053 // full path, for example in `std::iter::ExactSizeIterator`
3054 let use_absolute = match implementor.inner_impl().for_ {
3055 clean::ResolvedPath { ref path, is_generic: false, .. } |
3056 clean::BorrowedRef {
3057 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3059 } => implementor_dups[path.last_name()].1,
3062 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3063 implementor.impl_item.stable_since(), false, Some(use_absolute), false)?;
3067 fn render_impls(cx: &Context, w: &mut fmt::Formatter<'_>,
3069 containing_item: &clean::Item) -> fmt::Result {
3071 let did = i.trait_did().unwrap();
3072 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3073 render_impl(w, cx, i, assoc_link,
3074 RenderMode::Normal, containing_item.stable_since(), true, None, false)?;
3079 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3080 let mut bounds = String::new();
3081 if !t_bounds.is_empty() {
3083 bounds.push_str(": ");
3085 for (i, p) in t_bounds.iter().enumerate() {
3087 bounds.push_str(" + ");
3089 bounds.push_str(&(*p).to_string());
3095 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3096 let lhs = format!("{}", lhs.inner_impl());
3097 let rhs = format!("{}", rhs.inner_impl());
3099 // lhs and rhs are formatted as HTML, which may be unnecessary
3100 name_key(&lhs).cmp(&name_key(&rhs))
3104 w: &mut fmt::Formatter<'_>,
3109 let bounds = bounds(&t.bounds, false);
3110 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3111 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3112 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3113 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3115 // Output the trait definition
3116 wrap_into_docblock(w, |w| {
3117 write!(w, "<pre class='rust trait'>")?;
3118 render_attributes(w, it)?;
3119 write!(w, "{}{}{}trait {}{}{}",
3120 VisSpace(&it.visibility),
3121 UnsafetySpace(t.unsafety),
3122 if t.is_auto { "auto " } else { "" },
3123 it.name.as_ref().unwrap(),
3127 if !t.generics.where_predicates.is_empty() {
3128 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3133 if t.items.is_empty() {
3134 write!(w, "{{ }}")?;
3136 // FIXME: we should be using a derived_id for the Anchors here
3139 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3142 if !types.is_empty() && !consts.is_empty() {
3146 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3149 if !consts.is_empty() && !required.is_empty() {
3152 for (pos, m) in required.iter().enumerate() {
3153 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3156 if pos < required.len() - 1 {
3157 write!(w, "<div class='item-spacer'></div>")?;
3160 if !required.is_empty() && !provided.is_empty() {
3163 for (pos, m) in provided.iter().enumerate() {
3164 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3166 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3167 write!(w, ",\n {{ ... }}\n")?;
3170 write!(w, " {{ ... }}\n")?;
3173 if pos < provided.len() - 1 {
3174 write!(w, "<div class='item-spacer'></div>")?;
3182 // Trait documentation
3183 document(w, cx, it)?;
3185 fn write_small_section_header(
3186 w: &mut fmt::Formatter<'_>,
3189 extra_content: &str,
3192 <h2 id='{0}' class='small-section-header'>\
3193 {1}<a href='#{0}' class='anchor'></a>\
3194 </h2>{2}", id, title, extra_content)
3197 fn write_loading_content(w: &mut fmt::Formatter<'_>, extra_content: &str) -> fmt::Result {
3198 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3201 fn trait_item(w: &mut fmt::Formatter<'_>, cx: &Context, m: &clean::Item, t: &clean::Item)
3203 let name = m.name.as_ref().unwrap();
3204 let item_type = m.type_();
3205 let id = cx.derive_id(format!("{}.{}", item_type, name));
3206 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3207 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3208 extra = render_spotlight_traits(m)?,
3211 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3212 write!(w, "</code>")?;
3213 render_stability_since(w, m, t)?;
3214 write!(w, "</h3>")?;
3215 document(w, cx, m)?;
3219 if !types.is_empty() {
3220 write_small_section_header(w, "associated-types", "Associated Types",
3221 "<div class='methods'>")?;
3223 trait_item(w, cx, *t, it)?;
3225 write_loading_content(w, "</div>")?;
3228 if !consts.is_empty() {
3229 write_small_section_header(w, "associated-const", "Associated Constants",
3230 "<div class='methods'>")?;
3232 trait_item(w, cx, *t, it)?;
3234 write_loading_content(w, "</div>")?;
3237 // Output the documentation for each function individually
3238 if !required.is_empty() {
3239 write_small_section_header(w, "required-methods", "Required methods",
3240 "<div class='methods'>")?;
3241 for m in &required {
3242 trait_item(w, cx, *m, it)?;
3244 write_loading_content(w, "</div>")?;
3246 if !provided.is_empty() {
3247 write_small_section_header(w, "provided-methods", "Provided methods",
3248 "<div class='methods'>")?;
3249 for m in &provided {
3250 trait_item(w, cx, *m, it)?;
3252 write_loading_content(w, "</div>")?;
3255 // If there are methods directly on this trait object, render them here.
3256 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3258 let cache = cache();
3260 let mut synthetic_types = Vec::new();
3262 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3263 // The DefId is for the first Type found with that name. The bool is
3264 // if any Types with the same name but different DefId have been found.
3265 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3266 for implementor in implementors {
3267 match implementor.inner_impl().for_ {
3268 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3269 clean::BorrowedRef {
3270 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3273 let &mut (prev_did, ref mut has_duplicates) =
3274 implementor_dups.entry(path.last_name()).or_insert((did, false));
3275 if prev_did != did {
3276 *has_duplicates = true;
3283 let (local, foreign) = implementors.iter()
3284 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3285 .map_or(true, |d| cache.paths.contains_key(&d)));
3288 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3289 .partition(|i| i.inner_impl().synthetic);
3291 synthetic.sort_by(compare_impl);
3292 concrete.sort_by(compare_impl);
3294 if !foreign.is_empty() {
3295 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3297 for implementor in foreign {
3298 let assoc_link = AssocItemLink::GotoSource(
3299 implementor.impl_item.def_id,
3300 &implementor.inner_impl().provided_trait_methods
3302 render_impl(w, cx, &implementor, assoc_link,
3303 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3306 write_loading_content(w, "")?;
3309 write_small_section_header(w, "implementors", "Implementors",
3310 "<div class='item-list' id='implementors-list'>")?;
3311 for implementor in concrete {
3312 render_implementor(cx, implementor, w, &implementor_dups)?;
3314 write_loading_content(w, "</div>")?;
3317 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3318 "<div class='item-list' id='synthetic-implementors-list'>")?;
3319 for implementor in synthetic {
3320 synthetic_types.extend(
3321 collect_paths_for_type(implementor.inner_impl().for_.clone())
3323 render_implementor(cx, implementor, w, &implementor_dups)?;
3325 write_loading_content(w, "</div>")?;
3328 // even without any implementations to write in, we still want the heading and list, so the
3329 // implementors javascript file pulled in below has somewhere to write the impls into
3330 write_small_section_header(w, "implementors", "Implementors",
3331 "<div class='item-list' id='implementors-list'>")?;
3332 write_loading_content(w, "</div>")?;
3335 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3336 "<div class='item-list' id='synthetic-implementors-list'>")?;
3337 write_loading_content(w, "</div>")?;
3340 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3341 as_json(&synthetic_types))?;
3343 write!(w, r#"<script type="text/javascript" async
3344 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3346 root_path = vec![".."; cx.current.len()].join("/"),
3347 path = if it.def_id.is_local() {
3348 cx.current.join("/")
3350 let (ref path, _) = cache.external_paths[&it.def_id];
3351 path[..path.len() - 1].join("/")
3353 ty = it.type_().css_class(),
3354 name = *it.name.as_ref().unwrap())?;
3358 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
3359 use crate::html::item_type::ItemType::*;
3361 let name = it.name.as_ref().unwrap();
3362 let ty = match it.type_() {
3363 Typedef | AssociatedType => AssociatedType,
3367 let anchor = format!("#{}.{}", ty, name);
3369 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3370 AssocItemLink::Anchor(None) => anchor,
3371 AssocItemLink::GotoSource(did, _) => {
3372 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3377 fn assoc_const(w: &mut fmt::Formatter<'_>,
3380 _default: Option<&String>,
3381 link: AssocItemLink<'_>) -> fmt::Result {
3382 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3383 VisSpace(&it.visibility),
3384 naive_assoc_href(it, link),
3385 it.name.as_ref().unwrap(),
3390 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3391 bounds: &[clean::GenericBound],
3392 default: Option<&clean::Type>,
3393 link: AssocItemLink<'_>) -> fmt::Result {
3394 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3395 naive_assoc_href(it, link),
3396 it.name.as_ref().unwrap())?;
3397 if !bounds.is_empty() {
3398 write!(w, ": {}", GenericBounds(bounds))?
3400 if let Some(default) = default {
3401 write!(w, " = {}", default)?;
3406 fn render_stability_since_raw<'a, T: fmt::Write>(
3408 ver: Option<&'a str>,
3409 containing_ver: Option<&'a str>,
3411 if let Some(v) = ver {
3412 if containing_ver != ver && v.len() > 0 {
3413 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)?
3419 fn render_stability_since(w: &mut fmt::Formatter<'_>,
3421 containing_item: &clean::Item) -> fmt::Result {
3422 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3425 fn render_assoc_item(w: &mut fmt::Formatter<'_>,
3427 link: AssocItemLink<'_>,
3428 parent: ItemType) -> fmt::Result {
3429 fn method(w: &mut fmt::Formatter<'_>,
3431 header: hir::FnHeader,
3432 g: &clean::Generics,
3434 link: AssocItemLink<'_>,
3437 let name = meth.name.as_ref().unwrap();
3438 let anchor = format!("#{}.{}", meth.type_(), name);
3439 let href = match link {
3440 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3441 AssocItemLink::Anchor(None) => anchor,
3442 AssocItemLink::GotoSource(did, provided_methods) => {
3443 // We're creating a link from an impl-item to the corresponding
3444 // trait-item and need to map the anchored type accordingly.
3445 let ty = if provided_methods.contains(name) {
3451 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3454 let mut header_len = format!(
3455 "{}{}{}{}{}{:#}fn {}{:#}",
3456 VisSpace(&meth.visibility),
3457 ConstnessSpace(header.constness),
3458 UnsafetySpace(header.unsafety),
3459 AsyncSpace(header.asyncness),
3460 DefaultSpace(meth.is_default()),
3461 AbiSpace(header.abi),
3465 let (indent, end_newline) = if parent == ItemType::Trait {
3471 render_attributes(w, meth)?;
3472 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3473 {generics}{decl}{where_clause}",
3474 if parent == ItemType::Trait { " " } else { "" },
3475 VisSpace(&meth.visibility),
3476 ConstnessSpace(header.constness),
3477 UnsafetySpace(header.unsafety),
3478 AsyncSpace(header.asyncness),
3479 DefaultSpace(meth.is_default()),
3480 AbiSpace(header.abi),
3488 asyncness: header.asyncness,
3490 where_clause = WhereClause {
3497 clean::StrippedItem(..) => Ok(()),
3498 clean::TyMethodItem(ref m) => {
3499 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3501 clean::MethodItem(ref m) => {
3502 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3504 clean::AssociatedConstItem(ref ty, ref default) => {
3505 assoc_const(w, item, ty, default.as_ref(), link)
3507 clean::AssociatedTypeItem(ref bounds, ref default) => {
3508 assoc_type(w, item, bounds, default.as_ref(), link)
3510 _ => panic!("render_assoc_item called on non-associated-item")
3514 fn item_struct(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3515 s: &clean::Struct) -> fmt::Result {
3516 wrap_into_docblock(w, |w| {
3517 write!(w, "<pre class='rust struct'>")?;
3518 render_attributes(w, it)?;
3529 document(w, cx, it)?;
3530 let mut fields = s.fields.iter().filter_map(|f| {
3532 clean::StructFieldItem(ref ty) => Some((f, ty)),
3536 if let doctree::Plain = s.struct_type {
3537 if fields.peek().is_some() {
3538 write!(w, "<h2 id='fields' class='fields small-section-header'>
3539 Fields{}<a href='#fields' class='anchor'></a></h2>",
3540 document_non_exhaustive_header(it))?;
3541 document_non_exhaustive(w, it)?;
3542 for (field, ty) in fields {
3543 let id = cx.derive_id(format!("{}.{}",
3544 ItemType::StructField,
3545 field.name.as_ref().unwrap()));
3546 let ns_id = cx.derive_id(format!("{}.{}",
3547 field.name.as_ref().unwrap(),
3548 ItemType::StructField.name_space()));
3549 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3550 <a href=\"#{id}\" class=\"anchor field\"></a>\
3551 <code id=\"{ns_id}\">{name}: {ty}</code>\
3553 item_type = ItemType::StructField,
3556 name = field.name.as_ref().unwrap(),
3558 document(w, cx, field)?;
3562 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3565 fn item_union(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3566 s: &clean::Union) -> fmt::Result {
3567 wrap_into_docblock(w, |w| {
3568 write!(w, "<pre class='rust union'>")?;
3569 render_attributes(w, it)?;
3579 document(w, cx, it)?;
3580 let mut fields = s.fields.iter().filter_map(|f| {
3582 clean::StructFieldItem(ref ty) => Some((f, ty)),
3586 if fields.peek().is_some() {
3587 write!(w, "<h2 id='fields' class='fields small-section-header'>
3588 Fields<a href='#fields' class='anchor'></a></h2>")?;
3589 for (field, ty) in fields {
3590 let name = field.name.as_ref().expect("union field name");
3591 let id = format!("{}.{}", ItemType::StructField, name);
3592 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3593 <a href=\"#{id}\" class=\"anchor field\"></a>\
3594 <code>{name}: {ty}</code>\
3598 shortty = ItemType::StructField,
3600 if let Some(stability_class) = field.stability_class() {
3601 write!(w, "<span class='stab {stab}'></span>",
3602 stab = stability_class)?;
3604 document(w, cx, field)?;
3607 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3610 fn item_enum(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3611 e: &clean::Enum) -> fmt::Result {
3612 wrap_into_docblock(w, |w| {
3613 write!(w, "<pre class='rust enum'>")?;
3614 render_attributes(w, it)?;
3615 write!(w, "{}enum {}{}{}",
3616 VisSpace(&it.visibility),
3617 it.name.as_ref().unwrap(),
3619 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3620 if e.variants.is_empty() && !e.variants_stripped {
3621 write!(w, " {{}}")?;
3623 write!(w, " {{\n")?;
3624 for v in &e.variants {
3626 let name = v.name.as_ref().unwrap();
3628 clean::VariantItem(ref var) => {
3630 clean::VariantKind::CLike => write!(w, "{}", name)?,
3631 clean::VariantKind::Tuple(ref tys) => {
3632 write!(w, "{}(", name)?;
3633 for (i, ty) in tys.iter().enumerate() {
3635 write!(w, ", ")?
3637 write!(w, "{}", *ty)?;
3641 clean::VariantKind::Struct(ref s) => {
3657 if e.variants_stripped {
3658 write!(w, " // some variants omitted\n")?;
3665 document(w, cx, it)?;
3666 if !e.variants.is_empty() {
3667 write!(w, "<h2 id='variants' class='variants small-section-header'>
3668 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3669 document_non_exhaustive_header(it))?;
3670 document_non_exhaustive(w, it)?;
3671 for variant in &e.variants {
3672 let id = cx.derive_id(format!("{}.{}",
3674 variant.name.as_ref().unwrap()));
3675 let ns_id = cx.derive_id(format!("{}.{}",
3676 variant.name.as_ref().unwrap(),
3677 ItemType::Variant.name_space()));
3678 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3679 <a href=\"#{id}\" class=\"anchor field\"></a>\
3680 <code id='{ns_id}'>{name}",
3683 name = variant.name.as_ref().unwrap())?;
3684 if let clean::VariantItem(ref var) = variant.inner {
3685 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3687 for (i, ty) in tys.iter().enumerate() {
3689 write!(w, ", ")?;
3691 write!(w, "{}", *ty)?;
3696 write!(w, "</code></span>")?;
3697 document(w, cx, variant)?;
3698 document_non_exhaustive(w, variant)?;
3700 use crate::clean::{Variant, VariantKind};
3701 if let clean::VariantItem(Variant {
3702 kind: VariantKind::Struct(ref s)
3703 }) = variant.inner {
3704 let variant_id = cx.derive_id(format!("{}.{}.fields",
3706 variant.name.as_ref().unwrap()));
3707 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3709 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3710 name = variant.name.as_ref().unwrap())?;
3711 for field in &s.fields {
3712 use crate::clean::StructFieldItem;
3713 if let StructFieldItem(ref ty) = field.inner {
3714 let id = cx.derive_id(format!("variant.{}.field.{}",
3715 variant.name.as_ref().unwrap(),
3716 field.name.as_ref().unwrap()));
3717 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3718 variant.name.as_ref().unwrap(),
3719 ItemType::Variant.name_space(),
3720 field.name.as_ref().unwrap(),
3721 ItemType::StructField.name_space()));
3722 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3723 <a href=\"#{id}\" class=\"anchor field\"></a>\
3724 <code id='{ns_id}'>{f}: {t}\
3728 f = field.name.as_ref().unwrap(),
3730 document(w, cx, field)?;
3733 write!(w, "</div></span>")?;
3735 render_stability_since(w, variant, it)?;
3738 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3742 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3743 let path = attr.path.to_string();
3747 } else if let Some(v) = attr.value_str() {
3748 Some(format!("{} = {:?}", path, v.as_str()))
3749 } else if let Some(values) = attr.meta_item_list() {
3750 let display: Vec<_> = values.iter().filter_map(|attr| {
3751 attr.meta_item().and_then(|mi| render_attribute(mi))
3754 if display.len() > 0 {
3755 Some(format!("{}({})", path, display.join(", ")))
3764 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3771 "unsafe_destructor_blind_to_params",
3775 fn render_attributes(w: &mut dyn fmt::Write, it: &clean::Item) -> fmt::Result {
3776 let mut attrs = String::new();
3778 for attr in &it.attrs.other_attrs {
3779 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty().get()) {
3782 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3783 attrs.push_str(&format!("#[{}]\n", s));
3786 if attrs.len() > 0 {
3787 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3792 fn render_struct(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3793 g: Option<&clean::Generics>,
3794 ty: doctree::StructType,
3795 fields: &[clean::Item],
3797 structhead: bool) -> fmt::Result {
3799 VisSpace(&it.visibility),
3800 if structhead {"struct "} else {""},
3801 it.name.as_ref().unwrap())?;
3802 if let Some(g) = g {
3807 if let Some(g) = g {
3808 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3810 let mut has_visible_fields = false;
3812 for field in fields {
3813 if let clean::StructFieldItem(ref ty) = field.inner {
3814 write!(w, "\n{} {}{}: {},",
3816 VisSpace(&field.visibility),
3817 field.name.as_ref().unwrap(),
3819 has_visible_fields = true;
3823 if has_visible_fields {
3824 if it.has_stripped_fields().unwrap() {
3825 write!(w, "\n{} // some fields omitted", tab)?;
3827 write!(w, "\n{}", tab)?;
3828 } else if it.has_stripped_fields().unwrap() {
3829 // If there are no visible fields we can just display
3830 // `{ /* fields omitted */ }` to save space.
3831 write!(w, " /* fields omitted */ ")?;
3837 for (i, field) in fields.iter().enumerate() {
3842 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3845 clean::StructFieldItem(ref ty) => {
3846 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3852 if let Some(g) = g {
3853 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3858 // Needed for PhantomData.
3859 if let Some(g) = g {
3860 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3868 fn render_union(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3869 g: Option<&clean::Generics>,
3870 fields: &[clean::Item],
3872 structhead: bool) -> fmt::Result {
3874 VisSpace(&it.visibility),
3875 if structhead {"union "} else {""},
3876 it.name.as_ref().unwrap())?;
3877 if let Some(g) = g {
3878 write!(w, "{}", g)?;
3879 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3882 write!(w, " {{\n{}", tab)?;
3883 for field in fields {
3884 if let clean::StructFieldItem(ref ty) = field.inner {
3885 write!(w, " {}{}: {},\n{}",
3886 VisSpace(&field.visibility),
3887 field.name.as_ref().unwrap(),
3893 if it.has_stripped_fields().unwrap() {
3894 write!(w, " // some fields omitted\n{}", tab)?;
3900 #[derive(Copy, Clone)]
3901 enum AssocItemLink<'a> {
3902 Anchor(Option<&'a str>),
3903 GotoSource(DefId, &'a FxHashSet<String>),
3906 impl<'a> AssocItemLink<'a> {
3907 fn anchor(&self, id: &'a String) -> Self {
3909 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3910 ref other => *other,
3915 enum AssocItemRender<'a> {
3917 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3920 #[derive(Copy, Clone, PartialEq)]
3923 ForDeref { mut_: bool },
3926 fn render_assoc_items(w: &mut fmt::Formatter<'_>,
3928 containing_item: &clean::Item,
3930 what: AssocItemRender<'_>) -> fmt::Result {
3932 let v = match c.impls.get(&it) {
3934 None => return Ok(()),
3936 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3937 i.inner_impl().trait_.is_none()
3939 if !non_trait.is_empty() {
3940 let render_mode = match what {
3941 AssocItemRender::All => {
3943 <h2 id='methods' class='small-section-header'>\
3944 Methods<a href='#methods' class='anchor'></a>\
3949 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3951 <h2 id='deref-methods' class='small-section-header'>\
3952 Methods from {}<Target = {}>\
3953 <a href='#deref-methods' class='anchor'></a>\
3956 RenderMode::ForDeref { mut_: deref_mut_ }
3959 for i in &non_trait {
3960 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3961 containing_item.stable_since(), true, None, false)?;
3964 if let AssocItemRender::DerefFor { .. } = what {
3967 if !traits.is_empty() {
3968 let deref_impl = traits.iter().find(|t| {
3969 t.inner_impl().trait_.def_id() == c.deref_trait_did
3971 if let Some(impl_) = deref_impl {
3972 let has_deref_mut = traits.iter().find(|t| {
3973 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3975 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3978 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3980 .partition(|t| t.inner_impl().synthetic);
3981 let (blanket_impl, concrete) = concrete
3983 .partition(|t| t.inner_impl().blanket_impl.is_some());
3985 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3987 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3988 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3989 render_impls(self.0, fmt, &self.1, self.2)
3993 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3994 if !impls.is_empty() {
3996 <h2 id='implementations' class='small-section-header'>\
3997 Trait Implementations<a href='#implementations' class='anchor'></a>\
3999 <div id='implementations-list'>{}</div>", impls)?;
4002 if !synthetic.is_empty() {
4004 <h2 id='synthetic-implementations' class='small-section-header'>\
4005 Auto Trait Implementations\
4006 <a href='#synthetic-implementations' class='anchor'></a>\
4008 <div id='synthetic-implementations-list'>\
4010 render_impls(cx, w, &synthetic, containing_item)?;
4011 write!(w, "</div>")?;
4014 if !blanket_impl.is_empty() {
4016 <h2 id='blanket-implementations' class='small-section-header'>\
4017 Blanket Implementations\
4018 <a href='#blanket-implementations' class='anchor'></a>\
4020 <div id='blanket-implementations-list'>\
4022 render_impls(cx, w, &blanket_impl, containing_item)?;
4023 write!(w, "</div>")?;
4029 fn render_deref_methods(w: &mut fmt::Formatter<'_>, cx: &Context, impl_: &Impl,
4030 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
4031 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
4032 let target = impl_.inner_impl().items.iter().filter_map(|item| {
4034 clean::TypedefItem(ref t, true) => Some(&t.type_),
4037 }).next().expect("Expected associated type binding");
4038 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
4039 deref_mut_: deref_mut };
4040 if let Some(did) = target.def_id() {
4041 render_assoc_items(w, cx, container_item, did, what)
4043 if let Some(prim) = target.primitive_type() {
4044 if let Some(&did) = cache().primitive_locations.get(&prim) {
4045 render_assoc_items(w, cx, container_item, did, what)?;
4052 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
4053 let self_type_opt = match item.inner {
4054 clean::MethodItem(ref method) => method.decl.self_type(),
4055 clean::TyMethodItem(ref method) => method.decl.self_type(),
4059 if let Some(self_ty) = self_type_opt {
4060 let (by_mut_ref, by_box, by_value) = match self_ty {
4061 SelfTy::SelfBorrowed(_, mutability) |
4062 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4063 (mutability == Mutability::Mutable, false, false)
4065 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4066 (false, Some(did) == cache().owned_box_did, false)
4068 SelfTy::SelfValue => (false, false, true),
4069 _ => (false, false, false),
4072 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4078 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4079 let mut out = String::new();
4082 clean::FunctionItem(clean::Function { ref decl, .. }) |
4083 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4084 clean::MethodItem(clean::Method { ref decl, .. }) |
4085 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4086 out = spotlight_decl(decl)?;
4094 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4095 let mut out = String::new();
4096 let mut trait_ = String::new();
4098 if let Some(did) = decl.output.def_id() {
4100 if let Some(impls) = c.impls.get(&did) {
4102 let impl_ = i.inner_impl();
4103 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4106 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4107 <code class=\"content\">",
4109 trait_.push_str(&impl_.for_.to_string());
4112 //use the "where" class here to make it small
4113 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4114 let t_did = impl_.trait_.def_id().unwrap();
4115 for it in &impl_.items {
4116 if let clean::TypedefItem(ref tydef, _) = it.inner {
4117 out.push_str("<span class=\"where fmt-newline\"> ");
4118 assoc_type(&mut out, it, &[],
4120 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4121 out.push_str(";</span>");
4129 if !out.is_empty() {
4130 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4131 <span class='tooltiptext'>Important traits for {}</span></div>\
4132 <div class=\"content hidden\">",
4134 out.push_str("</code></div></div>");
4140 fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
4141 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
4142 use_absolute: Option<bool>, is_on_foreign_type: bool) -> fmt::Result {
4143 if render_mode == RenderMode::Normal {
4144 let id = cx.derive_id(match i.inner_impl().trait_ {
4145 Some(ref t) => if is_on_foreign_type {
4146 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
4148 format!("impl-{}", small_url_encode(&format!("{:#}", t)))
4150 None => "impl".to_string(),
4152 if let Some(use_absolute) = use_absolute {
4153 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4154 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4156 for it in &i.inner_impl().items {
4157 if let clean::TypedefItem(ref tydef, _) = it.inner {
4158 write!(w, "<span class=\"where fmt-newline\"> ")?;
4159 assoc_type(w, it, &vec![], Some(&tydef.type_),
4160 AssocItemLink::Anchor(None))?;
4161 write!(w, ";</span>")?;
4165 write!(w, "</code>")?;
4167 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4171 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4172 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4173 render_stability_since_raw(w, since, outer_version)?;
4174 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4175 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4176 l, "goto source code")?;
4178 write!(w, "</h3>")?;
4179 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4180 let mut ids = cx.id_map.borrow_mut();
4181 write!(w, "<div class='docblock'>{}</div>",
4182 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4186 fn doc_impl_item(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
4187 link: AssocItemLink<'_>, render_mode: RenderMode,
4188 is_default_item: bool, outer_version: Option<&str>,
4189 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4190 let item_type = item.type_();
4191 let name = item.name.as_ref().unwrap();
4193 let render_method_item: bool = match render_mode {
4194 RenderMode::Normal => true,
4195 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4198 let (is_hidden, extra_class) = if trait_.is_none() ||
4199 item.doc_value().is_some() ||
4200 item.inner.is_associated() {
4206 clean::MethodItem(clean::Method { ref decl, .. }) |
4207 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4208 // Only render when the method is not static or we allow static methods
4209 if render_method_item {
4210 let id = cx.derive_id(format!("{}.{}", item_type, name));
4211 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4212 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4213 write!(w, "{}", spotlight_decl(decl)?)?;
4214 write!(w, "<code id='{}'>", ns_id)?;
4215 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4216 write!(w, "</code>")?;
4217 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4218 if let Some(l) = (Item { cx, item }).src_href() {
4219 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4220 l, "goto source code")?;
4222 write!(w, "</h4>")?;
4225 clean::TypedefItem(ref tydef, _) => {
4226 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4227 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4228 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4229 write!(w, "<code id='{}'>", ns_id)?;
4230 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4231 write!(w, "</code></h4>")?;
4233 clean::AssociatedConstItem(ref ty, ref default) => {
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, "<code id='{}'>", ns_id)?;
4238 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4239 write!(w, "</code>")?;
4240 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4241 if let Some(l) = (Item { cx, item }).src_href() {
4242 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4243 l, "goto source code")?;
4245 write!(w, "</h4>")?;
4247 clean::AssociatedTypeItem(ref bounds, ref default) => {
4248 let id = cx.derive_id(format!("{}.{}", item_type, name));
4249 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4250 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4251 write!(w, "<code id='{}'>", ns_id)?;
4252 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4253 write!(w, "</code></h4>")?;
4255 clean::StrippedItem(..) => return Ok(()),
4256 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4259 if render_method_item || render_mode == RenderMode::Normal {
4260 if !is_default_item {
4261 if let Some(t) = trait_ {
4262 // The trait item may have been stripped so we might not
4263 // find any documentation or stability for it.
4264 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4265 // We need the stability of the item from the trait
4266 // because impls can't have a stability.
4267 document_stability(w, cx, it, is_hidden)?;
4268 if item.doc_value().is_some() {
4269 document_full(w, item, cx, "", is_hidden)?;
4270 } else if show_def_docs {
4271 // In case the item isn't documented,
4272 // provide short documentation from the trait.
4273 document_short(w, cx, it, link, "", is_hidden)?;
4277 document_stability(w, cx, item, is_hidden)?;
4279 document_full(w, item, cx, "", is_hidden)?;
4283 document_stability(w, cx, item, is_hidden)?;
4285 document_short(w, cx, item, link, "", is_hidden)?;
4292 let traits = &cache().traits;
4293 let trait_ = i.trait_did().map(|did| &traits[&did]);
4295 write!(w, "<div class='impl-items'>")?;
4296 for trait_item in &i.inner_impl().items {
4297 doc_impl_item(w, cx, trait_item, link, render_mode,
4298 false, outer_version, trait_, show_def_docs)?;
4301 fn render_default_items(w: &mut fmt::Formatter<'_>,
4305 render_mode: RenderMode,
4306 outer_version: Option<&str>,
4307 show_def_docs: bool) -> fmt::Result {
4308 for trait_item in &t.items {
4309 let n = trait_item.name.clone();
4310 if i.items.iter().find(|m| m.name == n).is_some() {
4313 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4314 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4316 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4317 outer_version, None, show_def_docs)?;
4322 // If we've implemented a trait, then also emit documentation for all
4323 // default items which weren't overridden in the implementation block.
4324 if let Some(t) = trait_ {
4325 render_default_items(w, cx, t, &i.inner_impl(),
4326 render_mode, outer_version, show_def_docs)?;
4328 write!(w, "</div>")?;
4333 fn item_existential(
4334 w: &mut fmt::Formatter<'_>,
4337 t: &clean::Existential,
4339 write!(w, "<pre class='rust existential'>")?;
4340 render_attributes(w, it)?;
4341 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4342 it.name.as_ref().unwrap(),
4344 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4345 bounds = bounds(&t.bounds, false))?;
4347 document(w, cx, it)?;
4349 // Render any items associated directly to this alias, as otherwise they
4350 // won't be visible anywhere in the docs. It would be nice to also show
4351 // associated items from the aliased type (see discussion in #32077), but
4352 // we need #14072 to make sense of the generics.
4353 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4356 fn item_trait_alias(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4357 t: &clean::TraitAlias) -> fmt::Result {
4358 write!(w, "<pre class='rust trait-alias'>")?;
4359 render_attributes(w, it)?;
4360 write!(w, "trait {}{}{} = {};</pre>",
4361 it.name.as_ref().unwrap(),
4363 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4364 bounds(&t.bounds, true))?;
4366 document(w, cx, it)?;
4368 // Render any items associated directly to this alias, as otherwise they
4369 // won't be visible anywhere in the docs. It would be nice to also show
4370 // associated items from the aliased type (see discussion in #32077), but
4371 // we need #14072 to make sense of the generics.
4372 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4375 fn item_typedef(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4376 t: &clean::Typedef) -> fmt::Result {
4377 write!(w, "<pre class='rust typedef'>")?;
4378 render_attributes(w, it)?;
4379 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4380 it.name.as_ref().unwrap(),
4382 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4385 document(w, cx, it)?;
4387 // Render any items associated directly to this alias, as otherwise they
4388 // won't be visible anywhere in the docs. It would be nice to also show
4389 // associated items from the aliased type (see discussion in #32077), but
4390 // we need #14072 to make sense of the generics.
4391 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4394 fn item_foreign_type(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item) -> fmt::Result {
4395 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4396 render_attributes(w, it)?;
4399 " {}type {};\n}}</pre>",
4400 VisSpace(&it.visibility),
4401 it.name.as_ref().unwrap(),
4404 document(w, cx, it)?;
4406 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4409 impl<'a> fmt::Display for Sidebar<'a> {
4410 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4413 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4415 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4416 || it.is_enum() || it.is_mod() || it.is_typedef() {
4417 write!(fmt, "<p class='location'>{}{}</p>",
4419 clean::StructItem(..) => "Struct ",
4420 clean::TraitItem(..) => "Trait ",
4421 clean::PrimitiveItem(..) => "Primitive Type ",
4422 clean::UnionItem(..) => "Union ",
4423 clean::EnumItem(..) => "Enum ",
4424 clean::TypedefItem(..) => "Type Definition ",
4425 clean::ForeignTypeItem => "Foreign Type ",
4426 clean::ModuleItem(..) => if it.is_crate() {
4433 it.name.as_ref().unwrap())?;
4437 if let Some(ref version) = cache().crate_version {
4439 "<div class='block version'>\
4446 write!(fmt, "<div class=\"sidebar-elems\">")?;
4448 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4449 it.name.as_ref().expect("crates always have a name"))?;
4452 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4453 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4454 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4455 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4456 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4457 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4458 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4459 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4463 // The sidebar is designed to display sibling functions, modules and
4464 // other miscellaneous information. since there are lots of sibling
4465 // items (and that causes quadratic growth in large modules),
4466 // we refactor common parts into a shared JavaScript file per module.
4467 // still, we don't move everything into JS because we want to preserve
4468 // as much HTML as possible in order to allow non-JS-enabled browsers
4469 // to navigate the documentation (though slightly inefficiently).
4471 write!(fmt, "<p class='location'>")?;
4472 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4474 write!(fmt, "::<wbr>")?;
4476 write!(fmt, "<a href='{}index.html'>{}</a>",
4477 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4480 write!(fmt, "</p>")?;
4482 // Sidebar refers to the enclosing module, not this module.
4483 let relpath = if it.is_mod() { "../" } else { "" };
4485 "<script>window.sidebarCurrent = {{\
4490 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4491 ty = it.type_().css_class(),
4494 // There is no sidebar-items.js beyond the crate root path
4495 // FIXME maybe dynamic crate loading can be merged here
4497 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4500 // Closes sidebar-elems div.
4501 write!(fmt, "</div>")?;
4507 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4508 if used_links.insert(url.clone()) {
4512 while used_links.insert(format!("{}-{}", url, add)) == false {
4515 format!("{}-{}", url, add)
4521 used_links: &mut FxHashSet<String>,
4523 i.items.iter().filter_map(|item| {
4525 // Maybe check with clean::Visibility::Public as well?
4526 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4527 if !for_deref || should_render_item(item, false) {
4528 Some(format!("<a href=\"#{}\">{}</a>",
4529 get_next_url(used_links, format!("method.{}", name)),
4537 }).collect::<Vec<_>>()
4540 // The point is to url encode any potential character from a type with genericity.
4541 fn small_url_encode(s: &str) -> String {
4542 s.replace("<", "%3C")
4543 .replace(">", "%3E")
4544 .replace(" ", "%20")
4545 .replace("?", "%3F")
4546 .replace("'", "%27")
4547 .replace("&", "%26")
4548 .replace(",", "%2C")
4549 .replace(":", "%3A")
4550 .replace(";", "%3B")
4551 .replace("[", "%5B")
4552 .replace("]", "%5D")
4553 .replace("\"", "%22")
4556 fn sidebar_assoc_items(it: &clean::Item) -> String {
4557 let mut out = String::new();
4559 if let Some(v) = c.impls.get(&it.def_id) {
4560 let mut used_links = FxHashSet::default();
4563 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4564 let mut ret = v.iter()
4565 .filter(|i| i.inner_impl().trait_.is_none())
4566 .flat_map(move |i| get_methods(i.inner_impl(),
4568 &mut used_links_bor.borrow_mut()))
4569 .collect::<Vec<_>>();
4570 // We want links' order to be reproducible so we don't use unstable sort.
4572 if !ret.is_empty() {
4573 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4574 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4578 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4579 if let Some(impl_) = v.iter()
4580 .filter(|i| i.inner_impl().trait_.is_some())
4581 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4582 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4584 clean::TypedefItem(ref t, true) => Some(&t.type_),
4588 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4589 c.primitive_locations.get(&prim).cloned()
4590 })).and_then(|did| c.impls.get(&did));
4591 if let Some(impls) = inner_impl {
4592 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4593 out.push_str(&format!("Methods from {}<Target={}>",
4594 Escape(&format!("{:#}",
4595 impl_.inner_impl().trait_.as_ref().unwrap())),
4596 Escape(&format!("{:#}", target))));
4597 out.push_str("</a>");
4598 let mut ret = impls.iter()
4599 .filter(|i| i.inner_impl().trait_.is_none())
4600 .flat_map(|i| get_methods(i.inner_impl(),
4603 .collect::<Vec<_>>();
4604 // We want links' order to be reproducible so we don't use unstable sort.
4606 if !ret.is_empty() {
4607 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4613 let format_impls = |impls: Vec<&Impl>| {
4614 let mut links = FxHashSet::default();
4616 let mut ret = impls.iter()
4618 let is_negative_impl = is_negative_impl(i.inner_impl());
4619 if let Some(ref i) = i.inner_impl().trait_ {
4620 let i_display = format!("{:#}", i);
4621 let out = Escape(&i_display);
4622 let encoded = small_url_encode(&format!("{:#}", i));
4623 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4625 if is_negative_impl { "!" } else { "" },
4627 if links.insert(generated.clone()) {
4636 .collect::<Vec<String>>();
4641 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4643 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4644 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4646 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4648 let concrete_format = format_impls(concrete);
4649 let synthetic_format = format_impls(synthetic);
4650 let blanket_format = format_impls(blanket_impl);
4652 if !concrete_format.is_empty() {
4653 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4654 Trait Implementations</a>");
4655 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4658 if !synthetic_format.is_empty() {
4659 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4660 Auto Trait Implementations</a>");
4661 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4664 if !blanket_format.is_empty() {
4665 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4666 Blanket Implementations</a>");
4667 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4675 fn sidebar_struct(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4676 s: &clean::Struct) -> fmt::Result {
4677 let mut sidebar = String::new();
4678 let fields = get_struct_fields_name(&s.fields);
4680 if !fields.is_empty() {
4681 if let doctree::Plain = s.struct_type {
4682 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4683 <div class=\"sidebar-links\">{}</div>", fields));
4687 sidebar.push_str(&sidebar_assoc_items(it));
4689 if !sidebar.is_empty() {
4690 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4695 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4696 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_, for_))
4699 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4701 clean::ItemEnum::ImplItem(ref i) => {
4702 if let Some(ref trait_) = i.trait_ {
4703 Some((format!("{:#}", i.for_), get_id_for_impl_on_foreign_type(&i.for_, trait_)))
4712 fn is_negative_impl(i: &clean::Impl) -> bool {
4713 i.polarity == Some(clean::ImplPolarity::Negative)
4716 fn sidebar_trait(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4717 t: &clean::Trait) -> fmt::Result {
4718 let mut sidebar = String::new();
4724 Some(ref name) if m.is_associated_type() => {
4725 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4731 .collect::<String>();
4732 let consts = t.items
4736 Some(ref name) if m.is_associated_const() => {
4737 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4743 .collect::<String>();
4744 let mut required = t.items
4748 Some(ref name) if m.is_ty_method() => {
4749 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4755 .collect::<Vec<String>>();
4756 let mut provided = t.items
4760 Some(ref name) if m.is_method() => {
4761 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4766 .collect::<Vec<String>>();
4768 if !types.is_empty() {
4769 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4770 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4773 if !consts.is_empty() {
4774 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4775 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4778 if !required.is_empty() {
4780 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4781 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4782 required.join("")));
4784 if !provided.is_empty() {
4786 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4787 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4788 provided.join("")));
4793 if let Some(implementors) = c.implementors.get(&it.def_id) {
4794 let mut res = implementors.iter()
4795 .filter(|i| i.inner_impl().for_.def_id()
4796 .map_or(false, |d| !c.paths.contains_key(&d)))
4798 match extract_for_impl_name(&i.impl_item) {
4799 Some((ref name, ref id)) => {
4800 Some(format!("<a href=\"#{}\">{}</a>",
4807 .collect::<Vec<String>>();
4808 if !res.is_empty() {
4810 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4811 Implementations on Foreign Types</a><div \
4812 class=\"sidebar-links\">{}</div>",
4817 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4819 sidebar.push_str("<a class=\"sidebar-title\" \
4820 href=\"#synthetic-implementors\">Auto Implementors</a>");
4823 sidebar.push_str(&sidebar_assoc_items(it));
4825 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4828 fn sidebar_primitive(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4829 _p: &clean::PrimitiveType) -> fmt::Result {
4830 let sidebar = sidebar_assoc_items(it);
4832 if !sidebar.is_empty() {
4833 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4838 fn sidebar_typedef(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4839 _t: &clean::Typedef) -> fmt::Result {
4840 let sidebar = sidebar_assoc_items(it);
4842 if !sidebar.is_empty() {
4843 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4848 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4850 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4855 .filter_map(|f| match f.name {
4856 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4857 {name}</a>", name=name)),
4863 fn sidebar_union(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4864 u: &clean::Union) -> fmt::Result {
4865 let mut sidebar = String::new();
4866 let fields = get_struct_fields_name(&u.fields);
4868 if !fields.is_empty() {
4869 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4870 <div class=\"sidebar-links\">{}</div>", fields));
4873 sidebar.push_str(&sidebar_assoc_items(it));
4875 if !sidebar.is_empty() {
4876 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4881 fn sidebar_enum(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4882 e: &clean::Enum) -> fmt::Result {
4883 let mut sidebar = String::new();
4885 let variants = e.variants.iter()
4886 .filter_map(|v| match v.name {
4887 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4888 </a>", name = name)),
4891 .collect::<String>();
4892 if !variants.is_empty() {
4893 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4894 <div class=\"sidebar-links\">{}</div>", variants));
4897 sidebar.push_str(&sidebar_assoc_items(it));
4899 if !sidebar.is_empty() {
4900 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4905 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4907 ItemType::ExternCrate |
4908 ItemType::Import => ("reexports", "Re-exports"),
4909 ItemType::Module => ("modules", "Modules"),
4910 ItemType::Struct => ("structs", "Structs"),
4911 ItemType::Union => ("unions", "Unions"),
4912 ItemType::Enum => ("enums", "Enums"),
4913 ItemType::Function => ("functions", "Functions"),
4914 ItemType::Typedef => ("types", "Type Definitions"),
4915 ItemType::Static => ("statics", "Statics"),
4916 ItemType::Constant => ("constants", "Constants"),
4917 ItemType::Trait => ("traits", "Traits"),
4918 ItemType::Impl => ("impls", "Implementations"),
4919 ItemType::TyMethod => ("tymethods", "Type Methods"),
4920 ItemType::Method => ("methods", "Methods"),
4921 ItemType::StructField => ("fields", "Struct Fields"),
4922 ItemType::Variant => ("variants", "Variants"),
4923 ItemType::Macro => ("macros", "Macros"),
4924 ItemType::Primitive => ("primitives", "Primitive Types"),
4925 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4926 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4927 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4928 ItemType::Keyword => ("keywords", "Keywords"),
4929 ItemType::Existential => ("existentials", "Existentials"),
4930 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4931 ItemType::ProcDerive => ("derives", "Derive Macros"),
4932 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4936 fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item,
4937 items: &[clean::Item]) -> fmt::Result {
4938 let mut sidebar = String::new();
4940 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4941 it.type_() == ItemType::Import) {
4942 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4944 name = "Re-exports"));
4947 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4948 // to print its headings
4949 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4950 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4951 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4952 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4953 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4954 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4955 let (short, name) = item_ty_to_strs(&myty);
4956 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4962 if !sidebar.is_empty() {
4963 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4968 fn sidebar_foreign_type(fmt: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
4969 let sidebar = sidebar_assoc_items(it);
4970 if !sidebar.is_empty() {
4971 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4976 impl<'a> fmt::Display for Source<'a> {
4977 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4978 let Source(s) = *self;
4979 let lines = s.lines().count();
4981 let mut tmp = lines;
4986 write!(fmt, "<pre class=\"line-numbers\">")?;
4987 for i in 1..=lines {
4988 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4990 write!(fmt, "</pre>")?;
4992 highlight::render_with_highlighting(s, None, None, None))?;
4997 fn item_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4998 t: &clean::Macro) -> fmt::Result {
4999 wrap_into_docblock(w, |w| {
5000 w.write_str(&highlight::render_with_highlighting(&t.source,
5008 fn item_proc_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
5011 let name = it.name.as_ref().expect("proc-macros always have names");
5013 MacroKind::Bang => {
5014 write!(w, "<pre class='rust macro'>")?;
5015 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
5016 write!(w, "</pre>")?;
5018 MacroKind::Attr => {
5019 write!(w, "<pre class='rust attr'>")?;
5020 write!(w, "#[{}]", name)?;
5021 write!(w, "</pre>")?;
5023 MacroKind::Derive => {
5024 write!(w, "<pre class='rust derive'>")?;
5025 write!(w, "#[derive({})]", name)?;
5026 if !m.helpers.is_empty() {
5027 writeln!(w, "\n{{")?;
5028 writeln!(w, " // Attributes available to this derive:")?;
5029 for attr in &m.helpers {
5030 writeln!(w, " #[{}]", attr)?;
5034 write!(w, "</pre>")?;
5041 fn item_primitive(w: &mut fmt::Formatter<'_>, cx: &Context,
5043 _p: &clean::PrimitiveType) -> fmt::Result {
5044 document(w, cx, it)?;
5045 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
5048 fn item_keyword(w: &mut fmt::Formatter<'_>, cx: &Context,
5050 _p: &str) -> fmt::Result {
5054 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
5056 fn make_item_keywords(it: &clean::Item) -> String {
5057 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
5060 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
5061 let (all_types, ret_types) = match item.inner {
5062 clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
5063 clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
5064 clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
5068 let inputs = all_types.iter().map(|arg| {
5069 get_index_type(&arg)
5070 }).filter(|a| a.name.is_some()).collect();
5071 let output = ret_types.iter().map(|arg| {
5072 get_index_type(&arg)
5073 }).filter(|a| a.name.is_some()).collect::<Vec<_>>();
5074 let output = if output.is_empty() {
5080 Some(IndexItemFunctionType { inputs, output })
5083 fn get_index_type(clean_type: &clean::Type) -> Type {
5085 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5086 generics: get_generics(clean_type),
5091 /// Returns a list of all paths used in the type.
5092 /// This is used to help deduplicate imported impls
5093 /// for reexported types. If any of the contained
5094 /// types are re-exported, we don't use the corresponding
5095 /// entry from the js file, as inlining will have already
5096 /// picked up the impl
5097 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5098 let mut out = Vec::new();
5099 let mut visited = FxHashSet::default();
5100 let mut work = VecDeque::new();
5101 let cache = cache();
5103 work.push_back(first_ty);
5105 while let Some(ty) = work.pop_front() {
5106 if !visited.insert(ty.clone()) {
5111 clean::Type::ResolvedPath { did, .. } => {
5112 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5113 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5117 out.push(path.join("::"));
5123 clean::Type::Tuple(tys) => {
5124 work.extend(tys.into_iter());
5126 clean::Type::Slice(ty) => {
5127 work.push_back(*ty);
5129 clean::Type::Array(ty, _) => {
5130 work.push_back(*ty);
5132 clean::Type::Unique(ty) => {
5133 work.push_back(*ty);
5135 clean::Type::RawPointer(_, ty) => {
5136 work.push_back(*ty);
5138 clean::Type::BorrowedRef { type_, .. } => {
5139 work.push_back(*type_);
5141 clean::Type::QPath { self_type, trait_, .. } => {
5142 work.push_back(*self_type);
5143 work.push_back(*trait_);
5151 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5153 clean::ResolvedPath { ref path, .. } => {
5154 let segments = &path.segments;
5155 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5156 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5157 clean_type, accept_generic
5159 Some(path_segment.name.clone())
5161 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5162 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5163 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5164 // FIXME: add all from clean::Type.
5169 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5170 clean_type.generics()
5172 let r = types.iter()
5173 .filter_map(|t| get_index_type_name(t, false))
5174 .map(|s| s.to_ascii_lowercase())
5175 .collect::<Vec<_>>();
5184 pub fn cache() -> Arc<Cache> {
5185 CACHE_KEY.with(|c| c.borrow().clone())
5190 fn test_name_key() {
5191 assert_eq!(name_key("0"), ("", 0, 1));
5192 assert_eq!(name_key("123"), ("", 123, 0));
5193 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5194 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5195 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5196 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5197 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5198 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5203 fn test_name_sorting() {
5204 let names = ["Apple",
5206 "Fruit", "Fruit0", "Fruit00",
5207 "Fruit1", "Fruit01",
5208 "Fruit2", "Fruit02",
5213 let mut sorted = names.to_owned();
5214 sorted.sort_by_key(|&s| name_key(s));
5215 assert_eq!(names, sorted);