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};
39 use std::io::prelude::*;
40 use std::io::{self, BufReader};
42 use std::path::{PathBuf, Path, Component};
48 use serialize::json::{ToJson, Json, as_json};
50 use syntax::edition::Edition;
51 use syntax::ext::base::MacroKind;
52 use syntax::source_map::FileName;
53 use syntax::feature_gate::UnstableFeatures;
54 use syntax::symbol::{Symbol, sym};
55 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
56 use rustc::middle::privacy::AccessLevels;
57 use rustc::middle::stability;
59 use rustc::util::nodemap::{FxHashMap, FxHashSet};
60 use rustc_data_structures::flock;
62 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
63 use crate::config::RenderOptions;
64 use crate::docfs::{DocFS, ErrorStorage, PathError};
66 use crate::fold::DocFolder;
67 use crate::html::escape::Escape;
68 use crate::html::format::{AsyncSpace, ConstnessSpace};
69 use crate::html::format::{GenericBounds, WhereClause, href, AbiSpace, DefaultSpace};
70 use crate::html::format::{VisSpace, Function, UnsafetySpace, MutableSpace};
71 use crate::html::format::fmt_impl_for_trait_page;
72 use crate::html::item_type::ItemType;
73 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
74 use crate::html::{highlight, layout, static_files};
78 /// A pair of name and its optional document.
79 pub type NameDoc = (String, Option<String>);
81 pub struct SlashChecker<'a>(pub &'a str);
83 impl<'a> Display for SlashChecker<'a> {
84 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
85 if !self.0.ends_with("/") && !self.0.is_empty() {
86 write!(f, "{}/", self.0)
88 write!(f, "{}", self.0)
99 impl error::Error for Error {
100 fn description(&self) -> &str {
101 self.error.description()
105 impl Display for Error {
106 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
107 let file = self.file.display().to_string();
109 write!(f, "{}", self.error)
111 write!(f, "\"{}\": {}", self.file.display(), self.error)
116 impl PathError for Error {
117 fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error {
119 file: path.as_ref().to_path_buf(),
125 macro_rules! try_none {
126 ($e:expr, $file:expr) => ({
130 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
136 macro_rules! try_err {
137 ($e:expr, $file:expr) => ({
140 Err(e) => return Err(Error::new(e, $file)),
145 /// Major driving force in all rustdoc rendering. This contains information
146 /// about where in the tree-like hierarchy rendering is occurring and controls
147 /// how the current page is being rendered.
149 /// It is intended that this context is a lightweight object which can be fairly
150 /// easily cloned because it is cloned per work-job (about once per item in the
154 /// Current hierarchy of components leading down to what's currently being
156 pub current: Vec<String>,
157 /// The current destination folder of where HTML artifacts should be placed.
158 /// This changes as the context descends into the module hierarchy.
160 /// A flag, which when `true`, will render pages which redirect to the
161 /// real location of an item. This is used to allow external links to
162 /// publicly reused items to redirect to the right location.
163 pub render_redirect_pages: bool,
164 pub codes: ErrorCodes,
165 /// The default edition used to parse doctests.
166 pub edition: Edition,
167 /// The map used to ensure all generated 'id=' attributes are unique.
168 id_map: Rc<RefCell<IdMap>>,
169 pub shared: Arc<SharedContext>,
172 struct SharedContext {
173 /// The path to the crate root source minus the file name.
174 /// Used for simplifying paths to the highlighted source code files.
175 pub src_root: PathBuf,
176 /// This describes the layout of each page, and is not modified after
177 /// creation of the context (contains info like the favicon and added html).
178 pub layout: layout::Layout,
179 /// This flag indicates whether `[src]` links should be generated or not. If
180 /// the source files are present in the html rendering, then this will be
182 pub include_sources: bool,
183 /// The local file sources we've emitted and their respective url-paths.
184 pub local_sources: FxHashMap<PathBuf, String>,
185 /// All the passes that were run on this crate.
186 pub passes: FxHashSet<String>,
187 /// The base-URL of the issue tracker for when an item has been tagged with
189 pub issue_tracker_base_url: Option<String>,
190 /// The given user css file which allow to customize the generated
191 /// documentation theme.
192 pub css_file_extension: Option<PathBuf>,
193 /// The directories that have already been created in this doc run. Used to reduce the number
194 /// of spurious `create_dir_all` calls.
195 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
196 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
197 /// should be ordered alphabetically or in order of appearance (in the source code).
198 pub sort_modules_alphabetically: bool,
199 /// Additional themes to be added to the generated docs.
200 pub themes: Vec<PathBuf>,
201 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
203 pub resource_suffix: String,
204 /// Optional path string to be used to load static files on output pages. If not set, uses
205 /// combinations of `../` to reach the documentation root.
206 pub static_root_path: Option<String>,
207 /// If false, the `select` element to have search filtering by crates on rendered docs
208 /// won't be generated.
209 pub generate_search_filter: bool,
210 /// Option disabled by default to generate files used by RLS and some other tools.
211 pub generate_redirect_pages: bool,
212 /// The fs handle we are working with.
217 fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
218 let mut dirs = self.created_dirs.borrow_mut();
219 if !dirs.contains(dst) {
220 try_err!(self.fs.create_dir_all(dst), dst);
221 dirs.insert(dst.to_path_buf());
229 /// Returns `true` if the `collapse-docs` pass was run on this crate.
230 pub fn was_collapsed(&self) -> bool {
231 self.passes.contains("collapse-docs")
234 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
235 /// `collapsed_doc_value` of the given item.
236 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
237 if self.was_collapsed() {
238 item.collapsed_doc_value().map(|s| s.into())
240 item.doc_value().map(|s| s.into())
245 /// Indicates where an external crate can be found.
246 pub enum ExternalLocation {
247 /// Remote URL root of the external crate
249 /// This external crate can be found in the local doc/ folder
251 /// The external crate could not be found.
255 /// Metadata about implementations for a type or trait.
256 #[derive(Clone, Debug)]
258 pub impl_item: clean::Item,
262 fn inner_impl(&self) -> &clean::Impl {
263 match self.impl_item.inner {
264 clean::ImplItem(ref impl_) => impl_,
265 _ => panic!("non-impl item found in impl")
269 fn trait_did(&self) -> Option<DefId> {
270 self.inner_impl().trait_.def_id()
274 /// This cache is used to store information about the `clean::Crate` being
275 /// rendered in order to provide more useful documentation. This contains
276 /// information like all implementors of a trait, all traits a type implements,
277 /// documentation for all known traits, etc.
279 /// This structure purposefully does not implement `Clone` because it's intended
280 /// to be a fairly large and expensive structure to clone. Instead this adheres
281 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
282 /// rendering threads.
285 /// Mapping of typaram ids to the name of the type parameter. This is used
286 /// when pretty-printing a type (so pretty-printing doesn't have to
287 /// painfully maintain a context like this)
288 pub param_names: FxHashMap<DefId, String>,
290 /// Maps a type ID to all known implementations for that type. This is only
291 /// recognized for intra-crate `ResolvedPath` types, and is used to print
292 /// out extra documentation on the page of an enum/struct.
294 /// The values of the map are a list of implementations and documentation
295 /// found on that implementation.
296 pub impls: FxHashMap<DefId, Vec<Impl>>,
298 /// Maintains a mapping of local crate `NodeId`s to the fully qualified name
299 /// and "short type description" of that node. This is used when generating
300 /// URLs when a type is being linked to. External paths are not located in
301 /// this map because the `External` type itself has all the information
303 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
305 /// Similar to `paths`, but only holds external paths. This is only used for
306 /// generating explicit hyperlinks to other crates.
307 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
309 /// Maps local `DefId`s of exported types to fully qualified paths.
310 /// Unlike 'paths', this mapping ignores any renames that occur
311 /// due to 'use' statements.
313 /// This map is used when writing out the special 'implementors'
314 /// javascript file. By using the exact path that the type
315 /// is declared with, we ensure that each path will be identical
316 /// to the path used if the corresponding type is inlined. By
317 /// doing this, we can detect duplicate impls on a trait page, and only display
318 /// the impl for the inlined type.
319 pub exact_paths: FxHashMap<DefId, Vec<String>>,
321 /// This map contains information about all known traits of this crate.
322 /// Implementations of a crate should inherit the documentation of the
323 /// parent trait if no extra documentation is specified, and default methods
324 /// should show up in documentation about trait implementations.
325 pub traits: FxHashMap<DefId, clean::Trait>,
327 /// When rendering traits, it's often useful to be able to list all
328 /// implementors of the trait, and this mapping is exactly, that: a mapping
329 /// of trait ids to the list of known implementors of the trait
330 pub implementors: FxHashMap<DefId, Vec<Impl>>,
332 /// Cache of where external crate documentation can be found.
333 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
335 /// Cache of where documentation for primitives can be found.
336 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
338 // Note that external items for which `doc(hidden)` applies to are shown as
339 // non-reachable while local items aren't. This is because we're reusing
340 // the access levels from the privacy check pass.
341 pub access_levels: AccessLevels<DefId>,
343 /// The version of the crate being documented, if given from the `--crate-version` flag.
344 pub crate_version: Option<String>,
346 // Private fields only used when initially crawling a crate to build a cache
349 parent_stack: Vec<DefId>,
350 parent_is_trait_impl: bool,
351 search_index: Vec<IndexItem>,
353 deref_trait_did: Option<DefId>,
354 deref_mut_trait_did: Option<DefId>,
355 owned_box_did: Option<DefId>,
356 masked_crates: FxHashSet<CrateNum>,
358 // In rare case where a structure is defined in one module but implemented
359 // in another, if the implementing module is parsed before defining module,
360 // then the fully qualified name of the structure isn't presented in `paths`
361 // yet when its implementation methods are being indexed. Caches such methods
362 // and their parent id here and indexes them at the end of crate parsing.
363 orphan_impl_items: Vec<(DefId, clean::Item)>,
365 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
366 // even though the trait itself is not exported. This can happen if a trait
367 // was defined in function/expression scope, since the impl will be picked
368 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
369 // crawl. In order to prevent crashes when looking for spotlight traits or
370 // when gathering trait documentation on a type, hold impls here while
371 // folding and add them to the cache later on if we find the trait.
372 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
374 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
375 /// we need the alias element to have an array of items.
376 aliases: FxHashMap<String, Vec<IndexItem>>,
379 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
380 /// Later on moved into `CACHE_KEY`.
382 pub struct RenderInfo {
383 pub inlined: FxHashSet<DefId>,
384 pub external_paths: crate::core::ExternalPaths,
385 pub external_param_names: FxHashMap<DefId, String>,
386 pub exact_paths: FxHashMap<DefId, Vec<String>>,
387 pub access_levels: AccessLevels<DefId>,
388 pub deref_trait_did: Option<DefId>,
389 pub deref_mut_trait_did: Option<DefId>,
390 pub owned_box_did: Option<DefId>,
393 /// Helper struct to render all source code to HTML pages
394 struct SourceCollector<'a> {
395 scx: &'a mut SharedContext,
397 /// Root destination to place all HTML output into
401 /// Wrapper struct to render the source code of a file. This will do things like
402 /// adding line numbers to the left-hand side.
403 struct Source<'a>(&'a str);
405 // Helper structs for rendering items/sidebars and carrying along contextual
408 #[derive(Copy, Clone)]
411 item: &'a clean::Item,
414 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
416 /// Struct representing one entry in the JS search index. These are all emitted
417 /// by hand to a large JS file at the end of cache-creation.
424 parent: Option<DefId>,
425 parent_idx: Option<usize>,
426 search_type: Option<IndexItemFunctionType>,
429 impl ToJson for IndexItem {
430 fn to_json(&self) -> Json {
431 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
433 let mut data = Vec::with_capacity(6);
434 data.push((self.ty as usize).to_json());
435 data.push(self.name.to_json());
436 data.push(self.path.to_json());
437 data.push(self.desc.to_json());
438 data.push(self.parent_idx.to_json());
439 data.push(self.search_type.to_json());
445 /// A type used for the search index.
448 name: Option<String>,
449 generics: Option<Vec<String>>,
452 impl ToJson for Type {
453 fn to_json(&self) -> Json {
456 let mut data = Vec::with_capacity(2);
457 data.push(name.to_json());
458 if let Some(ref generics) = self.generics {
459 data.push(generics.to_json());
468 /// Full type of functions/methods in the search index.
470 struct IndexItemFunctionType {
472 output: Option<Vec<Type>>,
475 impl ToJson for IndexItemFunctionType {
476 fn to_json(&self) -> Json {
477 // If we couldn't figure out a type, just write `null`.
478 let mut iter = self.inputs.iter();
479 if match self.output {
480 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
481 None => iter.any(|ref i| i.name.is_none()),
485 let mut data = Vec::with_capacity(2);
486 data.push(self.inputs.to_json());
487 if let Some(ref output) = self.output {
488 if output.len() > 1 {
489 data.push(output.to_json());
491 data.push(output[0].to_json());
499 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
500 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
502 pub fn initial_ids() -> Vec<String> {
514 "synthetic-implementors",
516 "synthetic-implementors-list",
520 ].iter().map(|id| (String::from(*id))).collect()
523 /// Generates the documentation for `crate` into the directory `dst`
524 pub fn run(mut krate: clean::Crate,
525 options: RenderOptions,
526 passes: FxHashSet<String>,
527 renderinfo: RenderInfo,
528 diag: &errors::Handler,
529 edition: Edition) -> Result<(), Error> {
530 // need to save a copy of the options for rendering the index page
531 let md_opts = options.clone();
537 sort_modules_alphabetically,
540 extern_html_root_urls,
543 generate_search_filter,
544 generate_redirect_pages,
548 let src_root = match krate.src {
549 FileName::Real(ref p) => match p.parent() {
550 Some(p) => p.to_path_buf(),
551 None => PathBuf::new(),
555 let mut errors = Arc::new(ErrorStorage::new());
556 let mut scx = SharedContext {
559 include_sources: true,
560 local_sources: Default::default(),
561 issue_tracker_base_url: None,
562 layout: layout::Layout {
564 favicon: String::new(),
566 krate: krate.name.clone(),
568 css_file_extension: extension_css,
569 created_dirs: Default::default(),
570 sort_modules_alphabetically,
574 generate_search_filter,
575 generate_redirect_pages,
576 fs: DocFS::new(&errors),
579 // If user passed in `--playground-url` arg, we fill in crate name here
580 if let Some(url) = playground_url {
581 markdown::PLAYGROUND.with(|slot| {
582 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
586 // Crawl the crate attributes looking for attributes which control how we're
587 // going to emit HTML
588 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
589 for attr in attrs.lists(sym::doc) {
590 match (attr.name_or_empty(), attr.value_str()) {
591 (sym::html_favicon_url, Some(s)) => {
592 scx.layout.favicon = s.to_string();
594 (sym::html_logo_url, Some(s)) => {
595 scx.layout.logo = s.to_string();
597 (sym::html_playground_url, Some(s)) => {
598 markdown::PLAYGROUND.with(|slot| {
599 let name = krate.name.clone();
600 *slot.borrow_mut() = Some((Some(name), s.to_string()));
603 (sym::issue_tracker_base_url, Some(s)) => {
604 scx.issue_tracker_base_url = Some(s.to_string());
606 (sym::html_no_source, None) if attr.is_word() => {
607 scx.include_sources = false;
614 scx.ensure_dir(&dst)?;
615 krate = render_sources(&dst, &mut scx, krate)?;
616 let mut cx = Context {
619 render_redirect_pages: false,
620 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
622 id_map: Rc::new(RefCell::new(id_map)),
623 shared: Arc::new(scx),
626 // Crawl the crate to build various caches used for the output
630 external_param_names,
638 let external_paths = external_paths.into_iter()
639 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
642 let mut cache = Cache {
643 impls: Default::default(),
646 paths: Default::default(),
647 implementors: Default::default(),
649 parent_stack: Vec::new(),
650 search_index: Vec::new(),
651 parent_is_trait_impl: false,
652 extern_locations: Default::default(),
653 primitive_locations: Default::default(),
656 crate_version: krate.version.take(),
657 orphan_impl_items: Vec::new(),
658 orphan_trait_impls: Vec::new(),
659 traits: krate.external_traits.lock().replace(Default::default()),
663 masked_crates: mem::take(&mut krate.masked_crates),
664 param_names: external_param_names,
665 aliases: Default::default(),
668 // Cache where all our extern crates are located
669 for &(n, ref e) in &krate.externs {
670 let src_root = match e.src {
671 FileName::Real(ref p) => match p.parent() {
672 Some(p) => p.to_path_buf(),
673 None => PathBuf::new(),
677 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
678 cache.extern_locations.insert(n, (e.name.clone(), src_root,
679 extern_location(e, extern_url, &cx.dst)));
681 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
682 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
685 // Cache where all known primitives have their documentation located.
687 // Favor linking to as local extern as possible, so iterate all crates in
688 // reverse topological order.
689 for &(_, ref e) in krate.externs.iter().rev() {
690 for &(def_id, prim, _) in &e.primitives {
691 cache.primitive_locations.insert(prim, def_id);
694 for &(def_id, prim, _) in &krate.primitives {
695 cache.primitive_locations.insert(prim, def_id);
698 cache.stack.push(krate.name.clone());
699 krate = cache.fold_crate(krate);
701 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
702 if cache.traits.contains_key(&trait_did) {
704 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
709 // Build our search index
710 let index = build_index(&krate, &mut cache);
712 // Freeze the cache now that the index has been built. Put an Arc into TLS
713 // for future parallelization opportunities
714 let cache = Arc::new(cache);
715 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
716 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
718 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
719 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
720 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
721 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
723 // And finally render the whole crate's documentation
724 let ret = cx.krate(krate);
725 let nb_errors = Arc::get_mut(&mut errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
728 } else if nb_errors > 0 {
729 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
735 /// Builds the search index from the collected metadata
736 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
737 let mut nodeid_to_pathid = FxHashMap::default();
738 let mut crate_items = Vec::with_capacity(cache.search_index.len());
739 let mut crate_paths = Vec::<Json>::new();
741 let Cache { ref mut search_index,
742 ref orphan_impl_items,
743 ref mut paths, .. } = *cache;
745 // Attach all orphan items to the type's definition if the type
746 // has since been learned.
747 for &(did, ref item) in orphan_impl_items {
748 if let Some(&(ref fqp, _)) = paths.get(&did) {
749 search_index.push(IndexItem {
751 name: item.name.clone().unwrap(),
752 path: fqp[..fqp.len() - 1].join("::"),
753 desc: plain_summary_line_short(item.doc_value()),
756 search_type: get_index_search_type(&item),
761 // Reduce `NodeId` in paths into smaller sequential numbers,
762 // and prune the paths that do not appear in the index.
763 let mut lastpath = String::new();
764 let mut lastpathid = 0usize;
766 for item in search_index {
767 item.parent_idx = item.parent.map(|nodeid| {
768 if nodeid_to_pathid.contains_key(&nodeid) {
769 *nodeid_to_pathid.get(&nodeid).unwrap()
771 let pathid = lastpathid;
772 nodeid_to_pathid.insert(nodeid, pathid);
775 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
776 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
781 // Omit the parent path if it is same to that of the prior item.
782 if lastpath == item.path {
785 lastpath = item.path.clone();
787 crate_items.push(item.to_json());
790 let crate_doc = krate.module.as_ref().map(|module| {
791 plain_summary_line_short(module.doc_value())
792 }).unwrap_or(String::new());
794 let mut crate_data = BTreeMap::new();
795 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
796 crate_data.insert("i".to_owned(), Json::Array(crate_items));
797 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
799 // Collect the index into a string
800 format!("searchIndex[{}] = {};",
801 as_json(&krate.name),
802 Json::Object(crate_data))
807 krate: &clean::Crate,
809 search_index: String,
810 options: &RenderOptions,
811 diag: &errors::Handler,
812 ) -> Result<(), Error> {
813 // Write out the shared files. Note that these are shared among all rustdoc
814 // docs placed in the output directory, so this needs to be a synchronized
815 // operation with respect to all other rustdocs running around.
816 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
818 // Add all the static files. These may already exist, but we just
819 // overwrite them anyway to make sure that they're fresh and up-to-date.
821 write_minify(&cx.shared.fs, cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
822 static_files::RUSTDOC_CSS,
823 options.enable_minification)?;
824 write_minify(&cx.shared.fs, cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
825 static_files::SETTINGS_CSS,
826 options.enable_minification)?;
827 write_minify(&cx.shared.fs, cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
828 static_files::NOSCRIPT_CSS,
829 options.enable_minification)?;
831 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
832 // then we'll run over the "official" styles.
833 let mut themes: FxHashSet<String> = FxHashSet::default();
835 for entry in &cx.shared.themes {
836 let content = try_err!(fs::read(&entry), &entry);
837 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
838 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
840 cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
841 content.as_slice())?;
842 themes.insert(theme.to_owned());
845 let write = |p, c| { cx.shared.fs.write(p, c) };
846 if (*cx.shared).layout.logo.is_empty() {
847 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
848 static_files::RUST_LOGO)?;
850 if (*cx.shared).layout.favicon.is_empty() {
851 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
852 static_files::RUST_FAVICON)?;
854 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
855 static_files::BRUSH_SVG)?;
856 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
857 static_files::WHEEL_SVG)?;
858 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
859 static_files::DOWN_ARROW_SVG)?;
860 write_minify(&cx.shared.fs, cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
861 static_files::themes::LIGHT,
862 options.enable_minification)?;
863 themes.insert("light".to_owned());
864 write_minify(&cx.shared.fs, cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
865 static_files::themes::DARK,
866 options.enable_minification)?;
867 themes.insert("dark".to_owned());
869 let mut themes: Vec<&String> = themes.iter().collect();
871 // To avoid theme switch latencies as much as possible, we put everything theme related
872 // at the beginning of the html files into another js file.
873 let theme_js = format!(
874 r#"var themes = document.getElementById("theme-choices");
875 var themePicker = document.getElementById("theme-picker");
877 function switchThemeButtonState() {{
878 if (themes.style.display === "block") {{
879 themes.style.display = "none";
880 themePicker.style.borderBottomRightRadius = "3px";
881 themePicker.style.borderBottomLeftRadius = "3px";
883 themes.style.display = "block";
884 themePicker.style.borderBottomRightRadius = "0";
885 themePicker.style.borderBottomLeftRadius = "0";
889 function handleThemeButtonsBlur(e) {{
890 var active = document.activeElement;
891 var related = e.relatedTarget;
893 if (active.id !== "themePicker" &&
894 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
896 (related.id !== "themePicker" &&
897 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
898 switchThemeButtonState();
902 themePicker.onclick = switchThemeButtonState;
903 themePicker.onblur = handleThemeButtonsBlur;
904 [{}].forEach(function(item) {{
905 var but = document.createElement('button');
906 but.innerHTML = item;
907 but.onclick = function(el) {{
908 switchTheme(currentTheme, mainTheme, item);
910 but.onblur = handleThemeButtonsBlur;
911 themes.appendChild(but);
914 .map(|s| format!("\"{}\"", s))
915 .collect::<Vec<String>>()
917 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
921 write_minify(&cx.shared.fs, cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
922 static_files::MAIN_JS,
923 options.enable_minification)?;
924 write_minify(&cx.shared.fs, cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
925 static_files::SETTINGS_JS,
926 options.enable_minification)?;
927 if cx.shared.include_sources {
930 cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
931 static_files::sidebar::SOURCE_SCRIPT,
932 options.enable_minification)?;
938 cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
939 &format!("var resourcesSuffix = \"{}\";{}",
940 cx.shared.resource_suffix,
941 static_files::STORAGE_JS),
942 options.enable_minification)?;
945 if let Some(ref css) = cx.shared.css_file_extension {
946 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
947 let buffer = try_err!(fs::read_to_string(css), css);
948 if !options.enable_minification {
949 cx.shared.fs.write(&out, &buffer)?;
951 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
954 write_minify(&cx.shared.fs, cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
955 static_files::NORMALIZE_CSS,
956 options.enable_minification)?;
957 write(cx.dst.join("FiraSans-Regular.woff"),
958 static_files::fira_sans::REGULAR)?;
959 write(cx.dst.join("FiraSans-Medium.woff"),
960 static_files::fira_sans::MEDIUM)?;
961 write(cx.dst.join("FiraSans-LICENSE.txt"),
962 static_files::fira_sans::LICENSE)?;
963 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
964 static_files::source_serif_pro::REGULAR)?;
965 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
966 static_files::source_serif_pro::BOLD)?;
967 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
968 static_files::source_serif_pro::ITALIC)?;
969 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
970 static_files::source_serif_pro::LICENSE)?;
971 write(cx.dst.join("SourceCodePro-Regular.woff"),
972 static_files::source_code_pro::REGULAR)?;
973 write(cx.dst.join("SourceCodePro-Semibold.woff"),
974 static_files::source_code_pro::SEMIBOLD)?;
975 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
976 static_files::source_code_pro::LICENSE)?;
977 write(cx.dst.join("LICENSE-MIT.txt"),
978 static_files::LICENSE_MIT)?;
979 write(cx.dst.join("LICENSE-APACHE.txt"),
980 static_files::LICENSE_APACHE)?;
981 write(cx.dst.join("COPYRIGHT.txt"),
982 static_files::COPYRIGHT)?;
988 for_search_index: bool,
989 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
990 let mut ret = Vec::new();
991 let mut krates = Vec::new();
992 let mut variables = Vec::new();
995 for line in BufReader::new(File::open(path)?).lines() {
997 if for_search_index && line.starts_with("var R") {
998 variables.push(line.clone());
1001 if !line.starts_with(key) {
1004 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
1007 ret.push(line.to_string());
1008 krates.push(line[key.len() + 2..].split('"')
1010 .map(|s| s.to_owned())
1011 .unwrap_or_else(|| String::new()));
1014 Ok((ret, krates, variables))
1017 fn show_item(item: &IndexItem, krate: &str) -> String {
1018 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
1019 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
1020 if let Some(p) = item.parent_idx {
1021 format!(",'parent':{}", p)
1027 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
1029 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
1030 let mut output = String::with_capacity(100);
1031 for (alias, items) in &cache.aliases {
1032 if items.is_empty() {
1035 output.push_str(&format!("\"{}\":[{}],",
1038 .map(|v| show_item(v, &krate.name))
1039 .collect::<Vec<_>>()
1042 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1044 let mut v = Vec::new();
1045 try_err!(writeln!(&mut v, "var ALIASES = {{}};"), &dst);
1046 for aliases in &all_aliases {
1047 try_err!(writeln!(&mut v, "{}", aliases), &dst);
1049 cx.shared.fs.write(&dst, &v)?;
1052 use std::ffi::OsString;
1057 children: FxHashMap<OsString, Hierarchy>,
1058 elems: FxHashSet<OsString>,
1062 fn new(elem: OsString) -> Hierarchy {
1065 children: FxHashMap::default(),
1066 elems: FxHashSet::default(),
1070 fn to_json_string(&self) -> String {
1071 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1072 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1073 let mut files = self.elems.iter()
1074 .map(|s| format!("\"{}\"",
1076 .expect("invalid osstring conversion")))
1077 .collect::<Vec<_>>();
1078 files.sort_unstable_by(|a, b| a.cmp(b));
1079 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
1080 let dirs = if subs.is_empty() {
1083 format!(",\"dirs\":[{}]", subs)
1085 let files = files.join(",");
1086 let files = if files.is_empty() {
1089 format!(",\"files\":[{}]", files)
1091 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
1092 name=self.elem.to_str().expect("invalid osstring conversion"),
1098 if cx.shared.include_sources {
1099 let mut hierarchy = Hierarchy::new(OsString::new());
1100 for source in cx.shared.local_sources.iter()
1101 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1103 let mut h = &mut hierarchy;
1104 let mut elems = source.components()
1107 Component::Normal(s) => Some(s.to_owned()),
1113 let cur_elem = elems.next().expect("empty file path");
1114 if elems.peek().is_none() {
1115 h.elems.insert(cur_elem);
1118 let e = cur_elem.clone();
1119 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1120 h = h.children.get_mut(&cur_elem).expect("not found child");
1125 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1126 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1129 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1131 hierarchy.to_json_string()));
1133 let mut v = Vec::new();
1134 try_err!(writeln!(&mut v,
1135 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1136 all_sources.join("\n")),
1138 cx.shared.fs.write(&dst, &v)?;
1141 // Update the search index
1142 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1143 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1147 all_indexes.push(search_index);
1149 // Sort the indexes by crate so the file will be generated identically even
1150 // with rustdoc running in parallel.
1153 let mut v = Vec::new();
1154 try_err!(writeln!(&mut v, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1155 try_err!(write_minify_replacer(
1157 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1158 options.enable_minification),
1160 try_err!(write!(&mut v, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1161 cx.shared.fs.write(&dst, &v)?;
1163 if options.enable_index_page {
1164 if let Some(index_page) = options.index_page.clone() {
1165 let mut md_opts = options.clone();
1166 md_opts.output = cx.dst.clone();
1167 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1169 crate::markdown::render(index_page, md_opts, diag, cx.edition);
1171 let dst = cx.dst.join("index.html");
1172 let page = layout::Page {
1173 title: "Index of crates",
1176 static_root_path: cx.shared.static_root_path.as_deref(),
1177 description: "List of crates",
1178 keywords: BASIC_KEYWORDS,
1179 resource_suffix: &cx.shared.resource_suffix,
1181 static_extra_scripts: &[],
1183 krates.push(krate.name.clone());
1187 let content = format!(
1189 <span class='in-band'>List of all crates</span>\
1190 </h1><ul class='mod'>{}</ul>",
1194 format!("<li><a href=\"{}index.html\">{}</li>",
1197 .collect::<String>());
1198 let mut v = Vec::new();
1199 try_err!(layout::render(&mut v, &cx.shared.layout,
1200 &page, &(""), &content,
1201 cx.shared.css_file_extension.is_some(),
1203 cx.shared.generate_search_filter), &dst);
1204 cx.shared.fs.write(&dst, &v)?;
1208 // Update the list of all implementors for traits
1209 let dst = cx.dst.join("implementors");
1210 for (&did, imps) in &cache.implementors {
1211 // Private modules can leak through to this phase of rustdoc, which
1212 // could contain implementations for otherwise private types. In some
1213 // rare cases we could find an implementation for an item which wasn't
1214 // indexed, so we just skip this step in that case.
1216 // FIXME: this is a vague explanation for why this can't be a `get`, in
1217 // theory it should be...
1218 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1220 None => match cache.external_paths.get(&did) {
1226 let mut have_impls = false;
1227 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1229 // If the trait and implementation are in the same crate, then
1230 // there's no need to emit information about it (there's inlining
1231 // going on). If they're in different crates then the crate defining
1232 // the trait will be interested in our implementation.
1233 if imp.impl_item.def_id.krate == did.krate { continue }
1234 // If the implementation is from another crate then that crate
1236 if !imp.impl_item.def_id.is_local() { continue }
1238 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1239 as_json(&imp.inner_impl().to_string()),
1240 imp.inner_impl().synthetic,
1241 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1243 implementors.push_str("];");
1245 // Only create a js file if we have impls to add to it. If the trait is
1246 // documented locally though we always create the file to avoid dead
1248 if !have_impls && !cache.paths.contains_key(&did) {
1252 let mut mydst = dst.clone();
1253 for part in &remote_path[..remote_path.len() - 1] {
1256 cx.shared.ensure_dir(&mydst)?;
1257 mydst.push(&format!("{}.{}.js",
1258 remote_item_type.css_class(),
1259 remote_path[remote_path.len() - 1]));
1261 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1264 all_implementors.push(implementors);
1265 // Sort the implementors by crate so the file will be generated
1266 // identically even with rustdoc running in parallel.
1267 all_implementors.sort();
1269 let mut v = Vec::new();
1270 try_err!(writeln!(&mut v, "(function() {{var implementors = {{}};"), &mydst);
1271 for implementor in &all_implementors {
1272 try_err!(writeln!(&mut v, "{}", *implementor), &mydst);
1274 try_err!(writeln!(&mut v, "{}", r"
1275 if (window.register_implementors) {
1276 window.register_implementors(implementors);
1278 window.pending_implementors = implementors;
1281 try_err!(writeln!(&mut v, r"}})()"), &mydst);
1282 cx.shared.fs.write(&mydst, &v)?;
1287 fn render_sources(dst: &Path, scx: &mut SharedContext,
1288 krate: clean::Crate) -> Result<clean::Crate, Error> {
1289 info!("emitting source files");
1290 let dst = dst.join("src").join(&krate.name);
1291 scx.ensure_dir(&dst)?;
1292 let mut folder = SourceCollector {
1296 Ok(folder.fold_crate(krate))
1299 fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool
1300 ) -> Result<(), Error> {
1301 if enable_minification {
1302 if dst.extension() == Some(&OsStr::new("css")) {
1303 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1304 fs.write(dst, res.as_bytes())
1306 fs.write(dst, minifier::js::minify(contents).as_bytes())
1309 fs.write(dst, contents.as_bytes())
1313 fn write_minify_replacer<W: Write>(
1316 enable_minification: bool,
1317 ) -> io::Result<()> {
1318 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1320 if enable_minification {
1323 let tokens: Tokens<'_> = simple_minify(contents)
1326 // We keep backlines.
1327 minifier::js::clean_token_except(f, &|c: &Token<'_>| {
1328 c.get_char() != Some(ReservedChar::Backline)
1332 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1334 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1335 Token::String(s) => {
1336 let s = &s[1..s.len() -1]; // The quotes are included
1338 Some(Token::Other("E"))
1339 } else if s == "t" {
1340 Some(Token::Other("T"))
1341 } else if s == "u" {
1342 Some(Token::Other("U"))
1351 .collect::<Vec<_>>()
1354 // We add a backline after the newly created variables.
1355 minifier::js::aggregate_strings_into_array_with_separation_filter(
1358 Token::Char(ReservedChar::Backline),
1359 // This closure prevents crates' names from being aggregated.
1361 // The point here is to check if the string is preceded by '[' and
1362 // "searchIndex". If so, it means this is a crate name and that it
1363 // shouldn't be aggregated.
1366 !tokens[pos - 1].is_char(ReservedChar::OpenBracket) ||
1367 tokens[pos - 2].get_other() != Some("searchIndex")
1374 writeln!(dst, "{}", contents)
1378 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1379 /// things like ".." to components which preserve the "top down" hierarchy of a
1380 /// static HTML tree. Each component in the cleaned path will be passed as an
1381 /// argument to `f`. The very last component of the path (ie the file name) will
1382 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1383 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
1387 // make it relative, if possible
1388 let p = p.strip_prefix(src_root).unwrap_or(p);
1390 let mut iter = p.components().peekable();
1392 while let Some(c) = iter.next() {
1393 if !keep_filename && iter.peek().is_none() {
1398 Component::ParentDir => f("up".as_ref()),
1399 Component::Normal(c) => f(c),
1405 /// Attempts to find where an external crate is located, given that we're
1406 /// rendering in to the specified source destination.
1407 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1410 // See if there's documentation generated into the local directory
1411 let local_location = dst.join(&e.name);
1412 if local_location.is_dir() {
1416 if let Some(url) = extern_url {
1417 let mut url = url.to_string();
1418 if !url.ends_with("/") {
1424 // Failing that, see if there's an attribute specifying where to find this
1426 e.attrs.lists(sym::doc)
1427 .filter(|a| a.check_name(sym::html_root_url))
1428 .filter_map(|a| a.value_str())
1430 let mut url = url.to_string();
1431 if !url.ends_with("/") {
1435 }).next().unwrap_or(Unknown) // Well, at least we tried.
1438 impl<'a> DocFolder for SourceCollector<'a> {
1439 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1440 // If we're including source files, and we haven't seen this file yet,
1441 // then we need to render it out to the filesystem.
1442 if self.scx.include_sources
1443 // skip all invalid or macro spans
1444 && item.source.filename.is_real()
1445 // skip non-local items
1446 && item.def_id.is_local() {
1448 // If it turns out that we couldn't read this file, then we probably
1449 // can't read any of the files (generating html output from json or
1450 // something like that), so just don't include sources for the
1451 // entire crate. The other option is maintaining this mapping on a
1452 // per-file basis, but that's probably not worth it...
1454 .include_sources = match self.emit_source(&item.source.filename) {
1457 println!("warning: source code was requested to be rendered, \
1458 but processing `{}` had an error: {}",
1459 item.source.filename, e);
1460 println!(" skipping rendering of source code");
1465 self.fold_item_recur(item)
1469 impl<'a> SourceCollector<'a> {
1470 /// Renders the given filename into its corresponding HTML source file.
1471 fn emit_source(&mut self, filename: &FileName) -> Result<(), Error> {
1472 let p = match *filename {
1473 FileName::Real(ref file) => file,
1476 if self.scx.local_sources.contains_key(&**p) {
1477 // We've already emitted this source
1481 let contents = try_err!(fs::read_to_string(&p), &p);
1483 // Remove the utf-8 BOM if any
1484 let contents = if contents.starts_with("\u{feff}") {
1490 // Create the intermediate directories
1491 let mut cur = self.dst.clone();
1492 let mut root_path = String::from("../../");
1493 let mut href = String::new();
1494 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1495 cur.push(component);
1496 root_path.push_str("../");
1497 href.push_str(&component.to_string_lossy());
1500 self.scx.ensure_dir(&cur)?;
1501 let mut fname = p.file_name()
1502 .expect("source has no filename")
1504 fname.push(".html");
1506 href.push_str(&fname.to_string_lossy());
1508 let mut v = Vec::new();
1509 let title = format!("{} -- source", cur.file_name().expect("failed to get file name")
1510 .to_string_lossy());
1511 let desc = format!("Source to the Rust file `{}`.", filename);
1512 let page = layout::Page {
1514 css_class: "source",
1515 root_path: &root_path,
1516 static_root_path: self.scx.static_root_path.as_deref(),
1518 keywords: BASIC_KEYWORDS,
1519 resource_suffix: &self.scx.resource_suffix,
1520 extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
1521 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1523 try_err!(layout::render(&mut v, &self.scx.layout,
1524 &page, &(""), &Source(contents),
1525 self.scx.css_file_extension.is_some(),
1527 self.scx.generate_search_filter), &cur);
1528 self.scx.fs.write(&cur, &v)?;
1529 self.scx.local_sources.insert(p.clone(), href);
1534 impl DocFolder for Cache {
1535 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1536 if item.def_id.is_local() {
1537 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1540 // If this is a stripped module,
1541 // we don't want it or its children in the search index.
1542 let orig_stripped_mod = match item.inner {
1543 clean::StrippedItem(box clean::ModuleItem(..)) => {
1544 mem::replace(&mut self.stripped_mod, true)
1546 _ => self.stripped_mod,
1549 // If the impl is from a masked crate or references something from a
1550 // masked crate then remove it completely.
1551 if let clean::ImplItem(ref i) = item.inner {
1552 if self.masked_crates.contains(&item.def_id.krate) ||
1553 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1554 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1559 // Register any generics to their corresponding string. This is used
1560 // when pretty-printing types.
1561 if let Some(generics) = item.inner.generics() {
1562 self.generics(generics);
1565 // Propagate a trait method's documentation to all implementors of the
1567 if let clean::TraitItem(ref t) = item.inner {
1568 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1571 // Collect all the implementors of traits.
1572 if let clean::ImplItem(ref i) = item.inner {
1573 if let Some(did) = i.trait_.def_id() {
1574 if i.blanket_impl.is_none() {
1575 self.implementors.entry(did).or_default().push(Impl {
1576 impl_item: item.clone(),
1582 // Index this method for searching later on.
1583 if let Some(ref s) = item.name {
1584 let (parent, is_inherent_impl_item) = match item.inner {
1585 clean::StrippedItem(..) => ((None, None), false),
1586 clean::AssocConstItem(..) |
1587 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1588 // skip associated items in trait impls
1589 ((None, None), false)
1591 clean::AssocTypeItem(..) |
1592 clean::TyMethodItem(..) |
1593 clean::StructFieldItem(..) |
1594 clean::VariantItem(..) => {
1595 ((Some(*self.parent_stack.last().unwrap()),
1596 Some(&self.stack[..self.stack.len() - 1])),
1599 clean::MethodItem(..) | clean::AssocConstItem(..) => {
1600 if self.parent_stack.is_empty() {
1601 ((None, None), false)
1603 let last = self.parent_stack.last().unwrap();
1605 let path = match self.paths.get(&did) {
1606 // The current stack not necessarily has correlation
1607 // for where the type was defined. On the other
1608 // hand, `paths` always has the right
1609 // information if present.
1610 Some(&(ref fqp, ItemType::Trait)) |
1611 Some(&(ref fqp, ItemType::Struct)) |
1612 Some(&(ref fqp, ItemType::Union)) |
1613 Some(&(ref fqp, ItemType::Enum)) =>
1614 Some(&fqp[..fqp.len() - 1]),
1615 Some(..) => Some(&*self.stack),
1618 ((Some(*last), path), true)
1621 _ => ((None, Some(&*self.stack)), false)
1625 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1626 debug_assert!(!item.is_stripped());
1628 // A crate has a module at its root, containing all items,
1629 // which should not be indexed. The crate-item itself is
1630 // inserted later on when serializing the search-index.
1631 if item.def_id.index != CRATE_DEF_INDEX {
1632 self.search_index.push(IndexItem {
1634 name: s.to_string(),
1635 path: path.join("::"),
1636 desc: plain_summary_line_short(item.doc_value()),
1639 search_type: get_index_search_type(&item),
1643 (Some(parent), None) if is_inherent_impl_item => {
1644 // We have a parent, but we don't know where they're
1645 // defined yet. Wait for later to index this item.
1646 self.orphan_impl_items.push((parent, item.clone()));
1652 // Keep track of the fully qualified path for this item.
1653 let pushed = match item.name {
1654 Some(ref n) if !n.is_empty() => {
1655 self.stack.push(n.to_string());
1662 clean::StructItem(..) | clean::EnumItem(..) |
1663 clean::TypedefItem(..) | clean::TraitItem(..) |
1664 clean::FunctionItem(..) | clean::ModuleItem(..) |
1665 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1666 clean::ConstantItem(..) | clean::StaticItem(..) |
1667 clean::UnionItem(..) | clean::ForeignTypeItem |
1668 clean::MacroItem(..) | clean::ProcMacroItem(..)
1669 if !self.stripped_mod => {
1670 // Re-exported items mean that the same id can show up twice
1671 // in the rustdoc ast that we're looking at. We know,
1672 // however, that a re-exported item doesn't show up in the
1673 // `public_items` map, so we can skip inserting into the
1674 // paths map if there was already an entry present and we're
1675 // not a public item.
1676 if !self.paths.contains_key(&item.def_id) ||
1677 self.access_levels.is_public(item.def_id)
1679 self.paths.insert(item.def_id,
1680 (self.stack.clone(), item.type_()));
1682 self.add_aliases(&item);
1684 // Link variants to their parent enum because pages aren't emitted
1685 // for each variant.
1686 clean::VariantItem(..) if !self.stripped_mod => {
1687 let mut stack = self.stack.clone();
1689 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1692 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1693 self.add_aliases(&item);
1694 self.paths.insert(item.def_id, (self.stack.clone(),
1701 // Maintain the parent stack
1702 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1703 let parent_pushed = match item.inner {
1704 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1705 clean::StructItem(..) | clean::UnionItem(..) => {
1706 self.parent_stack.push(item.def_id);
1707 self.parent_is_trait_impl = false;
1710 clean::ImplItem(ref i) => {
1711 self.parent_is_trait_impl = i.trait_.is_some();
1713 clean::ResolvedPath{ did, .. } => {
1714 self.parent_stack.push(did);
1718 let prim_did = t.primitive_type().and_then(|t| {
1719 self.primitive_locations.get(&t).cloned()
1723 self.parent_stack.push(did);
1734 // Once we've recursively found all the generics, hoard off all the
1735 // implementations elsewhere.
1736 let ret = self.fold_item_recur(item).and_then(|item| {
1737 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1738 // Figure out the id of this impl. This may map to a
1739 // primitive rather than always to a struct/enum.
1740 // Note: matching twice to restrict the lifetime of the `i` borrow.
1741 let mut dids = FxHashSet::default();
1742 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1744 clean::ResolvedPath { did, .. } |
1745 clean::BorrowedRef {
1746 type_: box clean::ResolvedPath { did, .. }, ..
1751 let did = t.primitive_type().and_then(|t| {
1752 self.primitive_locations.get(&t).cloned()
1755 if let Some(did) = did {
1761 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1762 for bound in generics {
1763 if let Some(did) = bound.def_id() {
1771 let impl_item = Impl {
1774 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1776 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1779 let trait_did = impl_item.trait_did().unwrap();
1780 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1788 if pushed { self.stack.pop().unwrap(); }
1789 if parent_pushed { self.parent_stack.pop().unwrap(); }
1790 self.stripped_mod = orig_stripped_mod;
1791 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1797 fn generics(&mut self, generics: &clean::Generics) {
1798 for param in &generics.params {
1800 clean::GenericParamDefKind::Lifetime => {}
1801 clean::GenericParamDefKind::Type { did, .. } |
1802 clean::GenericParamDefKind::Const { did, .. } => {
1803 self.param_names.insert(did, param.name.clone());
1809 fn add_aliases(&mut self, item: &clean::Item) {
1810 if item.def_id.index == CRATE_DEF_INDEX {
1813 if let Some(ref item_name) = item.name {
1814 let path = self.paths.get(&item.def_id)
1815 .map(|p| p.0[..p.0.len() - 1].join("::"))
1816 .unwrap_or("std".to_owned());
1817 for alias in item.attrs.lists(sym::doc)
1818 .filter(|a| a.check_name(sym::alias))
1819 .filter_map(|a| a.value_str()
1820 .map(|s| s.to_string().replace("\"", "")))
1821 .filter(|v| !v.is_empty())
1822 .collect::<FxHashSet<_>>()
1824 self.aliases.entry(alias)
1825 .or_insert(Vec::with_capacity(1))
1828 name: item_name.to_string(),
1830 desc: plain_summary_line_short(item.doc_value()),
1833 search_type: get_index_search_type(&item),
1840 #[derive(Debug, Eq, PartialEq, Hash)]
1847 fn new(mut url: String, name: String) -> ItemEntry {
1848 while url.starts_with('/') {
1858 impl fmt::Display for ItemEntry {
1859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1860 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1864 impl PartialOrd for ItemEntry {
1865 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1866 Some(self.cmp(other))
1870 impl Ord for ItemEntry {
1871 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1872 self.name.cmp(&other.name)
1878 structs: FxHashSet<ItemEntry>,
1879 enums: FxHashSet<ItemEntry>,
1880 unions: FxHashSet<ItemEntry>,
1881 primitives: FxHashSet<ItemEntry>,
1882 traits: FxHashSet<ItemEntry>,
1883 macros: FxHashSet<ItemEntry>,
1884 functions: FxHashSet<ItemEntry>,
1885 typedefs: FxHashSet<ItemEntry>,
1886 existentials: FxHashSet<ItemEntry>,
1887 statics: FxHashSet<ItemEntry>,
1888 constants: FxHashSet<ItemEntry>,
1889 keywords: FxHashSet<ItemEntry>,
1890 attributes: FxHashSet<ItemEntry>,
1891 derives: FxHashSet<ItemEntry>,
1892 trait_aliases: FxHashSet<ItemEntry>,
1896 fn new() -> AllTypes {
1897 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1899 structs: new_set(100),
1900 enums: new_set(100),
1901 unions: new_set(100),
1902 primitives: new_set(26),
1903 traits: new_set(100),
1904 macros: new_set(100),
1905 functions: new_set(100),
1906 typedefs: new_set(100),
1907 existentials: new_set(100),
1908 statics: new_set(100),
1909 constants: new_set(100),
1910 keywords: new_set(100),
1911 attributes: new_set(100),
1912 derives: new_set(100),
1913 trait_aliases: new_set(100),
1917 fn append(&mut self, item_name: String, item_type: &ItemType) {
1918 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1919 if let Some(name) = url.pop() {
1920 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1922 let name = url.join("::");
1924 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1925 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1926 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1927 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1928 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1929 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1930 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1931 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1932 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1933 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1934 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1935 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1936 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1937 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1944 fn print_entries(f: &mut fmt::Formatter<'_>, e: &FxHashSet<ItemEntry>, title: &str,
1945 class: &str) -> fmt::Result {
1947 let mut e: Vec<&ItemEntry> = e.iter().collect();
1949 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1953 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1958 impl fmt::Display for AllTypes {
1959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1962 <span class='out-of-band'>\
1963 <span id='render-detail'>\
1964 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1965 [<span class='inner'>−</span>]\
1969 <span class='in-band'>List of all items</span>\
1971 print_entries(f, &self.structs, "Structs", "structs")?;
1972 print_entries(f, &self.enums, "Enums", "enums")?;
1973 print_entries(f, &self.unions, "Unions", "unions")?;
1974 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1975 print_entries(f, &self.traits, "Traits", "traits")?;
1976 print_entries(f, &self.macros, "Macros", "macros")?;
1977 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1978 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1979 print_entries(f, &self.functions, "Functions", "functions")?;
1980 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1981 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1982 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1983 print_entries(f, &self.statics, "Statics", "statics")?;
1984 print_entries(f, &self.constants, "Constants", "constants")
1989 struct Settings<'a> {
1990 // (id, explanation, default value)
1991 settings: Vec<(&'static str, &'static str, bool)>,
1996 impl<'a> Settings<'a> {
1997 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
2000 ("item-declarations", "Auto-hide item declarations.", true),
2001 ("item-attributes", "Auto-hide item attributes.", true),
2002 ("trait-implementations", "Auto-hide trait implementations documentation",
2004 ("method-docs", "Auto-hide item methods' documentation", false),
2005 ("go-to-only-result", "Directly go to item in search if there is only one result",
2007 ("line-numbers", "Show line numbers on code examples", false),
2015 impl<'a> fmt::Display for Settings<'a> {
2016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2019 <span class='in-band'>Rustdoc settings</span>\
2021 <div class='settings'>{}</div>\
2022 <script src='{}settings{}.js'></script>",
2023 self.settings.iter()
2024 .map(|(id, text, enabled)| {
2025 format!("<div class='setting-line'>\
2026 <label class='toggle'>\
2027 <input type='checkbox' id='{}' {}>\
2028 <span class='slider'></span>\
2031 </div>", id, if *enabled { " checked" } else { "" }, text)
2033 .collect::<String>(),
2040 fn derive_id(&self, id: String) -> String {
2041 let mut map = self.id_map.borrow_mut();
2045 /// String representation of how to get back to the root path of the 'doc/'
2046 /// folder in terms of a relative URL.
2047 fn root_path(&self) -> String {
2048 "../".repeat(self.current.len())
2051 /// Recurse in the directory structure and change the "root path" to make
2052 /// sure it always points to the top (relatively).
2053 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2054 F: FnOnce(&mut Context) -> T,
2057 panic!("Unexpected empty destination: {:?}", self.current);
2059 let prev = self.dst.clone();
2061 self.current.push(s);
2063 info!("Recursing into {}", self.dst.display());
2067 info!("Recursed; leaving {}", self.dst.display());
2069 // Go back to where we were at
2071 self.current.pop().unwrap();
2076 /// Main method for rendering a crate.
2078 /// This currently isn't parallelized, but it'd be pretty easy to add
2079 /// parallelization to this function.
2080 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2081 let mut item = match krate.module.take() {
2083 None => return Ok(()),
2085 let final_file = self.dst.join(&krate.name)
2087 let settings_file = self.dst.join("settings.html");
2089 let crate_name = krate.name.clone();
2090 item.name = Some(krate.name);
2092 let mut all = AllTypes::new();
2095 // Render the crate documentation
2096 let mut work = vec![(self.clone(), item)];
2098 while let Some((mut cx, item)) = work.pop() {
2099 cx.item(item, &mut all, |cx, item| {
2100 work.push((cx.clone(), item))
2105 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2106 if !root_path.ends_with('/') {
2107 root_path.push('/');
2109 let mut page = layout::Page {
2110 title: "List of all items in this crate",
2113 static_root_path: self.shared.static_root_path.as_deref(),
2114 description: "List of all items in this crate",
2115 keywords: BASIC_KEYWORDS,
2116 resource_suffix: &self.shared.resource_suffix,
2118 static_extra_scripts: &[],
2120 let sidebar = if let Some(ref version) = cache().crate_version {
2121 format!("<p class='location'>Crate {}</p>\
2122 <div class='block version'>\
2125 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2126 crate_name, version)
2130 let mut v = Vec::new();
2131 try_err!(layout::render(&mut v, &self.shared.layout,
2132 &page, &sidebar, &all,
2133 self.shared.css_file_extension.is_some(),
2134 &self.shared.themes,
2135 self.shared.generate_search_filter),
2137 self.shared.fs.write(&final_file, &v)?;
2139 // Generating settings page.
2140 let settings = Settings::new(self.shared.static_root_path.as_deref().unwrap_or("./"),
2141 &self.shared.resource_suffix);
2142 page.title = "Rustdoc settings";
2143 page.description = "Settings of Rustdoc";
2144 page.root_path = "./";
2146 let mut themes = self.shared.themes.clone();
2147 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2148 themes.push(PathBuf::from("settings.css"));
2149 let layout = self.shared.layout.clone();
2150 let mut v = Vec::new();
2151 try_err!(layout::render(&mut v, &layout,
2152 &page, &sidebar, &settings,
2153 self.shared.css_file_extension.is_some(),
2155 self.shared.generate_search_filter),
2157 self.shared.fs.write(&settings_file, &v)?;
2162 fn render_item(&self,
2163 writer: &mut dyn io::Write,
2167 // A little unfortunate that this is done like this, but it sure
2168 // does make formatting *a lot* nicer.
2169 CURRENT_LOCATION_KEY.with(|slot| {
2170 *slot.borrow_mut() = self.current.clone();
2173 let mut title = if it.is_primitive() || it.is_keyword() {
2174 // No need to include the namespace for primitive types and keywords
2177 self.current.join("::")
2180 if !title.is_empty() {
2181 title.push_str("::");
2183 title.push_str(it.name.as_ref().unwrap());
2185 title.push_str(" - Rust");
2186 let tyname = it.type_().css_class();
2187 let desc = if it.is_crate() {
2188 format!("API documentation for the Rust `{}` crate.",
2189 self.shared.layout.krate)
2191 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2192 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2194 let keywords = make_item_keywords(it);
2195 let page = layout::Page {
2197 root_path: &self.root_path(),
2198 static_root_path: self.shared.static_root_path.as_deref(),
2201 keywords: &keywords,
2202 resource_suffix: &self.shared.resource_suffix,
2204 static_extra_scripts: &[],
2208 self.id_map.borrow_mut().reset();
2209 self.id_map.borrow_mut().populate(initial_ids());
2212 if !self.render_redirect_pages {
2213 layout::render(writer, &self.shared.layout, &page,
2214 &Sidebar{ cx: self, item: it },
2215 &Item{ cx: self, item: it },
2216 self.shared.css_file_extension.is_some(),
2217 &self.shared.themes,
2218 self.shared.generate_search_filter)?;
2220 let mut url = self.root_path();
2221 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2222 for name in &names[..names.len() - 1] {
2226 url.push_str(&item_path(ty, names.last().unwrap()));
2227 layout::redirect(writer, &url)?;
2233 /// Non-parallelized version of rendering an item. This will take the input
2234 /// item, render its contents, and then invoke the specified closure with
2235 /// all sub-items which need to be rendered.
2237 /// The rendering driver uses this closure to queue up more work.
2238 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2239 where F: FnMut(&mut Context, clean::Item),
2241 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2242 // if they contain impls for public types. These modules can also
2243 // contain items such as publicly re-exported structures.
2245 // External crates will provide links to these structures, so
2246 // these modules are recursed into, but not rendered normally
2247 // (a flag on the context).
2248 if !self.render_redirect_pages {
2249 self.render_redirect_pages = item.is_stripped();
2253 // modules are special because they add a namespace. We also need to
2254 // recurse into the items of the module as well.
2255 let name = item.name.as_ref().unwrap().to_string();
2256 let mut item = Some(item);
2257 let scx = self.shared.clone();
2258 self.recurse(name, |this| {
2259 let item = item.take().unwrap();
2261 let mut buf = Vec::new();
2262 this.render_item(&mut buf, &item, false).unwrap();
2263 // buf will be empty if the module is stripped and there is no redirect for it
2264 if !buf.is_empty() {
2265 this.shared.ensure_dir(&this.dst)?;
2266 let joint_dst = this.dst.join("index.html");
2267 scx.fs.write(&joint_dst, buf)?;
2270 let m = match item.inner {
2271 clean::StrippedItem(box clean::ModuleItem(m)) |
2272 clean::ModuleItem(m) => m,
2276 // Render sidebar-items.js used throughout this module.
2277 if !this.render_redirect_pages {
2278 let items = this.build_sidebar_items(&m);
2279 let js_dst = this.dst.join("sidebar-items.js");
2280 let mut v = Vec::new();
2281 try_err!(write!(&mut v, "initSidebarItems({});",
2282 as_json(&items)), &js_dst);
2283 scx.fs.write(&js_dst, &v)?;
2286 for item in m.items {
2292 } else if item.name.is_some() {
2293 let mut buf = Vec::new();
2294 self.render_item(&mut buf, &item, true).unwrap();
2295 // buf will be empty if the item is stripped and there is no redirect for it
2296 if !buf.is_empty() {
2297 let name = item.name.as_ref().unwrap();
2298 let item_type = item.type_();
2299 let file_name = &item_path(item_type, name);
2300 self.shared.ensure_dir(&self.dst)?;
2301 let joint_dst = self.dst.join(file_name);
2302 self.shared.fs.write(&joint_dst, buf)?;
2304 if !self.render_redirect_pages {
2305 all.append(full_path(self, &item), &item_type);
2307 if self.shared.generate_redirect_pages {
2308 // Redirect from a sane URL using the namespace to Rustdoc's
2309 // URL for the page.
2310 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2311 let redir_dst = self.dst.join(redir_name);
2312 let mut v = Vec::new();
2313 try_err!(layout::redirect(&mut v, file_name), &redir_dst);
2314 self.shared.fs.write(&redir_dst, &v)?;
2316 // If the item is a macro, redirect from the old macro URL (with !)
2317 // to the new one (without).
2318 if item_type == ItemType::Macro {
2319 let redir_name = format!("{}.{}!.html", item_type, name);
2320 let redir_dst = self.dst.join(redir_name);
2321 let mut v = Vec::new();
2322 try_err!(layout::redirect(&mut v, file_name), &redir_dst);
2323 self.shared.fs.write(&redir_dst, &v)?;
2330 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2331 // BTreeMap instead of HashMap to get a sorted output
2332 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2333 for item in &m.items {
2334 if item.is_stripped() { continue }
2336 let short = item.type_().css_class();
2337 let myname = match item.name {
2339 Some(ref s) => s.to_string(),
2341 let short = short.to_string();
2342 map.entry(short).or_default()
2343 .push((myname, Some(plain_summary_line(item.doc_value()))));
2346 if self.shared.sort_modules_alphabetically {
2347 for (_, items) in &mut map {
2356 /// Generates a url appropriate for an `href` attribute back to the source of
2359 /// The url generated, when clicked, will redirect the browser back to the
2360 /// original source code.
2362 /// If `None` is returned, then a source link couldn't be generated. This
2363 /// may happen, for example, with externally inlined items where the source
2364 /// of their crate documentation isn't known.
2365 fn src_href(&self) -> Option<String> {
2366 let mut root = self.cx.root_path();
2368 let cache = cache();
2369 let mut path = String::new();
2371 // We can safely ignore macros from other libraries
2372 let file = match self.item.source.filename {
2373 FileName::Real(ref path) => path,
2377 let (krate, path) = if self.item.def_id.is_local() {
2378 if let Some(path) = self.cx.shared.local_sources.get(file) {
2379 (&self.cx.shared.layout.krate, path)
2384 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2385 (ref name, ref src, Local) => (name, src),
2386 (ref name, ref src, Remote(ref s)) => {
2387 root = s.to_string();
2390 (_, _, Unknown) => return None,
2393 clean_srcpath(&src_root, file, false, |component| {
2394 path.push_str(&component.to_string_lossy());
2397 let mut fname = file.file_name().expect("source has no filename")
2399 fname.push(".html");
2400 path.push_str(&fname.to_string_lossy());
2404 let lines = if self.item.source.loline == self.item.source.hiline {
2405 self.item.source.loline.to_string()
2407 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2409 Some(format!("{root}src/{krate}/{path}#{lines}",
2410 root = Escape(&root),
2417 fn wrap_into_docblock<F>(w: &mut fmt::Formatter<'_>,
2418 f: F) -> fmt::Result
2419 where F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result {
2420 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2425 impl<'a> fmt::Display for Item<'a> {
2426 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2427 debug_assert!(!self.item.is_stripped());
2428 // Write the breadcrumb trail header for the top
2429 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2430 if let Some(version) = self.item.stable_since() {
2431 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2435 "<span id='render-detail'>\
2436 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2437 title=\"collapse all docs\">\
2438 [<span class='inner'>−</span>]\
2444 // When this item is part of a `pub use` in a downstream crate, the
2445 // [src] link in the downstream documentation will actually come back to
2446 // this page, and this link will be auto-clicked. The `id` attribute is
2447 // used to find the link to auto-click.
2448 if self.cx.shared.include_sources && !self.item.is_primitive() {
2449 if let Some(l) = self.src_href() {
2450 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2451 l, "goto source code")?;
2455 write!(fmt, "</span>")?; // out-of-band
2456 write!(fmt, "<span class='in-band'>")?;
2457 match self.item.inner {
2458 clean::ModuleItem(ref m) => if m.is_crate {
2459 write!(fmt, "Crate ")?;
2461 write!(fmt, "Module ")?;
2463 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2464 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2465 clean::StructItem(..) => write!(fmt, "Struct ")?,
2466 clean::UnionItem(..) => write!(fmt, "Union ")?,
2467 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2468 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2469 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2470 clean::ProcMacroItem(ref mac) => match mac.kind {
2471 MacroKind::Bang => write!(fmt, "Macro ")?,
2472 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2473 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2475 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2476 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2477 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2478 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2479 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2480 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2481 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2483 // We don't generate pages for any other type.
2487 if !self.item.is_primitive() && !self.item.is_keyword() {
2488 let cur = &self.cx.current;
2489 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2490 for (i, component) in cur.iter().enumerate().take(amt) {
2491 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2492 "../".repeat(cur.len() - i - 1),
2496 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2497 self.item.type_(), self.item.name.as_ref().unwrap())?;
2499 write!(fmt, "</span></h1>")?; // in-band
2501 match self.item.inner {
2502 clean::ModuleItem(ref m) =>
2503 item_module(fmt, self.cx, self.item, &m.items),
2504 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2505 item_function(fmt, self.cx, self.item, f),
2506 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2507 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2508 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2509 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2510 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2511 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2512 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2513 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2514 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2515 item_static(fmt, self.cx, self.item, i),
2516 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2517 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2518 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2519 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2520 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2522 // We don't generate pages for any other type.
2529 fn item_path(ty: ItemType, name: &str) -> String {
2531 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2532 _ => format!("{}.{}.html", ty.css_class(), name),
2536 fn full_path(cx: &Context, item: &clean::Item) -> String {
2537 let mut s = cx.current.join("::");
2539 s.push_str(item.name.as_ref().unwrap());
2543 fn shorter(s: Option<&str>) -> String {
2545 Some(s) => s.lines()
2546 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2548 (*line).chars().any(|chr|{
2549 !chr.is_whitespace()
2551 }).collect::<Vec<_>>().join("\n"),
2552 None => String::new()
2557 fn plain_summary_line(s: Option<&str>) -> String {
2558 let line = shorter(s).replace("\n", " ");
2559 markdown::plain_summary_line_full(&line[..], false)
2563 fn plain_summary_line_short(s: Option<&str>) -> String {
2564 let line = shorter(s).replace("\n", " ");
2565 markdown::plain_summary_line_full(&line[..], true)
2568 fn document(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item) -> fmt::Result {
2569 if let Some(ref name) = item.name {
2570 info!("Documenting {}", name);
2572 document_stability(w, cx, item, false)?;
2573 document_full(w, item, cx, "", false)?;
2577 /// Render md_text as markdown.
2578 fn render_markdown(w: &mut fmt::Formatter<'_>,
2581 links: Vec<(String, String)>,
2585 let mut ids = cx.id_map.borrow_mut();
2586 write!(w, "<div class='docblock{}'>{}{}</div>",
2587 if is_hidden { " hidden" } else { "" },
2589 Markdown(md_text, &links, RefCell::new(&mut ids),
2590 cx.codes, cx.edition))
2594 w: &mut fmt::Formatter<'_>,
2597 link: AssocItemLink<'_>,
2598 prefix: &str, is_hidden: bool
2600 if let Some(s) = item.doc_value() {
2601 let markdown = if s.contains('\n') {
2602 format!("{} [Read more]({})",
2603 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2605 plain_summary_line(Some(s))
2607 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2608 } else if !prefix.is_empty() {
2609 write!(w, "<div class='docblock{}'>{}</div>",
2610 if is_hidden { " hidden" } else { "" },
2616 fn document_full(w: &mut fmt::Formatter<'_>, item: &clean::Item,
2617 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2618 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2619 debug!("Doc block: =====\n{}\n=====", s);
2620 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2621 } else if !prefix.is_empty() {
2622 write!(w, "<div class='docblock{}'>{}</div>",
2623 if is_hidden { " hidden" } else { "" },
2629 fn document_stability(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
2630 is_hidden: bool) -> fmt::Result {
2631 let stabilities = short_stability(item, cx);
2632 if !stabilities.is_empty() {
2633 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2634 for stability in stabilities {
2635 write!(w, "{}", stability)?;
2637 write!(w, "</div>")?;
2642 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2643 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2646 fn document_non_exhaustive(w: &mut fmt::Formatter<'_>, item: &clean::Item) -> fmt::Result {
2647 if item.is_non_exhaustive() {
2648 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2649 if item.is_struct() {
2651 } else if item.is_enum() {
2653 } else if item.is_variant() {
2660 if item.is_struct() {
2661 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2662 Therefore, non-exhaustive structs cannot be constructed in external crates \
2663 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2664 matched against without a wildcard <code>..</code>; and \
2665 struct update syntax will not work.")?;
2666 } else if item.is_enum() {
2667 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2668 Therefore, when matching against variants of non-exhaustive enums, an \
2669 extra wildcard arm must be added to account for any future variants.")?;
2670 } else if item.is_variant() {
2671 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
2672 Therefore, non-exhaustive enum variants cannot be constructed in external \
2673 crates and cannot be matched against.")?;
2675 write!(w, "This type will require a wildcard arm in any match statements or \
2679 write!(w, "</div>")?;
2685 fn name_key(name: &str) -> (&str, u64, usize) {
2686 let end = name.bytes()
2687 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2689 // find number at end
2690 let split = name[0..end].bytes()
2691 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2693 // count leading zeroes
2695 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2697 // sort leading zeroes last
2698 let num_zeroes = after_zeroes - split;
2700 match name[split..end].parse() {
2701 Ok(n) => (&name[..split], n, num_zeroes),
2702 Err(_) => (name, 0, num_zeroes),
2706 fn item_module(w: &mut fmt::Formatter<'_>, cx: &Context,
2707 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2708 document(w, cx, item)?;
2710 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2712 // the order of item types in the listing
2713 fn reorder(ty: ItemType) -> u8 {
2715 ItemType::ExternCrate => 0,
2716 ItemType::Import => 1,
2717 ItemType::Primitive => 2,
2718 ItemType::Module => 3,
2719 ItemType::Macro => 4,
2720 ItemType::Struct => 5,
2721 ItemType::Enum => 6,
2722 ItemType::Constant => 7,
2723 ItemType::Static => 8,
2724 ItemType::Trait => 9,
2725 ItemType::Function => 10,
2726 ItemType::Typedef => 12,
2727 ItemType::Union => 13,
2732 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2733 let ty1 = i1.type_();
2734 let ty2 = i2.type_();
2736 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2738 let s1 = i1.stability.as_ref().map(|s| s.level);
2739 let s2 = i2.stability.as_ref().map(|s| s.level);
2741 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2742 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2745 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2746 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2747 name_key(lhs).cmp(&name_key(rhs))
2750 if cx.shared.sort_modules_alphabetically {
2751 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2753 // This call is to remove re-export duplicates in cases such as:
2758 // pub trait Double { fn foo(); }
2762 // pub use foo::bar::*;
2766 // `Double` will appear twice in the generated docs.
2768 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2769 // can be identical even if the elements are different (mostly in imports).
2770 // So in case this is an import, we keep everything by adding a "unique id"
2771 // (which is the position in the vector).
2772 indices.dedup_by_key(|i| (items[*i].def_id,
2773 if items[*i].name.as_ref().is_some() {
2774 Some(full_path(cx, &items[*i]))
2779 if items[*i].is_import() {
2785 debug!("{:?}", indices);
2786 let mut curty = None;
2787 for &idx in &indices {
2788 let myitem = &items[idx];
2789 if myitem.is_stripped() {
2793 let myty = Some(myitem.type_());
2794 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2795 // Put `extern crate` and `use` re-exports in the same section.
2797 } else if myty != curty {
2798 if curty.is_some() {
2799 write!(w, "</table>")?;
2802 let (short, name) = item_ty_to_strs(&myty.unwrap());
2803 write!(w, "<h2 id='{id}' class='section-header'>\
2804 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2805 id = cx.derive_id(short.to_owned()), name = name)?;
2808 match myitem.inner {
2809 clean::ExternCrateItem(ref name, ref src) => {
2810 use crate::html::format::HRef;
2814 write!(w, "<tr><td><code>{}extern crate {} as {};",
2815 VisSpace(&myitem.visibility),
2816 HRef::new(myitem.def_id, src),
2820 write!(w, "<tr><td><code>{}extern crate {};",
2821 VisSpace(&myitem.visibility),
2822 HRef::new(myitem.def_id, name))?
2825 write!(w, "</code></td></tr>")?;
2828 clean::ImportItem(ref import) => {
2829 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2830 VisSpace(&myitem.visibility), *import)?;
2834 if myitem.name.is_none() { continue }
2836 let unsafety_flag = match myitem.inner {
2837 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2838 if func.header.unsafety == hir::Unsafety::Unsafe => {
2839 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2844 let stab = myitem.stability_class();
2845 let add = if stab.is_some() {
2851 let doc_value = myitem.doc_value().unwrap_or("");
2853 <tr class='{stab}{add}module-item'>\
2854 <td><a class=\"{class}\" href=\"{href}\" \
2855 title='{title}'>{name}</a>{unsafety_flag}</td>\
2856 <td class='docblock-short'>{stab_tags}{docs}</td>\
2858 name = *myitem.name.as_ref().unwrap(),
2859 stab_tags = stability_tags(myitem),
2860 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2861 class = myitem.type_(),
2863 stab = stab.unwrap_or_else(|| String::new()),
2864 unsafety_flag = unsafety_flag,
2865 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2866 title = [full_path(cx, myitem), myitem.type_().to_string()]
2868 .filter_map(|s| if !s.is_empty() {
2873 .collect::<Vec<_>>()
2880 if curty.is_some() {
2881 write!(w, "</table>")?;
2886 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2888 fn stability_tags(item: &clean::Item) -> String {
2889 let mut tags = String::new();
2891 fn tag_html(class: &str, contents: &str) -> String {
2892 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2895 // The trailing space after each tag is to space it properly against the rest of the docs.
2896 if item.deprecation().is_some() {
2897 let mut message = "Deprecated";
2898 if let Some(ref stab) = item.stability {
2899 if let Some(ref depr) = stab.deprecation {
2900 if let Some(ref since) = depr.since {
2901 if !stability::deprecation_in_effect(&since) {
2902 message = "Deprecation planned";
2907 tags += &tag_html("deprecated", message);
2910 if let Some(stab) = item
2913 .filter(|s| s.level == stability::Unstable)
2915 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2916 tags += &tag_html("internal", "Internal");
2918 tags += &tag_html("unstable", "Experimental");
2922 if let Some(ref cfg) = item.attrs.cfg {
2923 tags += &tag_html("portability", &cfg.render_short_html());
2929 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2931 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2932 let mut stability = vec![];
2933 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2935 if let Some(Deprecation { note, since }) = &item.deprecation() {
2936 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2937 // but only display the future-deprecation messages for #[rustc_deprecated].
2938 let mut message = if let Some(since) = since {
2939 format!("Deprecated since {}", Escape(since))
2941 String::from("Deprecated")
2943 if let Some(ref stab) = item.stability {
2944 if let Some(ref depr) = stab.deprecation {
2945 if let Some(ref since) = depr.since {
2946 if !stability::deprecation_in_effect(&since) {
2947 message = format!("Deprecating in {}", Escape(&since));
2953 if let Some(note) = note {
2954 let mut ids = cx.id_map.borrow_mut();
2955 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes, cx.edition);
2956 message.push_str(&format!(": {}", html));
2958 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2961 if let Some(stab) = item
2964 .filter(|stab| stab.level == stability::Unstable)
2966 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2968 let mut message = if is_rustc_private {
2969 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2971 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2975 if let Some(feature) = stab.feature.as_ref() {
2976 let mut feature = format!("<code>{}</code>", Escape(&feature));
2977 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2978 feature.push_str(&format!(
2979 " <a href=\"{url}{issue}\">#{issue}</a>",
2985 message.push_str(&format!(" ({})", feature));
2988 if let Some(unstable_reason) = &stab.unstable_reason {
2989 // Provide a more informative message than the compiler help.
2990 let unstable_reason = if is_rustc_private {
2991 "This crate is being loaded from the sysroot, a permanently unstable location \
2992 for private compiler dependencies. It is not intended for general use. Prefer \
2993 using a public version of this crate from \
2994 [crates.io](https://crates.io) via [`Cargo.toml`]\
2995 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
3000 let mut ids = cx.id_map.borrow_mut();
3002 "<details><summary>{}</summary>{}</details>",
3004 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes, cx.edition)
3008 let class = if is_rustc_private {
3013 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
3016 if let Some(ref cfg) = item.attrs.cfg {
3017 stability.push(format!(
3018 "<div class='stab portability'>{}</div>",
3019 cfg.render_long_html()
3026 fn item_constant(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3027 c: &clean::Constant) -> fmt::Result {
3028 write!(w, "<pre class='rust const'>")?;
3029 render_attributes(w, it, false)?;
3030 write!(w, "{vis}const \
3031 {name}: {typ}</pre>",
3032 vis = VisSpace(&it.visibility),
3033 name = it.name.as_ref().unwrap(),
3038 fn item_static(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3039 s: &clean::Static) -> fmt::Result {
3040 write!(w, "<pre class='rust static'>")?;
3041 render_attributes(w, it, false)?;
3042 write!(w, "{vis}static {mutability}\
3043 {name}: {typ}</pre>",
3044 vis = VisSpace(&it.visibility),
3045 mutability = MutableSpace(s.mutability),
3046 name = it.name.as_ref().unwrap(),
3051 fn item_function(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3052 f: &clean::Function) -> fmt::Result {
3053 let header_len = format!(
3054 "{}{}{}{}{:#}fn {}{:#}",
3055 VisSpace(&it.visibility),
3056 ConstnessSpace(f.header.constness),
3057 UnsafetySpace(f.header.unsafety),
3058 AsyncSpace(f.header.asyncness),
3059 AbiSpace(f.header.abi),
3060 it.name.as_ref().unwrap(),
3063 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
3064 render_attributes(w, it, false)?;
3066 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
3067 {name}{generics}{decl}{where_clause}</pre>",
3068 vis = VisSpace(&it.visibility),
3069 constness = ConstnessSpace(f.header.constness),
3070 unsafety = UnsafetySpace(f.header.unsafety),
3071 asyncness = AsyncSpace(f.header.asyncness),
3072 abi = AbiSpace(f.header.abi),
3073 name = it.name.as_ref().unwrap(),
3074 generics = f.generics,
3075 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
3080 asyncness: f.header.asyncness,
3085 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter<'_>,
3086 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
3087 // If there's already another implementor that has the same abbridged name, use the
3088 // full path, for example in `std::iter::ExactSizeIterator`
3089 let use_absolute = match implementor.inner_impl().for_ {
3090 clean::ResolvedPath { ref path, is_generic: false, .. } |
3091 clean::BorrowedRef {
3092 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3094 } => implementor_dups[path.last_name()].1,
3097 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3098 implementor.impl_item.stable_since(), false, Some(use_absolute), false, false)?;
3102 fn render_impls(cx: &Context, w: &mut fmt::Formatter<'_>,
3104 containing_item: &clean::Item) -> fmt::Result {
3106 let did = i.trait_did().unwrap();
3107 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3108 render_impl(w, cx, i, assoc_link,
3109 RenderMode::Normal, containing_item.stable_since(), true, None, false, true)?;
3114 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3115 let mut bounds = String::new();
3116 if !t_bounds.is_empty() {
3118 bounds.push_str(": ");
3120 for (i, p) in t_bounds.iter().enumerate() {
3122 bounds.push_str(" + ");
3124 bounds.push_str(&(*p).to_string());
3130 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3131 let lhs = format!("{}", lhs.inner_impl());
3132 let rhs = format!("{}", rhs.inner_impl());
3134 // lhs and rhs are formatted as HTML, which may be unnecessary
3135 name_key(&lhs).cmp(&name_key(&rhs))
3139 w: &mut fmt::Formatter<'_>,
3144 let bounds = bounds(&t.bounds, false);
3145 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3146 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3147 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3148 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3150 // Output the trait definition
3151 wrap_into_docblock(w, |w| {
3152 write!(w, "<pre class='rust trait'>")?;
3153 render_attributes(w, it, true)?;
3154 write!(w, "{}{}{}trait {}{}{}",
3155 VisSpace(&it.visibility),
3156 UnsafetySpace(t.unsafety),
3157 if t.is_auto { "auto " } else { "" },
3158 it.name.as_ref().unwrap(),
3162 if !t.generics.where_predicates.is_empty() {
3163 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3168 if t.items.is_empty() {
3169 write!(w, "{{ }}")?;
3171 // FIXME: we should be using a derived_id for the Anchors here
3174 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3177 if !types.is_empty() && !consts.is_empty() {
3181 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3184 if !consts.is_empty() && !required.is_empty() {
3187 for (pos, m) in required.iter().enumerate() {
3188 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3191 if pos < required.len() - 1 {
3192 write!(w, "<div class='item-spacer'></div>")?;
3195 if !required.is_empty() && !provided.is_empty() {
3198 for (pos, m) in provided.iter().enumerate() {
3199 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3201 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3202 write!(w, ",\n {{ ... }}\n")?;
3205 write!(w, " {{ ... }}\n")?;
3208 if pos < provided.len() - 1 {
3209 write!(w, "<div class='item-spacer'></div>")?;
3217 // Trait documentation
3218 document(w, cx, it)?;
3220 fn write_small_section_header(
3221 w: &mut fmt::Formatter<'_>,
3224 extra_content: &str,
3227 <h2 id='{0}' class='small-section-header'>\
3228 {1}<a href='#{0}' class='anchor'></a>\
3229 </h2>{2}", id, title, extra_content)
3232 fn write_loading_content(w: &mut fmt::Formatter<'_>, extra_content: &str) -> fmt::Result {
3233 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3236 fn trait_item(w: &mut fmt::Formatter<'_>, cx: &Context, m: &clean::Item, t: &clean::Item)
3238 let name = m.name.as_ref().unwrap();
3239 let item_type = m.type_();
3240 let id = cx.derive_id(format!("{}.{}", item_type, name));
3241 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3242 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3243 extra = render_spotlight_traits(m)?,
3246 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3247 write!(w, "</code>")?;
3248 render_stability_since(w, m, t)?;
3249 write!(w, "</h3>")?;
3250 document(w, cx, m)?;
3254 if !types.is_empty() {
3255 write_small_section_header(w, "associated-types", "Associated Types",
3256 "<div class='methods'>")?;
3258 trait_item(w, cx, *t, it)?;
3260 write_loading_content(w, "</div>")?;
3263 if !consts.is_empty() {
3264 write_small_section_header(w, "associated-const", "Associated Constants",
3265 "<div class='methods'>")?;
3267 trait_item(w, cx, *t, it)?;
3269 write_loading_content(w, "</div>")?;
3272 // Output the documentation for each function individually
3273 if !required.is_empty() {
3274 write_small_section_header(w, "required-methods", "Required methods",
3275 "<div class='methods'>")?;
3276 for m in &required {
3277 trait_item(w, cx, *m, it)?;
3279 write_loading_content(w, "</div>")?;
3281 if !provided.is_empty() {
3282 write_small_section_header(w, "provided-methods", "Provided methods",
3283 "<div class='methods'>")?;
3284 for m in &provided {
3285 trait_item(w, cx, *m, it)?;
3287 write_loading_content(w, "</div>")?;
3290 // If there are methods directly on this trait object, render them here.
3291 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3293 let cache = cache();
3295 let mut synthetic_types = Vec::new();
3297 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3298 // The DefId is for the first Type found with that name. The bool is
3299 // if any Types with the same name but different DefId have been found.
3300 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3301 for implementor in implementors {
3302 match implementor.inner_impl().for_ {
3303 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3304 clean::BorrowedRef {
3305 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3308 let &mut (prev_did, ref mut has_duplicates) =
3309 implementor_dups.entry(path.last_name()).or_insert((did, false));
3310 if prev_did != did {
3311 *has_duplicates = true;
3318 let (local, foreign) = implementors.iter()
3319 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3320 .map_or(true, |d| cache.paths.contains_key(&d)));
3323 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3324 .partition(|i| i.inner_impl().synthetic);
3326 synthetic.sort_by(compare_impl);
3327 concrete.sort_by(compare_impl);
3329 if !foreign.is_empty() {
3330 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3332 for implementor in foreign {
3333 let assoc_link = AssocItemLink::GotoSource(
3334 implementor.impl_item.def_id,
3335 &implementor.inner_impl().provided_trait_methods
3337 render_impl(w, cx, &implementor, assoc_link,
3338 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3339 None, true, false)?;
3341 write_loading_content(w, "")?;
3344 write_small_section_header(w, "implementors", "Implementors",
3345 "<div class='item-list' id='implementors-list'>")?;
3346 for implementor in concrete {
3347 render_implementor(cx, implementor, w, &implementor_dups)?;
3349 write_loading_content(w, "</div>")?;
3352 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3353 "<div class='item-list' id='synthetic-implementors-list'>")?;
3354 for implementor in synthetic {
3355 synthetic_types.extend(
3356 collect_paths_for_type(implementor.inner_impl().for_.clone())
3358 render_implementor(cx, implementor, w, &implementor_dups)?;
3360 write_loading_content(w, "</div>")?;
3363 // even without any implementations to write in, we still want the heading and list, so the
3364 // implementors javascript file pulled in below has somewhere to write the impls into
3365 write_small_section_header(w, "implementors", "Implementors",
3366 "<div class='item-list' id='implementors-list'>")?;
3367 write_loading_content(w, "</div>")?;
3370 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3371 "<div class='item-list' id='synthetic-implementors-list'>")?;
3372 write_loading_content(w, "</div>")?;
3375 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3376 as_json(&synthetic_types))?;
3378 write!(w, r#"<script type="text/javascript" async
3379 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3381 root_path = vec![".."; cx.current.len()].join("/"),
3382 path = if it.def_id.is_local() {
3383 cx.current.join("/")
3385 let (ref path, _) = cache.external_paths[&it.def_id];
3386 path[..path.len() - 1].join("/")
3388 ty = it.type_().css_class(),
3389 name = *it.name.as_ref().unwrap())?;
3393 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
3394 use crate::html::item_type::ItemType::*;
3396 let name = it.name.as_ref().unwrap();
3397 let ty = match it.type_() {
3398 Typedef | AssocType => AssocType,
3402 let anchor = format!("#{}.{}", ty, name);
3404 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3405 AssocItemLink::Anchor(None) => anchor,
3406 AssocItemLink::GotoSource(did, _) => {
3407 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3412 fn assoc_const(w: &mut fmt::Formatter<'_>,
3415 _default: Option<&String>,
3416 link: AssocItemLink<'_>,
3417 extra: &str) -> fmt::Result {
3418 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3420 VisSpace(&it.visibility),
3421 naive_assoc_href(it, link),
3422 it.name.as_ref().unwrap(),
3427 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3428 bounds: &[clean::GenericBound],
3429 default: Option<&clean::Type>,
3430 link: AssocItemLink<'_>,
3431 extra: &str) -> fmt::Result {
3432 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
3434 naive_assoc_href(it, link),
3435 it.name.as_ref().unwrap())?;
3436 if !bounds.is_empty() {
3437 write!(w, ": {}", GenericBounds(bounds))?
3439 if let Some(default) = default {
3440 write!(w, " = {}", default)?;
3445 fn render_stability_since_raw<'a, T: fmt::Write>(
3447 ver: Option<&'a str>,
3448 containing_ver: Option<&'a str>,
3450 if let Some(v) = ver {
3451 if containing_ver != ver && v.len() > 0 {
3452 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)?
3458 fn render_stability_since(w: &mut fmt::Formatter<'_>,
3460 containing_item: &clean::Item) -> fmt::Result {
3461 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3464 fn render_assoc_item(w: &mut fmt::Formatter<'_>,
3466 link: AssocItemLink<'_>,
3467 parent: ItemType) -> fmt::Result {
3468 fn method(w: &mut fmt::Formatter<'_>,
3470 header: hir::FnHeader,
3471 g: &clean::Generics,
3473 link: AssocItemLink<'_>,
3476 let name = meth.name.as_ref().unwrap();
3477 let anchor = format!("#{}.{}", meth.type_(), name);
3478 let href = match link {
3479 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3480 AssocItemLink::Anchor(None) => anchor,
3481 AssocItemLink::GotoSource(did, provided_methods) => {
3482 // We're creating a link from an impl-item to the corresponding
3483 // trait-item and need to map the anchored type accordingly.
3484 let ty = if provided_methods.contains(name) {
3490 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3493 let mut header_len = format!(
3494 "{}{}{}{}{}{:#}fn {}{:#}",
3495 VisSpace(&meth.visibility),
3496 ConstnessSpace(header.constness),
3497 UnsafetySpace(header.unsafety),
3498 AsyncSpace(header.asyncness),
3499 DefaultSpace(meth.is_default()),
3500 AbiSpace(header.abi),
3504 let (indent, end_newline) = if parent == ItemType::Trait {
3510 render_attributes(w, meth, false)?;
3511 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3512 {generics}{decl}{where_clause}",
3513 if parent == ItemType::Trait { " " } else { "" },
3514 VisSpace(&meth.visibility),
3515 ConstnessSpace(header.constness),
3516 UnsafetySpace(header.unsafety),
3517 AsyncSpace(header.asyncness),
3518 DefaultSpace(meth.is_default()),
3519 AbiSpace(header.abi),
3527 asyncness: header.asyncness,
3529 where_clause = WhereClause {
3536 clean::StrippedItem(..) => Ok(()),
3537 clean::TyMethodItem(ref m) => {
3538 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3540 clean::MethodItem(ref m) => {
3541 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3543 clean::AssocConstItem(ref ty, ref default) => {
3544 assoc_const(w, item, ty, default.as_ref(), link,
3545 if parent == ItemType::Trait { " " } else { "" })
3547 clean::AssocTypeItem(ref bounds, ref default) => {
3548 assoc_type(w, item, bounds, default.as_ref(), link,
3549 if parent == ItemType::Trait { " " } else { "" })
3551 _ => panic!("render_assoc_item called on non-associated-item")
3555 fn item_struct(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3556 s: &clean::Struct) -> fmt::Result {
3557 wrap_into_docblock(w, |w| {
3558 write!(w, "<pre class='rust struct'>")?;
3559 render_attributes(w, it, true)?;
3570 document(w, cx, it)?;
3571 let mut fields = s.fields.iter().filter_map(|f| {
3573 clean::StructFieldItem(ref ty) => Some((f, ty)),
3577 if let doctree::Plain = s.struct_type {
3578 if fields.peek().is_some() {
3579 write!(w, "<h2 id='fields' class='fields small-section-header'>
3580 Fields{}<a href='#fields' class='anchor'></a></h2>",
3581 document_non_exhaustive_header(it))?;
3582 document_non_exhaustive(w, it)?;
3583 for (field, ty) in fields {
3584 let id = cx.derive_id(format!("{}.{}",
3585 ItemType::StructField,
3586 field.name.as_ref().unwrap()));
3587 let ns_id = cx.derive_id(format!("{}.{}",
3588 field.name.as_ref().unwrap(),
3589 ItemType::StructField.name_space()));
3590 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3591 <a href=\"#{id}\" class=\"anchor field\"></a>\
3592 <code id=\"{ns_id}\">{name}: {ty}</code>\
3594 item_type = ItemType::StructField,
3597 name = field.name.as_ref().unwrap(),
3599 document(w, cx, field)?;
3603 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3606 fn item_union(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3607 s: &clean::Union) -> fmt::Result {
3608 wrap_into_docblock(w, |w| {
3609 write!(w, "<pre class='rust union'>")?;
3610 render_attributes(w, it, true)?;
3620 document(w, cx, it)?;
3621 let mut fields = s.fields.iter().filter_map(|f| {
3623 clean::StructFieldItem(ref ty) => Some((f, ty)),
3627 if fields.peek().is_some() {
3628 write!(w, "<h2 id='fields' class='fields small-section-header'>
3629 Fields<a href='#fields' class='anchor'></a></h2>")?;
3630 for (field, ty) in fields {
3631 let name = field.name.as_ref().expect("union field name");
3632 let id = format!("{}.{}", ItemType::StructField, name);
3633 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3634 <a href=\"#{id}\" class=\"anchor field\"></a>\
3635 <code>{name}: {ty}</code>\
3639 shortty = ItemType::StructField,
3641 if let Some(stability_class) = field.stability_class() {
3642 write!(w, "<span class='stab {stab}'></span>",
3643 stab = stability_class)?;
3645 document(w, cx, field)?;
3648 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3651 fn item_enum(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
3652 e: &clean::Enum) -> fmt::Result {
3653 wrap_into_docblock(w, |w| {
3654 write!(w, "<pre class='rust enum'>")?;
3655 render_attributes(w, it, true)?;
3656 write!(w, "{}enum {}{}{}",
3657 VisSpace(&it.visibility),
3658 it.name.as_ref().unwrap(),
3660 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3661 if e.variants.is_empty() && !e.variants_stripped {
3662 write!(w, " {{}}")?;
3664 write!(w, " {{\n")?;
3665 for v in &e.variants {
3667 let name = v.name.as_ref().unwrap();
3669 clean::VariantItem(ref var) => {
3671 clean::VariantKind::CLike => write!(w, "{}", name)?,
3672 clean::VariantKind::Tuple(ref tys) => {
3673 write!(w, "{}(", name)?;
3674 for (i, ty) in tys.iter().enumerate() {
3676 write!(w, ", ")?
3678 write!(w, "{}", *ty)?;
3682 clean::VariantKind::Struct(ref s) => {
3698 if e.variants_stripped {
3699 write!(w, " // some variants omitted\n")?;
3706 document(w, cx, it)?;
3707 if !e.variants.is_empty() {
3708 write!(w, "<h2 id='variants' class='variants small-section-header'>
3709 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3710 document_non_exhaustive_header(it))?;
3711 document_non_exhaustive(w, it)?;
3712 for variant in &e.variants {
3713 let id = cx.derive_id(format!("{}.{}",
3715 variant.name.as_ref().unwrap()));
3716 let ns_id = cx.derive_id(format!("{}.{}",
3717 variant.name.as_ref().unwrap(),
3718 ItemType::Variant.name_space()));
3719 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3720 <a href=\"#{id}\" class=\"anchor field\"></a>\
3721 <code id='{ns_id}'>{name}",
3724 name = variant.name.as_ref().unwrap())?;
3725 if let clean::VariantItem(ref var) = variant.inner {
3726 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3728 for (i, ty) in tys.iter().enumerate() {
3730 write!(w, ", ")?;
3732 write!(w, "{}", *ty)?;
3737 write!(w, "</code></span>")?;
3738 document(w, cx, variant)?;
3739 document_non_exhaustive(w, variant)?;
3741 use crate::clean::{Variant, VariantKind};
3742 if let clean::VariantItem(Variant {
3743 kind: VariantKind::Struct(ref s)
3744 }) = variant.inner {
3745 let variant_id = cx.derive_id(format!("{}.{}.fields",
3747 variant.name.as_ref().unwrap()));
3748 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3750 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3751 name = variant.name.as_ref().unwrap())?;
3752 for field in &s.fields {
3753 use crate::clean::StructFieldItem;
3754 if let StructFieldItem(ref ty) = field.inner {
3755 let id = cx.derive_id(format!("variant.{}.field.{}",
3756 variant.name.as_ref().unwrap(),
3757 field.name.as_ref().unwrap()));
3758 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3759 variant.name.as_ref().unwrap(),
3760 ItemType::Variant.name_space(),
3761 field.name.as_ref().unwrap(),
3762 ItemType::StructField.name_space()));
3763 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3764 <a href=\"#{id}\" class=\"anchor field\"></a>\
3765 <code id='{ns_id}'>{f}: {t}\
3769 f = field.name.as_ref().unwrap(),
3771 document(w, cx, field)?;
3774 write!(w, "</div></span>")?;
3776 render_stability_since(w, variant, it)?;
3779 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3783 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3784 let path = attr.path.to_string();
3788 } else if let Some(v) = attr.value_str() {
3789 Some(format!("{} = {:?}", path, v.as_str()))
3790 } else if let Some(values) = attr.meta_item_list() {
3791 let display: Vec<_> = values.iter().filter_map(|attr| {
3792 attr.meta_item().and_then(|mi| render_attribute(mi))
3795 if display.len() > 0 {
3796 Some(format!("{}({})", path, display.join(", ")))
3805 const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
3815 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3816 // left padding. For example:
3818 // #[foo] <----- "top" attribute
3820 // #[bar] <---- not "top" attribute
3823 fn render_attributes(w: &mut dyn fmt::Write, it: &clean::Item, top: bool) -> fmt::Result {
3824 let mut attrs = String::new();
3826 for attr in &it.attrs.other_attrs {
3827 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
3830 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3831 attrs.push_str(&format!("#[{}]\n", s));
3834 if attrs.len() > 0 {
3835 write!(w, "<span class=\"docblock attributes{}\">{}</span>",
3836 if top { " top-attr" } else { "" }, &attrs)?;
3841 fn render_struct(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3842 g: Option<&clean::Generics>,
3843 ty: doctree::StructType,
3844 fields: &[clean::Item],
3846 structhead: bool) -> fmt::Result {
3848 VisSpace(&it.visibility),
3849 if structhead {"struct "} else {""},
3850 it.name.as_ref().unwrap())?;
3851 if let Some(g) = g {
3856 if let Some(g) = g {
3857 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3859 let mut has_visible_fields = false;
3861 for field in fields {
3862 if let clean::StructFieldItem(ref ty) = field.inner {
3863 write!(w, "\n{} {}{}: {},",
3865 VisSpace(&field.visibility),
3866 field.name.as_ref().unwrap(),
3868 has_visible_fields = true;
3872 if has_visible_fields {
3873 if it.has_stripped_fields().unwrap() {
3874 write!(w, "\n{} // some fields omitted", tab)?;
3876 write!(w, "\n{}", tab)?;
3877 } else if it.has_stripped_fields().unwrap() {
3878 // If there are no visible fields we can just display
3879 // `{ /* fields omitted */ }` to save space.
3880 write!(w, " /* fields omitted */ ")?;
3886 for (i, field) in fields.iter().enumerate() {
3891 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3894 clean::StructFieldItem(ref ty) => {
3895 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3901 if let Some(g) = g {
3902 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3907 // Needed for PhantomData.
3908 if let Some(g) = g {
3909 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3917 fn render_union(w: &mut fmt::Formatter<'_>, it: &clean::Item,
3918 g: Option<&clean::Generics>,
3919 fields: &[clean::Item],
3921 structhead: bool) -> fmt::Result {
3923 VisSpace(&it.visibility),
3924 if structhead {"union "} else {""},
3925 it.name.as_ref().unwrap())?;
3926 if let Some(g) = g {
3927 write!(w, "{}", g)?;
3928 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3931 write!(w, " {{\n{}", tab)?;
3932 for field in fields {
3933 if let clean::StructFieldItem(ref ty) = field.inner {
3934 write!(w, " {}{}: {},\n{}",
3935 VisSpace(&field.visibility),
3936 field.name.as_ref().unwrap(),
3942 if it.has_stripped_fields().unwrap() {
3943 write!(w, " // some fields omitted\n{}", tab)?;
3949 #[derive(Copy, Clone)]
3950 enum AssocItemLink<'a> {
3951 Anchor(Option<&'a str>),
3952 GotoSource(DefId, &'a FxHashSet<String>),
3955 impl<'a> AssocItemLink<'a> {
3956 fn anchor(&self, id: &'a String) -> Self {
3958 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3959 ref other => *other,
3964 enum AssocItemRender<'a> {
3966 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3969 #[derive(Copy, Clone, PartialEq)]
3972 ForDeref { mut_: bool },
3975 fn render_assoc_items(w: &mut fmt::Formatter<'_>,
3977 containing_item: &clean::Item,
3979 what: AssocItemRender<'_>) -> fmt::Result {
3981 let v = match c.impls.get(&it) {
3983 None => return Ok(()),
3985 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3986 i.inner_impl().trait_.is_none()
3988 if !non_trait.is_empty() {
3989 let render_mode = match what {
3990 AssocItemRender::All => {
3992 <h2 id='methods' class='small-section-header'>\
3993 Methods<a href='#methods' class='anchor'></a>\
3998 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
4000 <h2 id='deref-methods' class='small-section-header'>\
4001 Methods from {}<Target = {}>\
4002 <a href='#deref-methods' class='anchor'></a>\
4005 RenderMode::ForDeref { mut_: deref_mut_ }
4008 for i in &non_trait {
4009 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
4010 containing_item.stable_since(), true, None, false, true)?;
4013 if let AssocItemRender::DerefFor { .. } = what {
4016 if !traits.is_empty() {
4017 let deref_impl = traits.iter().find(|t| {
4018 t.inner_impl().trait_.def_id() == c.deref_trait_did
4020 if let Some(impl_) = deref_impl {
4021 let has_deref_mut = traits.iter().find(|t| {
4022 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
4024 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
4027 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
4029 .partition(|t| t.inner_impl().synthetic);
4030 let (blanket_impl, concrete) = concrete
4032 .partition(|t| t.inner_impl().blanket_impl.is_some());
4034 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
4036 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
4037 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4038 render_impls(self.0, fmt, &self.1, self.2)
4042 let impls = RendererStruct(cx, concrete, containing_item).to_string();
4043 if !impls.is_empty() {
4045 <h2 id='implementations' class='small-section-header'>\
4046 Trait Implementations<a href='#implementations' class='anchor'></a>\
4048 <div id='implementations-list'>{}</div>", impls)?;
4051 if !synthetic.is_empty() {
4053 <h2 id='synthetic-implementations' class='small-section-header'>\
4054 Auto Trait Implementations\
4055 <a href='#synthetic-implementations' class='anchor'></a>\
4057 <div id='synthetic-implementations-list'>\
4059 render_impls(cx, w, &synthetic, containing_item)?;
4060 write!(w, "</div>")?;
4063 if !blanket_impl.is_empty() {
4065 <h2 id='blanket-implementations' class='small-section-header'>\
4066 Blanket Implementations\
4067 <a href='#blanket-implementations' class='anchor'></a>\
4069 <div id='blanket-implementations-list'>\
4071 render_impls(cx, w, &blanket_impl, containing_item)?;
4072 write!(w, "</div>")?;
4078 fn render_deref_methods(w: &mut fmt::Formatter<'_>, cx: &Context, impl_: &Impl,
4079 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
4080 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
4081 let target = impl_.inner_impl().items.iter().filter_map(|item| {
4083 clean::TypedefItem(ref t, true) => Some(&t.type_),
4086 }).next().expect("Expected associated type binding");
4087 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
4088 deref_mut_: deref_mut };
4089 if let Some(did) = target.def_id() {
4090 render_assoc_items(w, cx, container_item, did, what)
4092 if let Some(prim) = target.primitive_type() {
4093 if let Some(&did) = cache().primitive_locations.get(&prim) {
4094 render_assoc_items(w, cx, container_item, did, what)?;
4101 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
4102 let self_type_opt = match item.inner {
4103 clean::MethodItem(ref method) => method.decl.self_type(),
4104 clean::TyMethodItem(ref method) => method.decl.self_type(),
4108 if let Some(self_ty) = self_type_opt {
4109 let (by_mut_ref, by_box, by_value) = match self_ty {
4110 SelfTy::SelfBorrowed(_, mutability) |
4111 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4112 (mutability == Mutability::Mutable, false, false)
4114 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4115 (false, Some(did) == cache().owned_box_did, false)
4117 SelfTy::SelfValue => (false, false, true),
4118 _ => (false, false, false),
4121 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4127 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4128 let mut out = String::new();
4131 clean::FunctionItem(clean::Function { ref decl, .. }) |
4132 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4133 clean::MethodItem(clean::Method { ref decl, .. }) |
4134 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4135 out = spotlight_decl(decl)?;
4143 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4144 let mut out = String::new();
4145 let mut trait_ = String::new();
4147 if let Some(did) = decl.output.def_id() {
4149 if let Some(impls) = c.impls.get(&did) {
4151 let impl_ = i.inner_impl();
4152 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4155 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4156 <code class=\"content\">",
4158 trait_.push_str(&impl_.for_.to_string());
4161 //use the "where" class here to make it small
4162 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4163 let t_did = impl_.trait_.def_id().unwrap();
4164 for it in &impl_.items {
4165 if let clean::TypedefItem(ref tydef, _) = it.inner {
4166 out.push_str("<span class=\"where fmt-newline\"> ");
4167 assoc_type(&mut out, it, &[],
4169 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
4171 out.push_str(";</span>");
4179 if !out.is_empty() {
4180 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4181 <span class='tooltiptext'>Important traits for {}</span></div>\
4182 <div class=\"content hidden\">",
4184 out.push_str("</code></div></div>");
4190 fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
4191 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
4192 use_absolute: Option<bool>, is_on_foreign_type: bool,
4193 show_default_items: bool) -> fmt::Result {
4194 if render_mode == RenderMode::Normal {
4195 let id = cx.derive_id(match i.inner_impl().trait_ {
4196 Some(ref t) => if is_on_foreign_type {
4197 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
4199 format!("impl-{}", small_url_encode(&format!("{:#}", t)))
4201 None => "impl".to_string(),
4203 if let Some(use_absolute) = use_absolute {
4204 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4205 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4207 for it in &i.inner_impl().items {
4208 if let clean::TypedefItem(ref tydef, _) = it.inner {
4209 write!(w, "<span class=\"where fmt-newline\"> ")?;
4210 assoc_type(w, it, &vec![], Some(&tydef.type_),
4211 AssocItemLink::Anchor(None),
4213 write!(w, ";</span>")?;
4217 write!(w, "</code>")?;
4219 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4223 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4224 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4225 render_stability_since_raw(w, since, outer_version)?;
4226 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4227 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4228 l, "goto source code")?;
4230 write!(w, "</h3>")?;
4231 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4232 let mut ids = cx.id_map.borrow_mut();
4233 write!(w, "<div class='docblock'>{}</div>",
4234 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids),
4235 cx.codes, cx.edition))?;
4239 fn doc_impl_item(w: &mut fmt::Formatter<'_>, cx: &Context, item: &clean::Item,
4240 link: AssocItemLink<'_>, render_mode: RenderMode,
4241 is_default_item: bool, outer_version: Option<&str>,
4242 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4243 let item_type = item.type_();
4244 let name = item.name.as_ref().unwrap();
4246 let render_method_item: bool = match render_mode {
4247 RenderMode::Normal => true,
4248 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4251 let (is_hidden, extra_class) = if trait_.is_none() ||
4252 item.doc_value().is_some() ||
4253 item.inner.is_associated() {
4259 clean::MethodItem(clean::Method { ref decl, .. }) |
4260 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4261 // Only render when the method is not static or we allow static methods
4262 if render_method_item {
4263 let id = cx.derive_id(format!("{}.{}", item_type, name));
4264 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4265 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4266 write!(w, "{}", spotlight_decl(decl)?)?;
4267 write!(w, "<code id='{}'>", ns_id)?;
4268 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4269 write!(w, "</code>")?;
4270 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4271 if let Some(l) = (Item { cx, item }).src_href() {
4272 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4273 l, "goto source code")?;
4275 write!(w, "</h4>")?;
4278 clean::TypedefItem(ref tydef, _) => {
4279 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
4280 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4281 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4282 write!(w, "<code id='{}'>", ns_id)?;
4283 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "")?;
4284 write!(w, "</code></h4>")?;
4286 clean::AssocConstItem(ref ty, ref default) => {
4287 let id = cx.derive_id(format!("{}.{}", item_type, name));
4288 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4289 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4290 write!(w, "<code id='{}'>", ns_id)?;
4291 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "")?;
4292 write!(w, "</code>")?;
4293 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4294 if let Some(l) = (Item { cx, item }).src_href() {
4295 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4296 l, "goto source code")?;
4298 write!(w, "</h4>")?;
4300 clean::AssocTypeItem(ref bounds, ref default) => {
4301 let id = cx.derive_id(format!("{}.{}", item_type, name));
4302 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4303 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4304 write!(w, "<code id='{}'>", ns_id)?;
4305 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "")?;
4306 write!(w, "</code></h4>")?;
4308 clean::StrippedItem(..) => return Ok(()),
4309 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4312 if render_method_item || render_mode == RenderMode::Normal {
4313 if !is_default_item {
4314 if let Some(t) = trait_ {
4315 // The trait item may have been stripped so we might not
4316 // find any documentation or stability for it.
4317 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4318 // We need the stability of the item from the trait
4319 // because impls can't have a stability.
4320 document_stability(w, cx, it, is_hidden)?;
4321 if item.doc_value().is_some() {
4322 document_full(w, item, cx, "", is_hidden)?;
4323 } else if show_def_docs {
4324 // In case the item isn't documented,
4325 // provide short documentation from the trait.
4326 document_short(w, cx, it, link, "", is_hidden)?;
4330 document_stability(w, cx, item, is_hidden)?;
4332 document_full(w, item, cx, "", is_hidden)?;
4336 document_stability(w, cx, item, is_hidden)?;
4338 document_short(w, cx, item, link, "", is_hidden)?;
4345 let traits = &cache().traits;
4346 let trait_ = i.trait_did().map(|did| &traits[&did]);
4348 write!(w, "<div class='impl-items'>")?;
4349 for trait_item in &i.inner_impl().items {
4350 doc_impl_item(w, cx, trait_item, link, render_mode,
4351 false, outer_version, trait_, show_def_docs)?;
4354 fn render_default_items(w: &mut fmt::Formatter<'_>,
4358 render_mode: RenderMode,
4359 outer_version: Option<&str>,
4360 show_def_docs: bool) -> fmt::Result {
4361 for trait_item in &t.items {
4362 let n = trait_item.name.clone();
4363 if i.items.iter().find(|m| m.name == n).is_some() {
4366 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4367 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4369 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4370 outer_version, None, show_def_docs)?;
4375 // If we've implemented a trait, then also emit documentation for all
4376 // default items which weren't overridden in the implementation block.
4377 // We don't emit documentation for default items if they appear in the
4378 // Implementations on Foreign Types or Implementors sections.
4379 if show_default_items {
4380 if let Some(t) = trait_ {
4381 render_default_items(w, cx, t, &i.inner_impl(),
4382 render_mode, outer_version, show_def_docs)?;
4385 write!(w, "</div>")?;
4390 fn item_existential(
4391 w: &mut fmt::Formatter<'_>,
4394 t: &clean::Existential,
4396 write!(w, "<pre class='rust existential'>")?;
4397 render_attributes(w, it, false)?;
4398 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4399 it.name.as_ref().unwrap(),
4401 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4402 bounds = bounds(&t.bounds, false))?;
4404 document(w, cx, it)?;
4406 // Render any items associated directly to this alias, as otherwise they
4407 // won't be visible anywhere in the docs. It would be nice to also show
4408 // associated items from the aliased type (see discussion in #32077), but
4409 // we need #14072 to make sense of the generics.
4410 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4413 fn item_trait_alias(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4414 t: &clean::TraitAlias) -> fmt::Result {
4415 write!(w, "<pre class='rust trait-alias'>")?;
4416 render_attributes(w, it, false)?;
4417 write!(w, "trait {}{}{} = {};</pre>",
4418 it.name.as_ref().unwrap(),
4420 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4421 bounds(&t.bounds, true))?;
4423 document(w, cx, it)?;
4425 // Render any items associated directly to this alias, as otherwise they
4426 // won't be visible anywhere in the docs. It would be nice to also show
4427 // associated items from the aliased type (see discussion in #32077), but
4428 // we need #14072 to make sense of the generics.
4429 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4432 fn item_typedef(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
4433 t: &clean::Typedef) -> fmt::Result {
4434 write!(w, "<pre class='rust typedef'>")?;
4435 render_attributes(w, it, false)?;
4436 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4437 it.name.as_ref().unwrap(),
4439 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4442 document(w, cx, it)?;
4444 // Render any items associated directly to this alias, as otherwise they
4445 // won't be visible anywhere in the docs. It would be nice to also show
4446 // associated items from the aliased type (see discussion in #32077), but
4447 // we need #14072 to make sense of the generics.
4448 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4451 fn item_foreign_type(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item) -> fmt::Result {
4452 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4453 render_attributes(w, it, false)?;
4456 " {}type {};\n}}</pre>",
4457 VisSpace(&it.visibility),
4458 it.name.as_ref().unwrap(),
4461 document(w, cx, it)?;
4463 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4466 impl<'a> fmt::Display for Sidebar<'a> {
4467 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4470 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4472 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4473 || it.is_enum() || it.is_mod() || it.is_typedef() {
4474 write!(fmt, "<p class='location'>{}{}</p>",
4476 clean::StructItem(..) => "Struct ",
4477 clean::TraitItem(..) => "Trait ",
4478 clean::PrimitiveItem(..) => "Primitive Type ",
4479 clean::UnionItem(..) => "Union ",
4480 clean::EnumItem(..) => "Enum ",
4481 clean::TypedefItem(..) => "Type Definition ",
4482 clean::ForeignTypeItem => "Foreign Type ",
4483 clean::ModuleItem(..) => if it.is_crate() {
4490 it.name.as_ref().unwrap())?;
4494 if let Some(ref version) = cache().crate_version {
4496 "<div class='block version'>\
4503 write!(fmt, "<div class=\"sidebar-elems\">")?;
4505 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4506 it.name.as_ref().expect("crates always have a name"))?;
4509 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4510 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4511 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4512 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4513 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4514 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4515 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4516 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4520 // The sidebar is designed to display sibling functions, modules and
4521 // other miscellaneous information. since there are lots of sibling
4522 // items (and that causes quadratic growth in large modules),
4523 // we refactor common parts into a shared JavaScript file per module.
4524 // still, we don't move everything into JS because we want to preserve
4525 // as much HTML as possible in order to allow non-JS-enabled browsers
4526 // to navigate the documentation (though slightly inefficiently).
4528 write!(fmt, "<p class='location'>")?;
4529 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4531 write!(fmt, "::<wbr>")?;
4533 write!(fmt, "<a href='{}index.html'>{}</a>",
4534 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4537 write!(fmt, "</p>")?;
4539 // Sidebar refers to the enclosing module, not this module.
4540 let relpath = if it.is_mod() { "../" } else { "" };
4542 "<script>window.sidebarCurrent = {{\
4547 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4548 ty = it.type_().css_class(),
4551 // There is no sidebar-items.js beyond the crate root path
4552 // FIXME maybe dynamic crate loading can be merged here
4554 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4557 // Closes sidebar-elems div.
4558 write!(fmt, "</div>")?;
4564 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4565 if used_links.insert(url.clone()) {
4569 while used_links.insert(format!("{}-{}", url, add)) == false {
4572 format!("{}-{}", url, add)
4578 used_links: &mut FxHashSet<String>,
4580 i.items.iter().filter_map(|item| {
4582 // Maybe check with clean::Visibility::Public as well?
4583 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4584 if !for_deref || should_render_item(item, false) {
4585 Some(format!("<a href=\"#{}\">{}</a>",
4586 get_next_url(used_links, format!("method.{}", name)),
4594 }).collect::<Vec<_>>()
4597 // The point is to url encode any potential character from a type with genericity.
4598 fn small_url_encode(s: &str) -> String {
4599 s.replace("<", "%3C")
4600 .replace(">", "%3E")
4601 .replace(" ", "%20")
4602 .replace("?", "%3F")
4603 .replace("'", "%27")
4604 .replace("&", "%26")
4605 .replace(",", "%2C")
4606 .replace(":", "%3A")
4607 .replace(";", "%3B")
4608 .replace("[", "%5B")
4609 .replace("]", "%5D")
4610 .replace("\"", "%22")
4613 fn sidebar_assoc_items(it: &clean::Item) -> String {
4614 let mut out = String::new();
4616 if let Some(v) = c.impls.get(&it.def_id) {
4617 let mut used_links = FxHashSet::default();
4620 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4621 let mut ret = v.iter()
4622 .filter(|i| i.inner_impl().trait_.is_none())
4623 .flat_map(move |i| get_methods(i.inner_impl(),
4625 &mut used_links_bor.borrow_mut()))
4626 .collect::<Vec<_>>();
4627 // We want links' order to be reproducible so we don't use unstable sort.
4629 if !ret.is_empty() {
4630 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4631 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4635 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4636 if let Some(impl_) = v.iter()
4637 .filter(|i| i.inner_impl().trait_.is_some())
4638 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4639 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4641 clean::TypedefItem(ref t, true) => Some(&t.type_),
4645 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4646 c.primitive_locations.get(&prim).cloned()
4647 })).and_then(|did| c.impls.get(&did));
4648 if let Some(impls) = inner_impl {
4649 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4650 out.push_str(&format!("Methods from {}<Target={}>",
4651 Escape(&format!("{:#}",
4652 impl_.inner_impl().trait_.as_ref().unwrap())),
4653 Escape(&format!("{:#}", target))));
4654 out.push_str("</a>");
4655 let mut ret = impls.iter()
4656 .filter(|i| i.inner_impl().trait_.is_none())
4657 .flat_map(|i| get_methods(i.inner_impl(),
4660 .collect::<Vec<_>>();
4661 // We want links' order to be reproducible so we don't use unstable sort.
4663 if !ret.is_empty() {
4664 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4670 let format_impls = |impls: Vec<&Impl>| {
4671 let mut links = FxHashSet::default();
4673 let mut ret = impls.iter()
4675 let is_negative_impl = is_negative_impl(i.inner_impl());
4676 if let Some(ref i) = i.inner_impl().trait_ {
4677 let i_display = format!("{:#}", i);
4678 let out = Escape(&i_display);
4679 let encoded = small_url_encode(&format!("{:#}", i));
4680 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4682 if is_negative_impl { "!" } else { "" },
4684 if links.insert(generated.clone()) {
4693 .collect::<Vec<String>>();
4698 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4700 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4701 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4703 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4705 let concrete_format = format_impls(concrete);
4706 let synthetic_format = format_impls(synthetic);
4707 let blanket_format = format_impls(blanket_impl);
4709 if !concrete_format.is_empty() {
4710 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4711 Trait Implementations</a>");
4712 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4715 if !synthetic_format.is_empty() {
4716 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4717 Auto Trait Implementations</a>");
4718 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4721 if !blanket_format.is_empty() {
4722 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4723 Blanket Implementations</a>");
4724 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4732 fn sidebar_struct(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4733 s: &clean::Struct) -> fmt::Result {
4734 let mut sidebar = String::new();
4735 let fields = get_struct_fields_name(&s.fields);
4737 if !fields.is_empty() {
4738 if let doctree::Plain = s.struct_type {
4739 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4740 <div class=\"sidebar-links\">{}</div>", fields));
4744 sidebar.push_str(&sidebar_assoc_items(it));
4746 if !sidebar.is_empty() {
4747 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4752 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4753 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_, for_))
4756 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4758 clean::ItemEnum::ImplItem(ref i) => {
4759 if let Some(ref trait_) = i.trait_ {
4760 Some((format!("{:#}", i.for_), get_id_for_impl_on_foreign_type(&i.for_, trait_)))
4769 fn is_negative_impl(i: &clean::Impl) -> bool {
4770 i.polarity == Some(clean::ImplPolarity::Negative)
4773 fn sidebar_trait(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4774 t: &clean::Trait) -> fmt::Result {
4775 let mut sidebar = String::new();
4781 Some(ref name) if m.is_associated_type() => {
4782 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4788 .collect::<String>();
4789 let consts = t.items
4793 Some(ref name) if m.is_associated_const() => {
4794 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4800 .collect::<String>();
4801 let mut required = t.items
4805 Some(ref name) if m.is_ty_method() => {
4806 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4812 .collect::<Vec<String>>();
4813 let mut provided = t.items
4817 Some(ref name) if m.is_method() => {
4818 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4823 .collect::<Vec<String>>();
4825 if !types.is_empty() {
4826 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4827 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4830 if !consts.is_empty() {
4831 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4832 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4835 if !required.is_empty() {
4837 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4838 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4839 required.join("")));
4841 if !provided.is_empty() {
4843 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4844 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4845 provided.join("")));
4850 if let Some(implementors) = c.implementors.get(&it.def_id) {
4851 let mut res = implementors.iter()
4852 .filter(|i| i.inner_impl().for_.def_id()
4853 .map_or(false, |d| !c.paths.contains_key(&d)))
4855 match extract_for_impl_name(&i.impl_item) {
4856 Some((ref name, ref id)) => {
4857 Some(format!("<a href=\"#{}\">{}</a>",
4864 .collect::<Vec<String>>();
4865 if !res.is_empty() {
4867 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4868 Implementations on Foreign Types</a><div \
4869 class=\"sidebar-links\">{}</div>",
4874 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4876 sidebar.push_str("<a class=\"sidebar-title\" \
4877 href=\"#synthetic-implementors\">Auto Implementors</a>");
4880 sidebar.push_str(&sidebar_assoc_items(it));
4882 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4885 fn sidebar_primitive(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4886 _p: &clean::PrimitiveType) -> fmt::Result {
4887 let sidebar = sidebar_assoc_items(it);
4889 if !sidebar.is_empty() {
4890 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4895 fn sidebar_typedef(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4896 _t: &clean::Typedef) -> fmt::Result {
4897 let sidebar = sidebar_assoc_items(it);
4899 if !sidebar.is_empty() {
4900 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4905 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4907 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4912 .filter_map(|f| match f.name {
4913 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4914 {name}</a>", name=name)),
4920 fn sidebar_union(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4921 u: &clean::Union) -> fmt::Result {
4922 let mut sidebar = String::new();
4923 let fields = get_struct_fields_name(&u.fields);
4925 if !fields.is_empty() {
4926 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4927 <div class=\"sidebar-links\">{}</div>", fields));
4930 sidebar.push_str(&sidebar_assoc_items(it));
4932 if !sidebar.is_empty() {
4933 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4938 fn sidebar_enum(fmt: &mut fmt::Formatter<'_>, it: &clean::Item,
4939 e: &clean::Enum) -> fmt::Result {
4940 let mut sidebar = String::new();
4942 let variants = e.variants.iter()
4943 .filter_map(|v| match v.name {
4944 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4945 </a>", name = name)),
4948 .collect::<String>();
4949 if !variants.is_empty() {
4950 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4951 <div class=\"sidebar-links\">{}</div>", variants));
4954 sidebar.push_str(&sidebar_assoc_items(it));
4956 if !sidebar.is_empty() {
4957 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4962 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4964 ItemType::ExternCrate |
4965 ItemType::Import => ("reexports", "Re-exports"),
4966 ItemType::Module => ("modules", "Modules"),
4967 ItemType::Struct => ("structs", "Structs"),
4968 ItemType::Union => ("unions", "Unions"),
4969 ItemType::Enum => ("enums", "Enums"),
4970 ItemType::Function => ("functions", "Functions"),
4971 ItemType::Typedef => ("types", "Type Definitions"),
4972 ItemType::Static => ("statics", "Statics"),
4973 ItemType::Constant => ("constants", "Constants"),
4974 ItemType::Trait => ("traits", "Traits"),
4975 ItemType::Impl => ("impls", "Implementations"),
4976 ItemType::TyMethod => ("tymethods", "Type Methods"),
4977 ItemType::Method => ("methods", "Methods"),
4978 ItemType::StructField => ("fields", "Struct Fields"),
4979 ItemType::Variant => ("variants", "Variants"),
4980 ItemType::Macro => ("macros", "Macros"),
4981 ItemType::Primitive => ("primitives", "Primitive Types"),
4982 ItemType::AssocType => ("associated-types", "Associated Types"),
4983 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4984 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4985 ItemType::Keyword => ("keywords", "Keywords"),
4986 ItemType::Existential => ("existentials", "Existentials"),
4987 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4988 ItemType::ProcDerive => ("derives", "Derive Macros"),
4989 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4993 fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item,
4994 items: &[clean::Item]) -> fmt::Result {
4995 let mut sidebar = String::new();
4997 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4998 it.type_() == ItemType::Import) {
4999 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
5001 name = "Re-exports"));
5004 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
5005 // to print its headings
5006 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
5007 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
5008 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
5009 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
5010 ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType] {
5011 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
5012 let (short, name) = item_ty_to_strs(&myty);
5013 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
5019 if !sidebar.is_empty() {
5020 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
5025 fn sidebar_foreign_type(fmt: &mut fmt::Formatter<'_>, it: &clean::Item) -> fmt::Result {
5026 let sidebar = sidebar_assoc_items(it);
5027 if !sidebar.is_empty() {
5028 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
5033 impl<'a> fmt::Display for Source<'a> {
5034 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5035 let Source(s) = *self;
5036 let lines = s.lines().count();
5038 let mut tmp = lines;
5043 write!(fmt, "<pre class=\"line-numbers\">")?;
5044 for i in 1..=lines {
5045 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
5047 write!(fmt, "</pre>")?;
5049 highlight::render_with_highlighting(s, None, None, None))?;
5054 fn item_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item,
5055 t: &clean::Macro) -> fmt::Result {
5056 wrap_into_docblock(w, |w| {
5057 w.write_str(&highlight::render_with_highlighting(&t.source,
5065 fn item_proc_macro(w: &mut fmt::Formatter<'_>, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
5068 let name = it.name.as_ref().expect("proc-macros always have names");
5070 MacroKind::Bang => {
5071 write!(w, "<pre class='rust macro'>")?;
5072 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
5073 write!(w, "</pre>")?;
5075 MacroKind::Attr => {
5076 write!(w, "<pre class='rust attr'>")?;
5077 write!(w, "#[{}]", name)?;
5078 write!(w, "</pre>")?;
5080 MacroKind::Derive => {
5081 write!(w, "<pre class='rust derive'>")?;
5082 write!(w, "#[derive({})]", name)?;
5083 if !m.helpers.is_empty() {
5084 writeln!(w, "\n{{")?;
5085 writeln!(w, " // Attributes available to this derive:")?;
5086 for attr in &m.helpers {
5087 writeln!(w, " #[{}]", attr)?;
5091 write!(w, "</pre>")?;
5097 fn item_primitive(w: &mut fmt::Formatter<'_>, cx: &Context,
5099 _p: &clean::PrimitiveType) -> fmt::Result {
5100 document(w, cx, it)?;
5101 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
5104 fn item_keyword(w: &mut fmt::Formatter<'_>, cx: &Context,
5106 _p: &str) -> fmt::Result {
5110 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
5112 fn make_item_keywords(it: &clean::Item) -> String {
5113 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
5116 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
5117 let (all_types, ret_types) = match item.inner {
5118 clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
5119 clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
5120 clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
5124 let inputs = all_types.iter().map(|arg| {
5125 get_index_type(&arg)
5126 }).filter(|a| a.name.is_some()).collect();
5127 let output = ret_types.iter().map(|arg| {
5128 get_index_type(&arg)
5129 }).filter(|a| a.name.is_some()).collect::<Vec<_>>();
5130 let output = if output.is_empty() {
5136 Some(IndexItemFunctionType { inputs, output })
5139 fn get_index_type(clean_type: &clean::Type) -> Type {
5141 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5142 generics: get_generics(clean_type),
5147 /// Returns a list of all paths used in the type.
5148 /// This is used to help deduplicate imported impls
5149 /// for reexported types. If any of the contained
5150 /// types are re-exported, we don't use the corresponding
5151 /// entry from the js file, as inlining will have already
5152 /// picked up the impl
5153 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5154 let mut out = Vec::new();
5155 let mut visited = FxHashSet::default();
5156 let mut work = VecDeque::new();
5157 let cache = cache();
5159 work.push_back(first_ty);
5161 while let Some(ty) = work.pop_front() {
5162 if !visited.insert(ty.clone()) {
5167 clean::Type::ResolvedPath { did, .. } => {
5168 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5169 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5173 out.push(path.join("::"));
5179 clean::Type::Tuple(tys) => {
5180 work.extend(tys.into_iter());
5182 clean::Type::Slice(ty) => {
5183 work.push_back(*ty);
5185 clean::Type::Array(ty, _) => {
5186 work.push_back(*ty);
5188 clean::Type::RawPointer(_, ty) => {
5189 work.push_back(*ty);
5191 clean::Type::BorrowedRef { type_, .. } => {
5192 work.push_back(*type_);
5194 clean::Type::QPath { self_type, trait_, .. } => {
5195 work.push_back(*self_type);
5196 work.push_back(*trait_);
5204 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5206 clean::ResolvedPath { ref path, .. } => {
5207 let segments = &path.segments;
5208 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5209 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5210 clean_type, accept_generic
5212 Some(path_segment.name.clone())
5214 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5215 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5216 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5217 // FIXME: add all from clean::Type.
5222 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5223 clean_type.generics()
5225 let r = types.iter()
5226 .filter_map(|t| get_index_type_name(t, false))
5227 .map(|s| s.to_ascii_lowercase())
5228 .collect::<Vec<_>>();
5237 pub fn cache() -> Arc<Cache> {
5238 CACHE_KEY.with(|c| c.borrow().clone())
5243 fn test_name_key() {
5244 assert_eq!(name_key("0"), ("", 0, 1));
5245 assert_eq!(name_key("123"), ("", 123, 0));
5246 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5247 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5248 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5249 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5250 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5251 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5256 fn test_name_sorting() {
5257 let names = ["Apple",
5259 "Fruit", "Fruit0", "Fruit00",
5260 "Fruit1", "Fruit01",
5261 "Fruit2", "Fruit02",
5266 let mut sorted = names.to_owned();
5267 sorted.sort_by_key(|&s| name_key(s));
5268 assert_eq!(names, sorted);