1 //! Rustdoc's HTML Rendering module
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
26 pub use self::ExternalLocation::*;
29 use std::cell::RefCell;
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
34 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
36 use std::fs::{self, File, OpenOptions};
37 use std::io::prelude::*;
38 use std::io::{self, BufWriter, BufReader};
40 use std::path::{PathBuf, Path, Component};
46 use serialize::json::{ToJson, Json, as_json};
48 use syntax::ext::base::MacroKind;
49 use syntax::source_map::FileName;
50 use syntax::feature_gate::UnstableFeatures;
51 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
52 use rustc::middle::privacy::AccessLevels;
53 use rustc::middle::stability;
55 use rustc::util::nodemap::{FxHashMap, FxHashSet};
56 use rustc_data_structures::flock;
58 use clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
59 use config::RenderOptions;
62 use html::escape::Escape;
63 use html::format::{AsyncSpace, ConstnessSpace};
64 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
65 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
66 use html::format::fmt_impl_for_trait_page;
67 use html::item_type::ItemType;
68 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
69 use html::{highlight, layout, static_files};
73 /// A pair of name and its optional document.
74 pub type NameDoc = (String, Option<String>);
76 /// Major driving force in all rustdoc rendering. This contains information
77 /// about where in the tree-like hierarchy rendering is occurring and controls
78 /// how the current page is being rendered.
80 /// It is intended that this context is a lightweight object which can be fairly
81 /// easily cloned because it is cloned per work-job (about once per item in the
85 /// Current hierarchy of components leading down to what's currently being
87 pub current: Vec<String>,
88 /// The current destination folder of where HTML artifacts should be placed.
89 /// This changes as the context descends into the module hierarchy.
91 /// A flag, which when `true`, will render pages which redirect to the
92 /// real location of an item. This is used to allow external links to
93 /// publicly reused items to redirect to the right location.
94 pub render_redirect_pages: bool,
95 pub codes: ErrorCodes,
96 /// The map used to ensure all generated 'id=' attributes are unique.
97 id_map: Rc<RefCell<IdMap>>,
98 pub shared: Arc<SharedContext>,
101 struct SharedContext {
102 /// The path to the crate root source minus the file name.
103 /// Used for simplifying paths to the highlighted source code files.
104 pub src_root: PathBuf,
105 /// This describes the layout of each page, and is not modified after
106 /// creation of the context (contains info like the favicon and added html).
107 pub layout: layout::Layout,
108 /// This flag indicates whether `[src]` links should be generated or not. If
109 /// the source files are present in the html rendering, then this will be
111 pub include_sources: bool,
112 /// The local file sources we've emitted and their respective url-paths.
113 pub local_sources: FxHashMap<PathBuf, String>,
114 /// All the passes that were run on this crate.
115 pub passes: FxHashSet<String>,
116 /// The base-URL of the issue tracker for when an item has been tagged with
118 pub issue_tracker_base_url: Option<String>,
119 /// The given user css file which allow to customize the generated
120 /// documentation theme.
121 pub css_file_extension: Option<PathBuf>,
122 /// The directories that have already been created in this doc run. Used to reduce the number
123 /// of spurious `create_dir_all` calls.
124 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
125 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
126 /// should be ordered alphabetically or in order of appearance (in the source code).
127 pub sort_modules_alphabetically: bool,
128 /// Additional themes to be added to the generated docs.
129 pub themes: Vec<PathBuf>,
130 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
132 pub resource_suffix: String,
133 /// Optional path string to be used to load static files on output pages. If not set, uses
134 /// combinations of `../` to reach the documentation root.
135 pub static_root_path: Option<String>,
136 /// If false, the `select` element to have search filtering by crates on rendered docs
137 /// won't be generated.
138 pub generate_search_filter: bool,
142 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
143 let mut dirs = self.created_dirs.borrow_mut();
144 if !dirs.contains(dst) {
145 fs::create_dir_all(dst)?;
146 dirs.insert(dst.to_path_buf());
154 /// Returns whether the `collapse-docs` pass was run on this crate.
155 pub fn was_collapsed(&self) -> bool {
156 self.passes.contains("collapse-docs")
159 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
160 /// `collapsed_doc_value` of the given item.
161 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
162 if self.was_collapsed() {
163 item.collapsed_doc_value().map(|s| s.into())
165 item.doc_value().map(|s| s.into())
170 /// Indicates where an external crate can be found.
171 pub enum ExternalLocation {
172 /// Remote URL root of the external crate
174 /// This external crate can be found in the local doc/ folder
176 /// The external crate could not be found.
180 /// Metadata about implementations for a type or trait.
181 #[derive(Clone, Debug)]
183 pub impl_item: clean::Item,
187 fn inner_impl(&self) -> &clean::Impl {
188 match self.impl_item.inner {
189 clean::ImplItem(ref impl_) => impl_,
190 _ => panic!("non-impl item found in impl")
194 fn trait_did(&self) -> Option<DefId> {
195 self.inner_impl().trait_.def_id()
202 pub error: io::Error,
205 impl error::Error for Error {
206 fn description(&self) -> &str {
207 self.error.description()
211 impl Display for Error {
212 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
213 write!(f, "\"{}\": {}", self.file.display(), self.error)
218 pub fn new(e: io::Error, file: &Path) -> Error {
220 file: file.to_path_buf(),
226 macro_rules! try_none {
227 ($e:expr, $file:expr) => ({
231 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
237 macro_rules! try_err {
238 ($e:expr, $file:expr) => ({
241 Err(e) => return Err(Error::new(e, $file)),
246 /// This cache is used to store information about the `clean::Crate` being
247 /// rendered in order to provide more useful documentation. This contains
248 /// information like all implementors of a trait, all traits a type implements,
249 /// documentation for all known traits, etc.
251 /// This structure purposefully does not implement `Clone` because it's intended
252 /// to be a fairly large and expensive structure to clone. Instead this adheres
253 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
254 /// rendering threads.
257 /// Mapping of typaram ids to the name of the type parameter. This is used
258 /// when pretty-printing a type (so pretty printing doesn't have to
259 /// painfully maintain a context like this)
260 pub typarams: FxHashMap<DefId, String>,
262 /// Maps a type id to all known implementations for that type. This is only
263 /// recognized for intra-crate `ResolvedPath` types, and is used to print
264 /// out extra documentation on the page of an enum/struct.
266 /// The values of the map are a list of implementations and documentation
267 /// found on that implementation.
268 pub impls: FxHashMap<DefId, Vec<Impl>>,
270 /// Maintains a mapping of local crate node ids to the fully qualified name
271 /// and "short type description" of that node. This is used when generating
272 /// URLs when a type is being linked to. External paths are not located in
273 /// this map because the `External` type itself has all the information
275 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
277 /// Similar to `paths`, but only holds external paths. This is only used for
278 /// generating explicit hyperlinks to other crates.
279 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
281 /// Maps local def ids of exported types to fully qualified paths.
282 /// Unlike 'paths', this mapping ignores any renames that occur
283 /// due to 'use' statements.
285 /// This map is used when writing out the special 'implementors'
286 /// javascript file. By using the exact path that the type
287 /// is declared with, we ensure that each path will be identical
288 /// to the path used if the corresponding type is inlined. By
289 /// doing this, we can detect duplicate impls on a trait page, and only display
290 /// the impl for the inlined type.
291 pub exact_paths: FxHashMap<DefId, Vec<String>>,
293 /// This map contains information about all known traits of this crate.
294 /// Implementations of a crate should inherit the documentation of the
295 /// parent trait if no extra documentation is specified, and default methods
296 /// should show up in documentation about trait implementations.
297 pub traits: FxHashMap<DefId, clean::Trait>,
299 /// When rendering traits, it's often useful to be able to list all
300 /// implementors of the trait, and this mapping is exactly, that: a mapping
301 /// of trait ids to the list of known implementors of the trait
302 pub implementors: FxHashMap<DefId, Vec<Impl>>,
304 /// Cache of where external crate documentation can be found.
305 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
307 /// Cache of where documentation for primitives can be found.
308 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
310 // Note that external items for which `doc(hidden)` applies to are shown as
311 // non-reachable while local items aren't. This is because we're reusing
312 // the access levels from crateanalysis.
313 pub access_levels: AccessLevels<DefId>,
315 /// The version of the crate being documented, if given from the `--crate-version` flag.
316 pub crate_version: Option<String>,
318 // Private fields only used when initially crawling a crate to build a cache
321 parent_stack: Vec<DefId>,
322 parent_is_trait_impl: bool,
323 search_index: Vec<IndexItem>,
325 deref_trait_did: Option<DefId>,
326 deref_mut_trait_did: Option<DefId>,
327 owned_box_did: Option<DefId>,
328 masked_crates: FxHashSet<CrateNum>,
330 // In rare case where a structure is defined in one module but implemented
331 // in another, if the implementing module is parsed before defining module,
332 // then the fully qualified name of the structure isn't presented in `paths`
333 // yet when its implementation methods are being indexed. Caches such methods
334 // and their parent id here and indexes them at the end of crate parsing.
335 orphan_impl_items: Vec<(DefId, clean::Item)>,
337 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
338 // even though the trait itself is not exported. This can happen if a trait
339 // was defined in function/expression scope, since the impl will be picked
340 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
341 // crawl. In order to prevent crashes when looking for spotlight traits or
342 // when gathering trait documentation on a type, hold impls here while
343 // folding and add them to the cache later on if we find the trait.
344 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
346 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
347 /// we need the alias element to have an array of items.
348 aliases: FxHashMap<String, Vec<IndexItem>>,
351 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
352 /// Later on moved into `CACHE_KEY`.
354 pub struct RenderInfo {
355 pub inlined: FxHashSet<DefId>,
356 pub external_paths: ::core::ExternalPaths,
357 pub external_typarams: FxHashMap<DefId, String>,
358 pub exact_paths: FxHashMap<DefId, Vec<String>>,
359 pub access_levels: AccessLevels<DefId>,
360 pub deref_trait_did: Option<DefId>,
361 pub deref_mut_trait_did: Option<DefId>,
362 pub owned_box_did: Option<DefId>,
365 /// Helper struct to render all source code to HTML pages
366 struct SourceCollector<'a> {
367 scx: &'a mut SharedContext,
369 /// Root destination to place all HTML output into
373 /// Wrapper struct to render the source code of a file. This will do things like
374 /// adding line numbers to the left-hand side.
375 struct Source<'a>(&'a str);
377 // Helper structs for rendering items/sidebars and carrying along contextual
380 #[derive(Copy, Clone)]
383 item: &'a clean::Item,
386 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
388 /// Struct representing one entry in the JS search index. These are all emitted
389 /// by hand to a large JS file at the end of cache-creation.
396 parent: Option<DefId>,
397 parent_idx: Option<usize>,
398 search_type: Option<IndexItemFunctionType>,
401 impl ToJson for IndexItem {
402 fn to_json(&self) -> Json {
403 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
405 let mut data = Vec::with_capacity(6);
406 data.push((self.ty as usize).to_json());
407 data.push(self.name.to_json());
408 data.push(self.path.to_json());
409 data.push(self.desc.to_json());
410 data.push(self.parent_idx.to_json());
411 data.push(self.search_type.to_json());
417 /// A type used for the search index.
420 name: Option<String>,
421 generics: Option<Vec<String>>,
424 impl ToJson for Type {
425 fn to_json(&self) -> Json {
428 let mut data = Vec::with_capacity(2);
429 data.push(name.to_json());
430 if let Some(ref generics) = self.generics {
431 data.push(generics.to_json());
440 /// Full type of functions/methods in the search index.
442 struct IndexItemFunctionType {
444 output: Option<Type>,
447 impl ToJson for IndexItemFunctionType {
448 fn to_json(&self) -> Json {
449 // If we couldn't figure out a type, just write `null`.
450 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
453 let mut data = Vec::with_capacity(2);
454 data.push(self.inputs.to_json());
455 if let Some(ref output) = self.output {
456 data.push(output.to_json());
463 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
464 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
466 pub fn initial_ids() -> Vec<String> {
478 "synthetic-implementors",
480 "synthetic-implementors-list",
484 ].into_iter().map(|id| (String::from(*id))).collect()
487 /// Generates the documentation for `crate` into the directory `dst`
488 pub fn run(mut krate: clean::Crate,
489 options: RenderOptions,
490 passes: FxHashSet<String>,
491 renderinfo: RenderInfo,
492 diag: &errors::Handler) -> Result<(), Error> {
493 // need to save a copy of the options for rendering the index page
494 let md_opts = options.clone();
500 sort_modules_alphabetically,
503 extern_html_root_urls,
506 generate_search_filter,
510 let src_root = match krate.src {
511 FileName::Real(ref p) => match p.parent() {
512 Some(p) => p.to_path_buf(),
513 None => PathBuf::new(),
517 let mut scx = SharedContext {
520 include_sources: true,
521 local_sources: Default::default(),
522 issue_tracker_base_url: None,
523 layout: layout::Layout {
525 favicon: String::new(),
527 krate: krate.name.clone(),
529 css_file_extension: extension_css,
530 created_dirs: Default::default(),
531 sort_modules_alphabetically,
535 generate_search_filter,
538 // If user passed in `--playground-url` arg, we fill in crate name here
539 if let Some(url) = playground_url {
540 markdown::PLAYGROUND.with(|slot| {
541 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
545 // Crawl the crate attributes looking for attributes which control how we're
546 // going to emit HTML
547 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
548 for attr in attrs.lists("doc") {
549 let name = attr.name().map(|s| s.as_str());
550 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
551 (Some("html_favicon_url"), Some(s)) => {
552 scx.layout.favicon = s.to_string();
554 (Some("html_logo_url"), Some(s)) => {
555 scx.layout.logo = s.to_string();
557 (Some("html_playground_url"), Some(s)) => {
558 markdown::PLAYGROUND.with(|slot| {
559 let name = krate.name.clone();
560 *slot.borrow_mut() = Some((Some(name), s.to_string()));
563 (Some("issue_tracker_base_url"), Some(s)) => {
564 scx.issue_tracker_base_url = Some(s.to_string());
566 (Some("html_no_source"), None) if attr.is_word() => {
567 scx.include_sources = false;
574 try_err!(fs::create_dir_all(&dst), &dst);
575 krate = render_sources(&dst, &mut scx, krate)?;
579 render_redirect_pages: false,
580 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
581 id_map: Rc::new(RefCell::new(id_map)),
582 shared: Arc::new(scx),
585 // Crawl the crate to build various caches used for the output
597 let external_paths = external_paths.into_iter()
598 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
601 let mut cache = Cache {
602 impls: Default::default(),
605 paths: Default::default(),
606 implementors: Default::default(),
608 parent_stack: Vec::new(),
609 search_index: Vec::new(),
610 parent_is_trait_impl: false,
611 extern_locations: Default::default(),
612 primitive_locations: Default::default(),
615 crate_version: krate.version.take(),
616 orphan_impl_items: Vec::new(),
617 orphan_trait_impls: Vec::new(),
618 traits: krate.external_traits.lock().replace(Default::default()),
622 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
623 typarams: external_typarams,
624 aliases: Default::default(),
627 // Cache where all our extern crates are located
628 for &(n, ref e) in &krate.externs {
629 let src_root = match e.src {
630 FileName::Real(ref p) => match p.parent() {
631 Some(p) => p.to_path_buf(),
632 None => PathBuf::new(),
636 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
637 cache.extern_locations.insert(n, (e.name.clone(), src_root,
638 extern_location(e, extern_url, &cx.dst)));
640 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
641 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
644 // Cache where all known primitives have their documentation located.
646 // Favor linking to as local extern as possible, so iterate all crates in
647 // reverse topological order.
648 for &(_, ref e) in krate.externs.iter().rev() {
649 for &(def_id, prim, _) in &e.primitives {
650 cache.primitive_locations.insert(prim, def_id);
653 for &(def_id, prim, _) in &krate.primitives {
654 cache.primitive_locations.insert(prim, def_id);
657 cache.stack.push(krate.name.clone());
658 krate = cache.fold_crate(krate);
660 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
661 if cache.traits.contains_key(&trait_did) {
663 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
668 // Build our search index
669 let index = build_index(&krate, &mut cache);
671 // Freeze the cache now that the index has been built. Put an Arc into TLS
672 // for future parallelization opportunities
673 let cache = Arc::new(cache);
674 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
675 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
677 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
679 // And finally render the whole crate's documentation
683 /// Build the search index from the collected metadata
684 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
685 let mut nodeid_to_pathid = FxHashMap::default();
686 let mut crate_items = Vec::with_capacity(cache.search_index.len());
687 let mut crate_paths = Vec::<Json>::new();
689 let Cache { ref mut search_index,
690 ref orphan_impl_items,
691 ref mut paths, .. } = *cache;
693 // Attach all orphan items to the type's definition if the type
694 // has since been learned.
695 for &(did, ref item) in orphan_impl_items {
696 if let Some(&(ref fqp, _)) = paths.get(&did) {
697 search_index.push(IndexItem {
699 name: item.name.clone().unwrap(),
700 path: fqp[..fqp.len() - 1].join("::"),
701 desc: plain_summary_line_short(item.doc_value()),
704 search_type: get_index_search_type(&item),
709 // Reduce `NodeId` in paths into smaller sequential numbers,
710 // and prune the paths that do not appear in the index.
711 let mut lastpath = String::new();
712 let mut lastpathid = 0usize;
714 for item in search_index {
715 item.parent_idx = item.parent.map(|nodeid| {
716 if nodeid_to_pathid.contains_key(&nodeid) {
717 *nodeid_to_pathid.get(&nodeid).unwrap()
719 let pathid = lastpathid;
720 nodeid_to_pathid.insert(nodeid, pathid);
723 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
724 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
729 // Omit the parent path if it is same to that of the prior item.
730 if lastpath == item.path {
733 lastpath = item.path.clone();
735 crate_items.push(item.to_json());
738 let crate_doc = krate.module.as_ref().map(|module| {
739 plain_summary_line_short(module.doc_value())
740 }).unwrap_or(String::new());
742 let mut crate_data = BTreeMap::new();
743 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
744 crate_data.insert("items".to_owned(), Json::Array(crate_items));
745 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
747 // Collect the index into a string
748 format!("searchIndex[{}] = {};",
749 as_json(&krate.name),
750 Json::Object(crate_data))
755 krate: &clean::Crate,
757 search_index: String,
758 options: &RenderOptions,
759 diag: &errors::Handler,
760 ) -> Result<(), Error> {
761 // Write out the shared files. Note that these are shared among all rustdoc
762 // docs placed in the output directory, so this needs to be a synchronized
763 // operation with respect to all other rustdocs running around.
764 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
766 // Add all the static files. These may already exist, but we just
767 // overwrite them anyway to make sure that they're fresh and up-to-date.
769 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
770 static_files::RUSTDOC_CSS,
771 options.enable_minification)?;
772 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
773 static_files::SETTINGS_CSS,
774 options.enable_minification)?;
775 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
776 static_files::NOSCRIPT_CSS,
777 options.enable_minification)?;
779 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
780 // then we'll run over the "official" styles.
781 let mut themes: FxHashSet<String> = FxHashSet::default();
783 for entry in &cx.shared.themes {
784 let content = try_err!(fs::read(&entry), &entry);
785 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
786 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
787 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
788 content.as_slice())?;
789 themes.insert(theme.to_owned());
792 if (*cx.shared).layout.logo.is_empty() {
793 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
794 static_files::RUST_LOGO)?;
796 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
797 static_files::BRUSH_SVG)?;
798 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
799 static_files::WHEEL_SVG)?;
800 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
801 static_files::DOWN_ARROW_SVG)?;
802 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
803 static_files::themes::LIGHT,
804 options.enable_minification)?;
805 themes.insert("light".to_owned());
806 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
807 static_files::themes::DARK,
808 options.enable_minification)?;
809 themes.insert("dark".to_owned());
811 let mut themes: Vec<&String> = themes.iter().collect();
813 // To avoid theme switch latencies as much as possible, we put everything theme related
814 // at the beginning of the html files into another js file.
815 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
817 r#"var themes = document.getElementById("theme-choices");
818 var themePicker = document.getElementById("theme-picker");
820 function switchThemeButtonState() {{
821 if (themes.style.display === "block") {{
822 themes.style.display = "none";
823 themePicker.style.borderBottomRightRadius = "3px";
824 themePicker.style.borderBottomLeftRadius = "3px";
826 themes.style.display = "block";
827 themePicker.style.borderBottomRightRadius = "0";
828 themePicker.style.borderBottomLeftRadius = "0";
832 function handleThemeButtonsBlur(e) {{
833 var active = document.activeElement;
834 var related = e.relatedTarget;
836 if (active.id !== "themePicker" &&
837 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
839 (related.id !== "themePicker" &&
840 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
841 switchThemeButtonState();
845 themePicker.onclick = switchThemeButtonState;
846 themePicker.onblur = handleThemeButtonsBlur;
847 [{}].forEach(function(item) {{
848 var but = document.createElement('button');
849 but.innerHTML = item;
850 but.onclick = function(el) {{
851 switchTheme(currentTheme, mainTheme, item);
853 but.onblur = handleThemeButtonsBlur;
854 themes.appendChild(but);
857 .map(|s| format!("\"{}\"", s))
858 .collect::<Vec<String>>()
859 .join(",")).as_bytes(),
862 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
863 static_files::MAIN_JS,
864 options.enable_minification)?;
865 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
866 static_files::SETTINGS_JS,
867 options.enable_minification)?;
868 if cx.shared.include_sources {
869 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
870 static_files::sidebar::SOURCE_SCRIPT,
871 options.enable_minification)?;
875 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
876 &format!("var resourcesSuffix = \"{}\";{}",
877 cx.shared.resource_suffix,
878 static_files::STORAGE_JS),
879 options.enable_minification)?;
882 if let Some(ref css) = cx.shared.css_file_extension {
883 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
884 if !options.enable_minification {
885 try_err!(fs::copy(css, out), css);
887 let buffer = try_err!(fs::read_to_string(css), css);
888 write_minify(out, &buffer, options.enable_minification)?;
891 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
892 static_files::NORMALIZE_CSS,
893 options.enable_minification)?;
894 write(cx.dst.join("FiraSans-Regular.woff"),
895 static_files::fira_sans::REGULAR)?;
896 write(cx.dst.join("FiraSans-Medium.woff"),
897 static_files::fira_sans::MEDIUM)?;
898 write(cx.dst.join("FiraSans-LICENSE.txt"),
899 static_files::fira_sans::LICENSE)?;
900 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
901 static_files::source_serif_pro::REGULAR)?;
902 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
903 static_files::source_serif_pro::BOLD)?;
904 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
905 static_files::source_serif_pro::ITALIC)?;
906 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
907 static_files::source_serif_pro::LICENSE)?;
908 write(cx.dst.join("SourceCodePro-Regular.woff"),
909 static_files::source_code_pro::REGULAR)?;
910 write(cx.dst.join("SourceCodePro-Semibold.woff"),
911 static_files::source_code_pro::SEMIBOLD)?;
912 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
913 static_files::source_code_pro::LICENSE)?;
914 write(cx.dst.join("LICENSE-MIT.txt"),
915 static_files::LICENSE_MIT)?;
916 write(cx.dst.join("LICENSE-APACHE.txt"),
917 static_files::LICENSE_APACHE)?;
918 write(cx.dst.join("COPYRIGHT.txt"),
919 static_files::COPYRIGHT)?;
921 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
922 let mut ret = Vec::new();
923 let mut krates = Vec::new();
925 for line in BufReader::new(File::open(path)?).lines() {
927 if !line.starts_with(key) {
930 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
933 ret.push(line.to_string());
934 krates.push(line[key.len() + 2..].split('"')
936 .map(|s| s.to_owned())
937 .unwrap_or_else(|| String::new()));
943 fn show_item(item: &IndexItem, krate: &str) -> String {
944 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
945 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
946 if let Some(p) = item.parent_idx {
947 format!(",'parent':{}", p)
953 let dst = cx.dst.join("aliases.js");
955 let (mut all_aliases, _) = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
956 let mut w = try_err!(File::create(&dst), &dst);
957 let mut output = String::with_capacity(100);
958 for (alias, items) in &cache.aliases {
959 if items.is_empty() {
962 output.push_str(&format!("\"{}\":[{}],",
965 .map(|v| show_item(v, &krate.name))
969 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
971 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
972 for aliases in &all_aliases {
973 try_err!(writeln!(&mut w, "{}", aliases), &dst);
977 use std::ffi::OsString;
982 children: FxHashMap<OsString, Hierarchy>,
983 elems: FxHashSet<OsString>,
987 fn new(elem: OsString) -> Hierarchy {
990 children: FxHashMap::default(),
991 elems: FxHashSet::default(),
995 fn to_json_string(&self) -> String {
996 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
997 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
998 let mut files = self.elems.iter()
999 .map(|s| format!("\"{}\"",
1001 .expect("invalid osstring conversion")))
1002 .collect::<Vec<_>>();
1003 files.sort_unstable_by(|a, b| a.cmp(b));
1004 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1005 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1006 name=self.elem.to_str().expect("invalid osstring conversion"),
1007 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1008 files=files.join(","))
1012 if cx.shared.include_sources {
1013 use std::path::Component;
1015 let mut hierarchy = Hierarchy::new(OsString::new());
1016 for source in cx.shared.local_sources.iter()
1017 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1019 let mut h = &mut hierarchy;
1020 let mut elems = source.components()
1023 Component::Normal(s) => Some(s.to_owned()),
1029 let cur_elem = elems.next().expect("empty file path");
1030 if elems.peek().is_none() {
1031 h.elems.insert(cur_elem);
1034 let e = cur_elem.clone();
1035 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1036 h = h.children.get_mut(&cur_elem).expect("not found child");
1041 let dst = cx.dst.join("source-files.js");
1042 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1043 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1045 hierarchy.to_json_string()));
1047 let mut w = try_err!(File::create(&dst), &dst);
1048 try_err!(writeln!(&mut w,
1049 "var N = null;var sourcesIndex = {{}};\n{}",
1050 all_sources.join("\n")),
1054 // Update the search index
1055 let dst = cx.dst.join("search-index.js");
1056 let (mut all_indexes, mut krates) = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
1057 all_indexes.push(search_index);
1059 // Sort the indexes by crate so the file will be generated identically even
1060 // with rustdoc running in parallel.
1062 let mut w = try_err!(File::create(&dst), &dst);
1063 try_err!(writeln!(&mut w, "var N = null;var searchIndex = {{}};"), &dst);
1064 for index in &all_indexes {
1065 try_err!(write_minify_replacer(&mut w, &*index, options.enable_minification,
1066 &[(minifier::js::Keyword::Null, "N")]),
1069 try_err!(writeln!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1071 if options.enable_index_page {
1072 if let Some(index_page) = options.index_page.clone() {
1073 let mut md_opts = options.clone();
1074 md_opts.output = cx.dst.clone();
1075 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1077 ::markdown::render(index_page, md_opts, diag);
1079 let dst = cx.dst.join("index.html");
1080 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1081 let page = layout::Page {
1082 title: "Index of crates",
1085 static_root_path: cx.shared.static_root_path.deref(),
1086 description: "List of crates",
1087 keywords: BASIC_KEYWORDS,
1088 resource_suffix: &cx.shared.resource_suffix,
1090 static_extra_scripts: &[],
1092 krates.push(krate.name.clone());
1096 let content = format!(
1098 <span class='in-band'>List of all crates</span>\
1099 </h1><ul class='mod'>{}</ul>",
1103 format!("<li><a href=\"{}/index.html\">{}</li>", s, s)
1105 .collect::<String>());
1106 try_err!(layout::render(&mut w, &cx.shared.layout,
1107 &page, &(""), &content,
1108 cx.shared.css_file_extension.is_some(),
1110 cx.shared.generate_search_filter), &dst);
1111 try_err!(w.flush(), &dst);
1115 // Update the list of all implementors for traits
1116 let dst = cx.dst.join("implementors");
1117 for (&did, imps) in &cache.implementors {
1118 // Private modules can leak through to this phase of rustdoc, which
1119 // could contain implementations for otherwise private types. In some
1120 // rare cases we could find an implementation for an item which wasn't
1121 // indexed, so we just skip this step in that case.
1123 // FIXME: this is a vague explanation for why this can't be a `get`, in
1124 // theory it should be...
1125 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1127 None => match cache.external_paths.get(&did) {
1133 let mut have_impls = false;
1134 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1136 // If the trait and implementation are in the same crate, then
1137 // there's no need to emit information about it (there's inlining
1138 // going on). If they're in different crates then the crate defining
1139 // the trait will be interested in our implementation.
1140 if imp.impl_item.def_id.krate == did.krate { continue }
1141 // If the implementation is from another crate then that crate
1143 if !imp.impl_item.def_id.is_local() { continue }
1145 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1146 as_json(&imp.inner_impl().to_string()),
1147 imp.inner_impl().synthetic,
1148 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1150 implementors.push_str("];");
1152 // Only create a js file if we have impls to add to it. If the trait is
1153 // documented locally though we always create the file to avoid dead
1155 if !have_impls && !cache.paths.contains_key(&did) {
1159 let mut mydst = dst.clone();
1160 for part in &remote_path[..remote_path.len() - 1] {
1163 try_err!(fs::create_dir_all(&mydst), &mydst);
1164 mydst.push(&format!("{}.{}.js",
1165 remote_item_type.css_class(),
1166 remote_path[remote_path.len() - 1]));
1168 let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name, "implementors"),
1170 all_implementors.push(implementors);
1171 // Sort the implementors by crate so the file will be generated
1172 // identically even with rustdoc running in parallel.
1173 all_implementors.sort();
1175 let mut f = try_err!(File::create(&mydst), &mydst);
1176 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1177 for implementor in &all_implementors {
1178 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1180 try_err!(writeln!(&mut f, "{}", r"
1181 if (window.register_implementors) {
1182 window.register_implementors(implementors);
1184 window.pending_implementors = implementors;
1187 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1192 fn render_sources(dst: &Path, scx: &mut SharedContext,
1193 krate: clean::Crate) -> Result<clean::Crate, Error> {
1194 info!("emitting source files");
1195 let dst = dst.join("src").join(&krate.name);
1196 try_err!(fs::create_dir_all(&dst), &dst);
1197 let mut folder = SourceCollector {
1201 Ok(folder.fold_crate(krate))
1204 /// Writes the entire contents of a string to a destination, not attempting to
1205 /// catch any errors.
1206 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1207 Ok(try_err!(fs::write(&dst, contents), &dst))
1210 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1211 if enable_minification {
1212 if dst.extension() == Some(&OsStr::new("css")) {
1213 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1214 write(dst, res.as_bytes())
1216 write(dst, minifier::js::minify(contents).as_bytes())
1219 write(dst, contents.as_bytes())
1223 fn write_minify_replacer<W: Write>(dst: &mut W,
1225 enable_minification: bool,
1226 keywords_to_replace: &[(minifier::js::Keyword, &str)])
1228 if enable_minification {
1230 minifier::js::minify_and_replace_keywords(contents, keywords_to_replace))
1232 writeln!(dst, "{}", contents)
1236 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1237 /// things like ".." to components which preserve the "top down" hierarchy of a
1238 /// static HTML tree. Each component in the cleaned path will be passed as an
1239 /// argument to `f`. The very last component of the path (ie the file name) will
1240 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1241 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1244 // make it relative, if possible
1245 let p = p.strip_prefix(src_root).unwrap_or(p);
1247 let mut iter = p.components().peekable();
1249 while let Some(c) = iter.next() {
1250 if !keep_filename && iter.peek().is_none() {
1255 Component::ParentDir => f("up".as_ref()),
1256 Component::Normal(c) => f(c),
1262 /// Attempts to find where an external crate is located, given that we're
1263 /// rendering in to the specified source destination.
1264 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1267 // See if there's documentation generated into the local directory
1268 let local_location = dst.join(&e.name);
1269 if local_location.is_dir() {
1273 if let Some(url) = extern_url {
1274 let mut url = url.to_string();
1275 if !url.ends_with("/") {
1281 // Failing that, see if there's an attribute specifying where to find this
1283 e.attrs.lists("doc")
1284 .filter(|a| a.check_name("html_root_url"))
1285 .filter_map(|a| a.value_str())
1287 let mut url = url.to_string();
1288 if !url.ends_with("/") {
1292 }).next().unwrap_or(Unknown) // Well, at least we tried.
1295 impl<'a> DocFolder for SourceCollector<'a> {
1296 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1297 // If we're including source files, and we haven't seen this file yet,
1298 // then we need to render it out to the filesystem.
1299 if self.scx.include_sources
1300 // skip all invalid or macro spans
1301 && item.source.filename.is_real()
1302 // skip non-local items
1303 && item.def_id.is_local() {
1305 // If it turns out that we couldn't read this file, then we probably
1306 // can't read any of the files (generating html output from json or
1307 // something like that), so just don't include sources for the
1308 // entire crate. The other option is maintaining this mapping on a
1309 // per-file basis, but that's probably not worth it...
1311 .include_sources = match self.emit_source(&item.source.filename) {
1314 println!("warning: source code was requested to be rendered, \
1315 but processing `{}` had an error: {}",
1316 item.source.filename, e);
1317 println!(" skipping rendering of source code");
1322 self.fold_item_recur(item)
1326 impl<'a> SourceCollector<'a> {
1327 /// Renders the given filename into its corresponding HTML source file.
1328 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1329 let p = match *filename {
1330 FileName::Real(ref file) => file,
1333 if self.scx.local_sources.contains_key(&**p) {
1334 // We've already emitted this source
1338 let contents = fs::read_to_string(&p)?;
1340 // Remove the utf-8 BOM if any
1341 let contents = if contents.starts_with("\u{feff}") {
1347 // Create the intermediate directories
1348 let mut cur = self.dst.clone();
1349 let mut root_path = String::from("../../");
1350 let mut href = String::new();
1351 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1352 cur.push(component);
1353 fs::create_dir_all(&cur).unwrap();
1354 root_path.push_str("../");
1355 href.push_str(&component.to_string_lossy());
1358 let mut fname = p.file_name()
1359 .expect("source has no filename")
1361 fname.push(".html");
1363 href.push_str(&fname.to_string_lossy());
1365 let mut w = BufWriter::new(File::create(&cur)?);
1366 let title = format!("{} -- source", cur.file_name().unwrap()
1367 .to_string_lossy());
1368 let desc = format!("Source to the Rust file `{}`.", filename);
1369 let page = layout::Page {
1371 css_class: "source",
1372 root_path: &root_path,
1373 static_root_path: self.scx.static_root_path.deref(),
1375 keywords: BASIC_KEYWORDS,
1376 resource_suffix: &self.scx.resource_suffix,
1377 extra_scripts: &["source-files"],
1378 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1380 layout::render(&mut w, &self.scx.layout,
1381 &page, &(""), &Source(contents),
1382 self.scx.css_file_extension.is_some(),
1384 self.scx.generate_search_filter)?;
1386 self.scx.local_sources.insert(p.clone(), href);
1391 impl DocFolder for Cache {
1392 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1393 if item.def_id.is_local() {
1394 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1397 // If this is a stripped module,
1398 // we don't want it or its children in the search index.
1399 let orig_stripped_mod = match item.inner {
1400 clean::StrippedItem(box clean::ModuleItem(..)) => {
1401 mem::replace(&mut self.stripped_mod, true)
1403 _ => self.stripped_mod,
1406 // If the impl is from a masked crate or references something from a
1407 // masked crate then remove it completely.
1408 if let clean::ImplItem(ref i) = item.inner {
1409 if self.masked_crates.contains(&item.def_id.krate) ||
1410 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1411 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1416 // Register any generics to their corresponding string. This is used
1417 // when pretty-printing types.
1418 if let Some(generics) = item.inner.generics() {
1419 self.generics(generics);
1422 // Propagate a trait method's documentation to all implementors of the
1424 if let clean::TraitItem(ref t) = item.inner {
1425 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1428 // Collect all the implementors of traits.
1429 if let clean::ImplItem(ref i) = item.inner {
1430 if let Some(did) = i.trait_.def_id() {
1431 if i.blanket_impl.is_none() {
1432 self.implementors.entry(did).or_default().push(Impl {
1433 impl_item: item.clone(),
1439 // Index this method for searching later on.
1440 if let Some(ref s) = item.name {
1441 let (parent, is_inherent_impl_item) = match item.inner {
1442 clean::StrippedItem(..) => ((None, None), false),
1443 clean::AssociatedConstItem(..) |
1444 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1445 // skip associated items in trait impls
1446 ((None, None), false)
1448 clean::AssociatedTypeItem(..) |
1449 clean::TyMethodItem(..) |
1450 clean::StructFieldItem(..) |
1451 clean::VariantItem(..) => {
1452 ((Some(*self.parent_stack.last().unwrap()),
1453 Some(&self.stack[..self.stack.len() - 1])),
1456 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1457 if self.parent_stack.is_empty() {
1458 ((None, None), false)
1460 let last = self.parent_stack.last().unwrap();
1462 let path = match self.paths.get(&did) {
1463 // The current stack not necessarily has correlation
1464 // for where the type was defined. On the other
1465 // hand, `paths` always has the right
1466 // information if present.
1467 Some(&(ref fqp, ItemType::Trait)) |
1468 Some(&(ref fqp, ItemType::Struct)) |
1469 Some(&(ref fqp, ItemType::Union)) |
1470 Some(&(ref fqp, ItemType::Enum)) =>
1471 Some(&fqp[..fqp.len() - 1]),
1472 Some(..) => Some(&*self.stack),
1475 ((Some(*last), path), true)
1478 _ => ((None, Some(&*self.stack)), false)
1482 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1483 debug_assert!(!item.is_stripped());
1485 // A crate has a module at its root, containing all items,
1486 // which should not be indexed. The crate-item itself is
1487 // inserted later on when serializing the search-index.
1488 if item.def_id.index != CRATE_DEF_INDEX {
1489 self.search_index.push(IndexItem {
1491 name: s.to_string(),
1492 path: path.join("::"),
1493 desc: plain_summary_line_short(item.doc_value()),
1496 search_type: get_index_search_type(&item),
1500 (Some(parent), None) if is_inherent_impl_item => {
1501 // We have a parent, but we don't know where they're
1502 // defined yet. Wait for later to index this item.
1503 self.orphan_impl_items.push((parent, item.clone()));
1509 // Keep track of the fully qualified path for this item.
1510 let pushed = match item.name {
1511 Some(ref n) if !n.is_empty() => {
1512 self.stack.push(n.to_string());
1519 clean::StructItem(..) | clean::EnumItem(..) |
1520 clean::TypedefItem(..) | clean::TraitItem(..) |
1521 clean::FunctionItem(..) | clean::ModuleItem(..) |
1522 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1523 clean::ConstantItem(..) | clean::StaticItem(..) |
1524 clean::UnionItem(..) | clean::ForeignTypeItem |
1525 clean::MacroItem(..) | clean::ProcMacroItem(..)
1526 if !self.stripped_mod => {
1527 // Re-exported items mean that the same id can show up twice
1528 // in the rustdoc ast that we're looking at. We know,
1529 // however, that a re-exported item doesn't show up in the
1530 // `public_items` map, so we can skip inserting into the
1531 // paths map if there was already an entry present and we're
1532 // not a public item.
1533 if !self.paths.contains_key(&item.def_id) ||
1534 self.access_levels.is_public(item.def_id)
1536 self.paths.insert(item.def_id,
1537 (self.stack.clone(), item.type_()));
1539 self.add_aliases(&item);
1541 // Link variants to their parent enum because pages aren't emitted
1542 // for each variant.
1543 clean::VariantItem(..) if !self.stripped_mod => {
1544 let mut stack = self.stack.clone();
1546 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1549 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1550 self.add_aliases(&item);
1551 self.paths.insert(item.def_id, (self.stack.clone(),
1558 // Maintain the parent stack
1559 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1560 let parent_pushed = match item.inner {
1561 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1562 clean::StructItem(..) | clean::UnionItem(..) => {
1563 self.parent_stack.push(item.def_id);
1564 self.parent_is_trait_impl = false;
1567 clean::ImplItem(ref i) => {
1568 self.parent_is_trait_impl = i.trait_.is_some();
1570 clean::ResolvedPath{ did, .. } => {
1571 self.parent_stack.push(did);
1575 let prim_did = t.primitive_type().and_then(|t| {
1576 self.primitive_locations.get(&t).cloned()
1580 self.parent_stack.push(did);
1591 // Once we've recursively found all the generics, hoard off all the
1592 // implementations elsewhere.
1593 let ret = self.fold_item_recur(item).and_then(|item| {
1594 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1595 // Figure out the id of this impl. This may map to a
1596 // primitive rather than always to a struct/enum.
1597 // Note: matching twice to restrict the lifetime of the `i` borrow.
1598 let mut dids = FxHashSet::default();
1599 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1601 clean::ResolvedPath { did, .. } |
1602 clean::BorrowedRef {
1603 type_: box clean::ResolvedPath { did, .. }, ..
1608 let did = t.primitive_type().and_then(|t| {
1609 self.primitive_locations.get(&t).cloned()
1612 if let Some(did) = did {
1618 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1619 for bound in generics {
1620 if let Some(did) = bound.def_id() {
1628 let impl_item = Impl {
1631 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1633 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1636 let trait_did = impl_item.trait_did().unwrap();
1637 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1645 if pushed { self.stack.pop().unwrap(); }
1646 if parent_pushed { self.parent_stack.pop().unwrap(); }
1647 self.stripped_mod = orig_stripped_mod;
1648 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1654 fn generics(&mut self, generics: &clean::Generics) {
1655 for param in &generics.params {
1657 clean::GenericParamDefKind::Lifetime => {}
1658 clean::GenericParamDefKind::Type { did, .. } => {
1659 self.typarams.insert(did, param.name.clone());
1665 fn add_aliases(&mut self, item: &clean::Item) {
1666 if item.def_id.index == CRATE_DEF_INDEX {
1669 if let Some(ref item_name) = item.name {
1670 let path = self.paths.get(&item.def_id)
1671 .map(|p| p.0[..p.0.len() - 1].join("::"))
1672 .unwrap_or("std".to_owned());
1673 for alias in item.attrs.lists("doc")
1674 .filter(|a| a.check_name("alias"))
1675 .filter_map(|a| a.value_str()
1676 .map(|s| s.to_string().replace("\"", "")))
1677 .filter(|v| !v.is_empty())
1678 .collect::<FxHashSet<_>>()
1680 self.aliases.entry(alias)
1681 .or_insert(Vec::with_capacity(1))
1684 name: item_name.to_string(),
1686 desc: plain_summary_line_short(item.doc_value()),
1689 search_type: get_index_search_type(&item),
1696 #[derive(Debug, Eq, PartialEq, Hash)]
1703 fn new(mut url: String, name: String) -> ItemEntry {
1704 while url.starts_with('/') {
1714 impl fmt::Display for ItemEntry {
1715 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1716 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1720 impl PartialOrd for ItemEntry {
1721 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1722 Some(self.cmp(other))
1726 impl Ord for ItemEntry {
1727 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1728 self.name.cmp(&other.name)
1734 structs: FxHashSet<ItemEntry>,
1735 enums: FxHashSet<ItemEntry>,
1736 unions: FxHashSet<ItemEntry>,
1737 primitives: FxHashSet<ItemEntry>,
1738 traits: FxHashSet<ItemEntry>,
1739 macros: FxHashSet<ItemEntry>,
1740 functions: FxHashSet<ItemEntry>,
1741 typedefs: FxHashSet<ItemEntry>,
1742 existentials: FxHashSet<ItemEntry>,
1743 statics: FxHashSet<ItemEntry>,
1744 constants: FxHashSet<ItemEntry>,
1745 keywords: FxHashSet<ItemEntry>,
1746 attributes: FxHashSet<ItemEntry>,
1747 derives: FxHashSet<ItemEntry>,
1751 fn new() -> AllTypes {
1752 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1754 structs: new_set(100),
1755 enums: new_set(100),
1756 unions: new_set(100),
1757 primitives: new_set(26),
1758 traits: new_set(100),
1759 macros: new_set(100),
1760 functions: new_set(100),
1761 typedefs: new_set(100),
1762 existentials: new_set(100),
1763 statics: new_set(100),
1764 constants: new_set(100),
1765 keywords: new_set(100),
1766 attributes: new_set(100),
1767 derives: new_set(100),
1771 fn append(&mut self, item_name: String, item_type: &ItemType) {
1772 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1773 if let Some(name) = url.pop() {
1774 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1776 let name = url.join("::");
1778 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1779 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1780 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1781 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1782 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1783 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1784 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1785 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1786 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1787 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1788 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1789 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1790 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1797 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1798 class: &str) -> fmt::Result {
1800 let mut e: Vec<&ItemEntry> = e.iter().collect();
1802 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1806 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1811 impl fmt::Display for AllTypes {
1812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1815 <span class='out-of-band'>\
1816 <span id='render-detail'>\
1817 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1818 [<span class='inner'>−</span>]\
1822 <span class='in-band'>List of all items</span>\
1824 print_entries(f, &self.structs, "Structs", "structs")?;
1825 print_entries(f, &self.enums, "Enums", "enums")?;
1826 print_entries(f, &self.unions, "Unions", "unions")?;
1827 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1828 print_entries(f, &self.traits, "Traits", "traits")?;
1829 print_entries(f, &self.macros, "Macros", "macros")?;
1830 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1831 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1832 print_entries(f, &self.functions, "Functions", "functions")?;
1833 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1834 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1835 print_entries(f, &self.statics, "Statics", "statics")?;
1836 print_entries(f, &self.constants, "Constants", "constants")
1841 struct Settings<'a> {
1842 // (id, explanation, default value)
1843 settings: Vec<(&'static str, &'static str, bool)>,
1848 impl<'a> Settings<'a> {
1849 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1852 ("item-declarations", "Auto-hide item declarations.", true),
1853 ("item-attributes", "Auto-hide item attributes.", true),
1854 ("trait-implementations", "Auto-hide trait implementations documentation",
1856 ("method-docs", "Auto-hide item methods' documentation", false),
1857 ("go-to-only-result", "Directly go to item in search if there is only one result",
1859 ("line-numbers", "Show line numbers on code examples", false),
1867 impl<'a> fmt::Display for Settings<'a> {
1868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1871 <span class='in-band'>Rustdoc settings</span>\
1873 <div class='settings'>{}</div>\
1874 <script src='{}settings{}.js'></script>",
1875 self.settings.iter()
1876 .map(|(id, text, enabled)| {
1877 format!("<div class='setting-line'>\
1878 <label class='toggle'>\
1879 <input type='checkbox' id='{}' {}>\
1880 <span class='slider'></span>\
1883 </div>", id, if *enabled { " checked" } else { "" }, text)
1885 .collect::<String>(),
1892 fn derive_id(&self, id: String) -> String {
1893 let mut map = self.id_map.borrow_mut();
1897 /// String representation of how to get back to the root path of the 'doc/'
1898 /// folder in terms of a relative URL.
1899 fn root_path(&self) -> String {
1900 "../".repeat(self.current.len())
1903 /// Recurse in the directory structure and change the "root path" to make
1904 /// sure it always points to the top (relatively).
1905 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1906 F: FnOnce(&mut Context) -> T,
1909 panic!("Unexpected empty destination: {:?}", self.current);
1911 let prev = self.dst.clone();
1913 self.current.push(s);
1915 info!("Recursing into {}", self.dst.display());
1919 info!("Recursed; leaving {}", self.dst.display());
1921 // Go back to where we were at
1923 self.current.pop().unwrap();
1928 /// Main method for rendering a crate.
1930 /// This currently isn't parallelized, but it'd be pretty easy to add
1931 /// parallelization to this function.
1932 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1933 let mut item = match krate.module.take() {
1935 None => return Ok(()),
1937 let final_file = self.dst.join(&krate.name)
1939 let settings_file = self.dst.join("settings.html");
1941 let crate_name = krate.name.clone();
1942 item.name = Some(krate.name);
1944 let mut all = AllTypes::new();
1947 // Render the crate documentation
1948 let mut work = vec![(self.clone(), item)];
1950 while let Some((mut cx, item)) = work.pop() {
1951 cx.item(item, &mut all, |cx, item| {
1952 work.push((cx.clone(), item))
1957 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1958 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1959 if !root_path.ends_with('/') {
1960 root_path.push('/');
1962 let mut page = layout::Page {
1963 title: "List of all items in this crate",
1966 static_root_path: self.shared.static_root_path.deref(),
1967 description: "List of all items in this crate",
1968 keywords: BASIC_KEYWORDS,
1969 resource_suffix: &self.shared.resource_suffix,
1971 static_extra_scripts: &[],
1973 let sidebar = if let Some(ref version) = cache().crate_version {
1974 format!("<p class='location'>Crate {}</p>\
1975 <div class='block version'>\
1978 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1979 crate_name, version)
1983 try_err!(layout::render(&mut w, &self.shared.layout,
1984 &page, &sidebar, &all,
1985 self.shared.css_file_extension.is_some(),
1986 &self.shared.themes,
1987 self.shared.generate_search_filter),
1990 // Generating settings page.
1991 let settings = Settings::new("./", &self.shared.resource_suffix);
1992 page.title = "Rustdoc settings";
1993 page.description = "Settings of Rustdoc";
1994 page.root_path = "./";
1996 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1997 let mut themes = self.shared.themes.clone();
1998 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1999 themes.push(PathBuf::from("settings.css"));
2000 let mut layout = self.shared.layout.clone();
2001 layout.krate = String::new();
2002 layout.logo = String::new();
2003 layout.favicon = String::new();
2004 try_err!(layout::render(&mut w, &layout,
2005 &page, &sidebar, &settings,
2006 self.shared.css_file_extension.is_some(),
2008 self.shared.generate_search_filter),
2014 fn render_item(&self,
2015 writer: &mut dyn io::Write,
2019 // A little unfortunate that this is done like this, but it sure
2020 // does make formatting *a lot* nicer.
2021 CURRENT_LOCATION_KEY.with(|slot| {
2022 *slot.borrow_mut() = self.current.clone();
2025 let mut title = if it.is_primitive() || it.is_keyword() {
2026 // No need to include the namespace for primitive types and keywords
2029 self.current.join("::")
2032 if !title.is_empty() {
2033 title.push_str("::");
2035 title.push_str(it.name.as_ref().unwrap());
2037 title.push_str(" - Rust");
2038 let tyname = it.type_().css_class();
2039 let desc = if it.is_crate() {
2040 format!("API documentation for the Rust `{}` crate.",
2041 self.shared.layout.krate)
2043 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2044 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2046 let keywords = make_item_keywords(it);
2047 let page = layout::Page {
2049 root_path: &self.root_path(),
2050 static_root_path: self.shared.static_root_path.deref(),
2053 keywords: &keywords,
2054 resource_suffix: &self.shared.resource_suffix,
2056 static_extra_scripts: &[],
2060 self.id_map.borrow_mut().reset();
2061 self.id_map.borrow_mut().populate(initial_ids());
2064 if !self.render_redirect_pages {
2065 layout::render(writer, &self.shared.layout, &page,
2066 &Sidebar{ cx: self, item: it },
2067 &Item{ cx: self, item: it },
2068 self.shared.css_file_extension.is_some(),
2069 &self.shared.themes,
2070 self.shared.generate_search_filter)?;
2072 let mut url = self.root_path();
2073 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2074 for name in &names[..names.len() - 1] {
2078 url.push_str(&item_path(ty, names.last().unwrap()));
2079 layout::redirect(writer, &url)?;
2085 /// Non-parallelized version of rendering an item. This will take the input
2086 /// item, render its contents, and then invoke the specified closure with
2087 /// all sub-items which need to be rendered.
2089 /// The rendering driver uses this closure to queue up more work.
2090 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2091 where F: FnMut(&mut Context, clean::Item),
2093 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2094 // if they contain impls for public types. These modules can also
2095 // contain items such as publicly re-exported structures.
2097 // External crates will provide links to these structures, so
2098 // these modules are recursed into, but not rendered normally
2099 // (a flag on the context).
2100 if !self.render_redirect_pages {
2101 self.render_redirect_pages = item.is_stripped();
2105 // modules are special because they add a namespace. We also need to
2106 // recurse into the items of the module as well.
2107 let name = item.name.as_ref().unwrap().to_string();
2108 let mut item = Some(item);
2109 self.recurse(name, |this| {
2110 let item = item.take().unwrap();
2112 let mut buf = Vec::new();
2113 this.render_item(&mut buf, &item, false).unwrap();
2114 // buf will be empty if the module is stripped and there is no redirect for it
2115 if !buf.is_empty() {
2116 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2117 let joint_dst = this.dst.join("index.html");
2118 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2121 let m = match item.inner {
2122 clean::StrippedItem(box clean::ModuleItem(m)) |
2123 clean::ModuleItem(m) => m,
2127 // Render sidebar-items.js used throughout this module.
2128 if !this.render_redirect_pages {
2129 let items = this.build_sidebar_items(&m);
2130 let js_dst = this.dst.join("sidebar-items.js");
2131 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2132 try_err!(write!(&mut js_out, "initSidebarItems({});",
2133 as_json(&items)), &js_dst);
2136 for item in m.items {
2142 } else if item.name.is_some() {
2143 let mut buf = Vec::new();
2144 self.render_item(&mut buf, &item, true).unwrap();
2145 // buf will be empty if the item is stripped and there is no redirect for it
2146 if !buf.is_empty() {
2147 let name = item.name.as_ref().unwrap();
2148 let item_type = item.type_();
2149 let file_name = &item_path(item_type, name);
2150 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2151 let joint_dst = self.dst.join(file_name);
2152 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2154 if !self.render_redirect_pages {
2155 all.append(full_path(self, &item), &item_type);
2157 // Redirect from a sane URL using the namespace to Rustdoc's
2158 // URL for the page.
2159 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2160 let redir_dst = self.dst.join(redir_name);
2161 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2164 let mut redirect_out = BufWriter::new(redirect_out);
2165 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2168 // If the item is a macro, redirect from the old macro URL (with !)
2169 // to the new one (without).
2170 if item_type == ItemType::Macro {
2171 let redir_name = format!("{}.{}!.html", item_type, name);
2172 let redir_dst = self.dst.join(redir_name);
2173 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2174 let mut redirect_out = BufWriter::new(redirect_out);
2175 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2182 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2183 // BTreeMap instead of HashMap to get a sorted output
2184 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2185 for item in &m.items {
2186 if item.is_stripped() { continue }
2188 let short = item.type_().css_class();
2189 let myname = match item.name {
2191 Some(ref s) => s.to_string(),
2193 let short = short.to_string();
2194 map.entry(short).or_default()
2195 .push((myname, Some(plain_summary_line(item.doc_value()))));
2198 if self.shared.sort_modules_alphabetically {
2199 for (_, items) in &mut map {
2208 /// Generate a url appropriate for an `href` attribute back to the source of
2211 /// The url generated, when clicked, will redirect the browser back to the
2212 /// original source code.
2214 /// If `None` is returned, then a source link couldn't be generated. This
2215 /// may happen, for example, with externally inlined items where the source
2216 /// of their crate documentation isn't known.
2217 fn src_href(&self) -> Option<String> {
2218 let mut root = self.cx.root_path();
2220 let cache = cache();
2221 let mut path = String::new();
2223 // We can safely ignore macros from other libraries
2224 let file = match self.item.source.filename {
2225 FileName::Real(ref path) => path,
2229 let (krate, path) = if self.item.def_id.is_local() {
2230 if let Some(path) = self.cx.shared.local_sources.get(file) {
2231 (&self.cx.shared.layout.krate, path)
2236 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2237 (ref name, ref src, Local) => (name, src),
2238 (ref name, ref src, Remote(ref s)) => {
2239 root = s.to_string();
2242 (_, _, Unknown) => return None,
2245 clean_srcpath(&src_root, file, false, |component| {
2246 path.push_str(&component.to_string_lossy());
2249 let mut fname = file.file_name().expect("source has no filename")
2251 fname.push(".html");
2252 path.push_str(&fname.to_string_lossy());
2256 let lines = if self.item.source.loline == self.item.source.hiline {
2257 self.item.source.loline.to_string()
2259 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2261 Some(format!("{root}src/{krate}/{path}#{lines}",
2262 root = Escape(&root),
2269 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2270 f: F) -> fmt::Result
2271 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2272 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2277 impl<'a> fmt::Display for Item<'a> {
2278 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2279 debug_assert!(!self.item.is_stripped());
2280 // Write the breadcrumb trail header for the top
2281 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2282 if let Some(version) = self.item.stable_since() {
2283 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2287 "<span id='render-detail'>\
2288 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2289 title=\"collapse all docs\">\
2290 [<span class='inner'>−</span>]\
2296 // When this item is part of a `pub use` in a downstream crate, the
2297 // [src] link in the downstream documentation will actually come back to
2298 // this page, and this link will be auto-clicked. The `id` attribute is
2299 // used to find the link to auto-click.
2300 if self.cx.shared.include_sources && !self.item.is_primitive() {
2301 if let Some(l) = self.src_href() {
2302 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2303 l, "goto source code")?;
2307 write!(fmt, "</span>")?; // out-of-band
2308 write!(fmt, "<span class='in-band'>")?;
2309 match self.item.inner {
2310 clean::ModuleItem(ref m) => if m.is_crate {
2311 write!(fmt, "Crate ")?;
2313 write!(fmt, "Module ")?;
2315 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2316 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2317 clean::StructItem(..) => write!(fmt, "Struct ")?,
2318 clean::UnionItem(..) => write!(fmt, "Union ")?,
2319 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2320 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2321 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2322 clean::ProcMacroItem(ref mac) => match mac.kind {
2323 MacroKind::Bang => write!(fmt, "Macro ")?,
2324 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2325 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2326 MacroKind::ProcMacroStub => unreachable!(),
2328 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2329 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2330 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2331 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2332 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2333 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2335 // We don't generate pages for any other type.
2339 if !self.item.is_primitive() && !self.item.is_keyword() {
2340 let cur = &self.cx.current;
2341 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2342 for (i, component) in cur.iter().enumerate().take(amt) {
2343 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2344 "../".repeat(cur.len() - i - 1),
2348 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2349 self.item.type_(), self.item.name.as_ref().unwrap())?;
2351 write!(fmt, "</span></h1>")?; // in-band
2353 match self.item.inner {
2354 clean::ModuleItem(ref m) =>
2355 item_module(fmt, self.cx, self.item, &m.items),
2356 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2357 item_function(fmt, self.cx, self.item, f),
2358 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2359 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2360 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2361 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2362 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2363 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2364 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2365 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2366 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2367 item_static(fmt, self.cx, self.item, i),
2368 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2369 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2370 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2371 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2373 // We don't generate pages for any other type.
2380 fn item_path(ty: ItemType, name: &str) -> String {
2382 ItemType::Module => format!("{}/index.html", name),
2383 _ => format!("{}.{}.html", ty.css_class(), name),
2387 fn full_path(cx: &Context, item: &clean::Item) -> String {
2388 let mut s = cx.current.join("::");
2390 s.push_str(item.name.as_ref().unwrap());
2394 fn shorter<'a>(s: Option<&'a str>) -> String {
2396 Some(s) => s.lines()
2397 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2399 (*line).chars().any(|chr|{
2400 !chr.is_whitespace()
2402 }).collect::<Vec<_>>().join("\n"),
2403 None => String::new()
2408 fn plain_summary_line(s: Option<&str>) -> String {
2409 let line = shorter(s).replace("\n", " ");
2410 markdown::plain_summary_line_full(&line[..], false)
2414 fn plain_summary_line_short(s: Option<&str>) -> String {
2415 let line = shorter(s).replace("\n", " ");
2416 markdown::plain_summary_line_full(&line[..], true)
2419 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2420 if let Some(ref name) = item.name {
2421 info!("Documenting {}", name);
2423 document_stability(w, cx, item, false)?;
2424 document_full(w, item, cx, "", false)?;
2428 /// Render md_text as markdown.
2429 fn render_markdown(w: &mut fmt::Formatter,
2432 links: Vec<(String, String)>,
2436 let mut ids = cx.id_map.borrow_mut();
2437 write!(w, "<div class='docblock{}'>{}{}</div>",
2438 if is_hidden { " hidden" } else { "" },
2440 Markdown(md_text, &links, RefCell::new(&mut ids),
2444 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2445 prefix: &str, is_hidden: bool) -> fmt::Result {
2446 if let Some(s) = item.doc_value() {
2447 let markdown = if s.contains('\n') {
2448 format!("{} [Read more]({})",
2449 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2451 plain_summary_line(Some(s))
2453 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2454 } else if !prefix.is_empty() {
2455 write!(w, "<div class='docblock{}'>{}</div>",
2456 if is_hidden { " hidden" } else { "" },
2462 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2463 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2464 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2465 debug!("Doc block: =====\n{}\n=====", s);
2466 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2467 } else if !prefix.is_empty() {
2468 write!(w, "<div class='docblock{}'>{}</div>",
2469 if is_hidden { " hidden" } else { "" },
2475 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2476 is_hidden: bool) -> fmt::Result {
2477 let stabilities = short_stability(item, cx);
2478 if !stabilities.is_empty() {
2479 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2480 for stability in stabilities {
2481 write!(w, "{}", stability)?;
2483 write!(w, "</div>")?;
2488 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2489 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2492 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2493 if item.is_non_exhaustive() {
2494 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2495 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2498 if item.is_struct() {
2499 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2500 Therefore, non-exhaustive structs cannot be constructed in external crates \
2501 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2502 matched against without a wildcard <code>..</code>; and \
2503 struct update syntax will not work.")?;
2504 } else if item.is_enum() {
2505 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2506 Therefore, when matching against variants of non-exhaustive enums, an \
2507 extra wildcard arm must be added to account for any future variants.")?;
2509 write!(w, "This type will require a wildcard arm in any match statements or \
2513 write!(w, "</div>")?;
2519 fn name_key(name: &str) -> (&str, u64, usize) {
2520 let end = name.bytes()
2521 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2523 // find number at end
2524 let split = name[0..end].bytes()
2525 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2527 // count leading zeroes
2529 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2531 // sort leading zeroes last
2532 let num_zeroes = after_zeroes - split;
2534 match name[split..end].parse() {
2535 Ok(n) => (&name[..split], n, num_zeroes),
2536 Err(_) => (name, 0, num_zeroes),
2540 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2541 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2542 document(w, cx, item)?;
2544 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2546 // the order of item types in the listing
2547 fn reorder(ty: ItemType) -> u8 {
2549 ItemType::ExternCrate => 0,
2550 ItemType::Import => 1,
2551 ItemType::Primitive => 2,
2552 ItemType::Module => 3,
2553 ItemType::Macro => 4,
2554 ItemType::Struct => 5,
2555 ItemType::Enum => 6,
2556 ItemType::Constant => 7,
2557 ItemType::Static => 8,
2558 ItemType::Trait => 9,
2559 ItemType::Function => 10,
2560 ItemType::Typedef => 12,
2561 ItemType::Union => 13,
2566 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2567 let ty1 = i1.type_();
2568 let ty2 = i2.type_();
2570 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2572 let s1 = i1.stability.as_ref().map(|s| s.level);
2573 let s2 = i2.stability.as_ref().map(|s| s.level);
2575 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2576 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2579 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2580 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2581 name_key(lhs).cmp(&name_key(rhs))
2584 if cx.shared.sort_modules_alphabetically {
2585 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2587 // This call is to remove re-export duplicates in cases such as:
2592 // pub trait Double { fn foo(); }
2596 // pub use foo::bar::*;
2600 // `Double` will appear twice in the generated docs.
2602 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2603 // can be identical even if the elements are different (mostly in imports).
2604 // So in case this is an import, we keep everything by adding a "unique id"
2605 // (which is the position in the vector).
2606 indices.dedup_by_key(|i| (items[*i].def_id,
2607 if items[*i].name.as_ref().is_some() {
2608 Some(full_path(cx, &items[*i]))
2613 if items[*i].is_import() {
2619 debug!("{:?}", indices);
2620 let mut curty = None;
2621 for &idx in &indices {
2622 let myitem = &items[idx];
2623 if myitem.is_stripped() {
2627 let myty = Some(myitem.type_());
2628 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2629 // Put `extern crate` and `use` re-exports in the same section.
2631 } else if myty != curty {
2632 if curty.is_some() {
2633 write!(w, "</table>")?;
2636 let (short, name) = item_ty_to_strs(&myty.unwrap());
2637 write!(w, "<h2 id='{id}' class='section-header'>\
2638 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2639 id = cx.derive_id(short.to_owned()), name = name)?;
2642 match myitem.inner {
2643 clean::ExternCrateItem(ref name, ref src) => {
2644 use html::format::HRef;
2648 write!(w, "<tr><td><code>{}extern crate {} as {};",
2649 VisSpace(&myitem.visibility),
2650 HRef::new(myitem.def_id, src),
2654 write!(w, "<tr><td><code>{}extern crate {};",
2655 VisSpace(&myitem.visibility),
2656 HRef::new(myitem.def_id, name))?
2659 write!(w, "</code></td></tr>")?;
2662 clean::ImportItem(ref import) => {
2663 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2664 VisSpace(&myitem.visibility), *import)?;
2668 if myitem.name.is_none() { continue }
2670 let unsafety_flag = match myitem.inner {
2671 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2672 if func.header.unsafety == hir::Unsafety::Unsafe => {
2673 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2678 let stab = myitem.stability_class();
2679 let add = if stab.is_some() {
2685 let doc_value = myitem.doc_value().unwrap_or("");
2687 <tr class='{stab}{add}module-item'>\
2688 <td><a class=\"{class}\" href=\"{href}\" \
2689 title='{title}'>{name}</a>{unsafety_flag}</td>\
2690 <td class='docblock-short'>{stab_tags}{docs}\
2693 name = *myitem.name.as_ref().unwrap(),
2694 stab_tags = stability_tags(myitem),
2695 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2696 class = myitem.type_(),
2698 stab = stab.unwrap_or_else(|| String::new()),
2699 unsafety_flag = unsafety_flag,
2700 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2701 title = [full_path(cx, myitem), myitem.type_().to_string()]
2703 .filter_map(|s| if !s.is_empty() {
2708 .collect::<Vec<_>>()
2715 if curty.is_some() {
2716 write!(w, "</table>")?;
2721 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2723 fn stability_tags(item: &clean::Item) -> String {
2724 let mut tags = String::new();
2726 // The trailing space after each tag is to space it properly against the rest of the docs.
2727 if item.deprecation().is_some() {
2728 tags.push_str("[<div class='stab deprecated'>Deprecated</div>] ");
2731 if let Some(stab) = item
2734 .filter(|s| s.level == stability::Unstable)
2736 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2737 tags.push_str("[<div class='stab internal'>Internal</div>] ");
2739 tags.push_str("[<div class='stab unstable'>Experimental</div>] ");
2743 if let Some(ref cfg) = item.attrs.cfg {
2744 tags.push_str(&format!(
2745 "[<div class='stab portability'>{}</div>] ",
2746 cfg.render_short_html()
2753 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2755 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2756 let mut stability = vec![];
2757 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2759 if let Some(Deprecation { since, note }) = &item.deprecation() {
2760 let mut message = if let Some(since) = since {
2761 if stability::deprecation_in_effect(since) {
2762 format!("Deprecated since {}", Escape(since))
2764 format!("Deprecating in {}", Escape(since))
2767 String::from("Deprecated")
2770 if let Some(note) = note {
2771 let mut ids = cx.id_map.borrow_mut();
2772 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2773 message.push_str(&format!(": {}", html));
2775 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2778 if let Some(stab) = item
2781 .filter(|stab| stab.level == stability::Unstable)
2783 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2785 let mut message = if is_rustc_private {
2786 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2788 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2792 if let Some(feature) = stab.feature.as_ref() {
2793 let mut feature = format!("<code>{}</code>", Escape(&feature));
2794 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2795 feature.push_str(&format!(
2796 " <a href=\"{url}{issue}\">#{issue}</a>",
2802 message.push_str(&format!(" ({})", feature));
2805 if let Some(unstable_reason) = &stab.unstable_reason {
2806 // Provide a more informative message than the compiler help.
2807 let unstable_reason = if is_rustc_private {
2808 "This crate is being loaded from the sysroot, a permanently unstable location \
2809 for private compiler dependencies. It is not intended for general use. Prefer \
2810 using a public version of this crate from \
2811 [crates.io](https://crates.io) via [`Cargo.toml`]\
2812 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2817 let mut ids = cx.id_map.borrow_mut();
2819 "<details><summary>{}</summary>{}</details>",
2821 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2825 let class = if is_rustc_private {
2830 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2833 if let Some(ref cfg) = item.attrs.cfg {
2834 stability.push(format!(
2835 "<div class='stab portability'>{}</div>",
2836 cfg.render_long_html()
2843 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2844 c: &clean::Constant) -> fmt::Result {
2845 write!(w, "<pre class='rust const'>")?;
2846 render_attributes(w, it)?;
2847 write!(w, "{vis}const \
2848 {name}: {typ}</pre>",
2849 vis = VisSpace(&it.visibility),
2850 name = it.name.as_ref().unwrap(),
2855 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2856 s: &clean::Static) -> fmt::Result {
2857 write!(w, "<pre class='rust static'>")?;
2858 render_attributes(w, it)?;
2859 write!(w, "{vis}static {mutability}\
2860 {name}: {typ}</pre>",
2861 vis = VisSpace(&it.visibility),
2862 mutability = MutableSpace(s.mutability),
2863 name = it.name.as_ref().unwrap(),
2868 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2869 f: &clean::Function) -> fmt::Result {
2870 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2871 VisSpace(&it.visibility),
2872 ConstnessSpace(f.header.constness),
2873 UnsafetySpace(f.header.unsafety),
2874 AsyncSpace(f.header.asyncness),
2875 AbiSpace(f.header.abi),
2876 it.name.as_ref().unwrap(),
2878 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2879 render_attributes(w, it)?;
2881 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2882 {name}{generics}{decl}{where_clause}</pre>",
2883 vis = VisSpace(&it.visibility),
2884 constness = ConstnessSpace(f.header.constness),
2885 unsafety = UnsafetySpace(f.header.unsafety),
2886 asyncness = AsyncSpace(f.header.asyncness),
2887 abi = AbiSpace(f.header.abi),
2888 name = it.name.as_ref().unwrap(),
2889 generics = f.generics,
2890 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2899 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2900 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2901 // If there's already another implementor that has the same abbridged name, use the
2902 // full path, for example in `std::iter::ExactSizeIterator`
2903 let use_absolute = match implementor.inner_impl().for_ {
2904 clean::ResolvedPath { ref path, is_generic: false, .. } |
2905 clean::BorrowedRef {
2906 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2908 } => implementor_dups[path.last_name()].1,
2911 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2912 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
2916 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2918 containing_item: &clean::Item) -> fmt::Result {
2920 let did = i.trait_did().unwrap();
2921 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2922 render_impl(w, cx, i, assoc_link,
2923 RenderMode::Normal, containing_item.stable_since(), true, None)?;
2928 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
2929 let mut bounds = String::new();
2930 let mut bounds_plain = String::new();
2931 if !t_bounds.is_empty() {
2932 if !bounds.is_empty() {
2934 bounds_plain.push(' ');
2936 bounds.push_str(": ");
2937 bounds_plain.push_str(": ");
2938 for (i, p) in t_bounds.iter().enumerate() {
2940 bounds.push_str(" + ");
2941 bounds_plain.push_str(" + ");
2943 bounds.push_str(&(*p).to_string());
2944 bounds_plain.push_str(&format!("{:#}", *p));
2950 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2951 let lhs = format!("{}", lhs.inner_impl());
2952 let rhs = format!("{}", rhs.inner_impl());
2954 // lhs and rhs are formatted as HTML, which may be unnecessary
2955 name_key(&lhs).cmp(&name_key(&rhs))
2959 w: &mut fmt::Formatter,
2964 let bounds = bounds(&t.bounds);
2965 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2966 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2967 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2968 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2970 // Output the trait definition
2971 wrap_into_docblock(w, |w| {
2972 write!(w, "<pre class='rust trait'>")?;
2973 render_attributes(w, it)?;
2974 write!(w, "{}{}{}trait {}{}{}",
2975 VisSpace(&it.visibility),
2976 UnsafetySpace(t.unsafety),
2977 if t.is_auto { "auto " } else { "" },
2978 it.name.as_ref().unwrap(),
2982 if !t.generics.where_predicates.is_empty() {
2983 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2988 if t.items.is_empty() {
2989 write!(w, "{{ }}")?;
2991 // FIXME: we should be using a derived_id for the Anchors here
2995 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2998 if !types.is_empty() && !consts.is_empty() {
3003 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3006 if !consts.is_empty() && !required.is_empty() {
3009 for (pos, m) in required.iter().enumerate() {
3011 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3014 if pos < required.len() - 1 {
3015 write!(w, "<div class='item-spacer'></div>")?;
3018 if !required.is_empty() && !provided.is_empty() {
3021 for (pos, m) in provided.iter().enumerate() {
3023 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3025 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3026 write!(w, ",\n {{ ... }}\n")?;
3029 write!(w, " {{ ... }}\n")?;
3032 if pos < provided.len() - 1 {
3033 write!(w, "<div class='item-spacer'></div>")?;
3041 // Trait documentation
3042 document(w, cx, it)?;
3044 fn write_small_section_header(
3045 w: &mut fmt::Formatter,
3048 extra_content: &str,
3051 <h2 id='{0}' class='small-section-header'>\
3052 {1}<a href='#{0}' class='anchor'></a>\
3053 </h2>{2}", id, title, extra_content)
3056 fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3057 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3060 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3062 let name = m.name.as_ref().unwrap();
3063 let item_type = m.type_();
3064 let id = cx.derive_id(format!("{}.{}", item_type, name));
3065 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3066 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3067 extra = render_spotlight_traits(m)?,
3070 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3071 write!(w, "</code>")?;
3072 render_stability_since(w, m, t)?;
3073 write!(w, "</h3>")?;
3074 document(w, cx, m)?;
3078 if !types.is_empty() {
3079 write_small_section_header(w, "associated-types", "Associated Types",
3080 "<div class='methods'>")?;
3082 trait_item(w, cx, *t, it)?;
3084 write_loading_content(w, "</div>")?;
3087 if !consts.is_empty() {
3088 write_small_section_header(w, "associated-const", "Associated Constants",
3089 "<div class='methods'>")?;
3091 trait_item(w, cx, *t, it)?;
3093 write_loading_content(w, "</div>")?;
3096 // Output the documentation for each function individually
3097 if !required.is_empty() {
3098 write_small_section_header(w, "required-methods", "Required methods",
3099 "<div class='methods'>")?;
3100 for m in &required {
3101 trait_item(w, cx, *m, it)?;
3103 write_loading_content(w, "</div>")?;
3105 if !provided.is_empty() {
3106 write_small_section_header(w, "provided-methods", "Provided methods",
3107 "<div class='methods'>")?;
3108 for m in &provided {
3109 trait_item(w, cx, *m, it)?;
3111 write_loading_content(w, "</div>")?;
3114 // If there are methods directly on this trait object, render them here.
3115 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3117 let cache = cache();
3119 let mut synthetic_types = Vec::new();
3121 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3122 // The DefId is for the first Type found with that name. The bool is
3123 // if any Types with the same name but different DefId have been found.
3124 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3125 for implementor in implementors {
3126 match implementor.inner_impl().for_ {
3127 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3128 clean::BorrowedRef {
3129 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3132 let &mut (prev_did, ref mut has_duplicates) =
3133 implementor_dups.entry(path.last_name()).or_insert((did, false));
3134 if prev_did != did {
3135 *has_duplicates = true;
3142 let (local, foreign) = implementors.iter()
3143 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3144 .map_or(true, |d| cache.paths.contains_key(&d)));
3147 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3148 .partition(|i| i.inner_impl().synthetic);
3150 synthetic.sort_by(compare_impl);
3151 concrete.sort_by(compare_impl);
3153 if !foreign.is_empty() {
3154 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3156 for implementor in foreign {
3157 let assoc_link = AssocItemLink::GotoSource(
3158 implementor.impl_item.def_id,
3159 &implementor.inner_impl().provided_trait_methods
3161 render_impl(w, cx, &implementor, assoc_link,
3162 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3165 write_loading_content(w, "")?;
3168 write_small_section_header(w, "implementors", "Implementors",
3169 "<div class='item-list' id='implementors-list'>")?;
3170 for implementor in concrete {
3171 render_implementor(cx, implementor, w, &implementor_dups)?;
3173 write_loading_content(w, "</div>")?;
3176 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3177 "<div class='item-list' id='synthetic-implementors-list'>")?;
3178 for implementor in synthetic {
3179 synthetic_types.extend(
3180 collect_paths_for_type(implementor.inner_impl().for_.clone())
3182 render_implementor(cx, implementor, w, &implementor_dups)?;
3184 write_loading_content(w, "</div>")?;
3187 // even without any implementations to write in, we still want the heading and list, so the
3188 // implementors javascript file pulled in below has somewhere to write the impls into
3189 write_small_section_header(w, "implementors", "Implementors",
3190 "<div class='item-list' id='implementors-list'>")?;
3191 write_loading_content(w, "</div>")?;
3194 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3195 "<div class='item-list' id='synthetic-implementors-list'>")?;
3196 write_loading_content(w, "</div>")?;
3199 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3200 as_json(&synthetic_types))?;
3202 write!(w, r#"<script type="text/javascript" async
3203 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3205 root_path = vec![".."; cx.current.len()].join("/"),
3206 path = if it.def_id.is_local() {
3207 cx.current.join("/")
3209 let (ref path, _) = cache.external_paths[&it.def_id];
3210 path[..path.len() - 1].join("/")
3212 ty = it.type_().css_class(),
3213 name = *it.name.as_ref().unwrap())?;
3217 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3218 use html::item_type::ItemType::*;
3220 let name = it.name.as_ref().unwrap();
3221 let ty = match it.type_() {
3222 Typedef | AssociatedType => AssociatedType,
3226 let anchor = format!("#{}.{}", ty, name);
3228 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3229 AssocItemLink::Anchor(None) => anchor,
3230 AssocItemLink::GotoSource(did, _) => {
3231 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3236 fn assoc_const(w: &mut fmt::Formatter,
3239 _default: Option<&String>,
3240 link: AssocItemLink) -> fmt::Result {
3241 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3242 VisSpace(&it.visibility),
3243 naive_assoc_href(it, link),
3244 it.name.as_ref().unwrap(),
3249 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3250 bounds: &[clean::GenericBound],
3251 default: Option<&clean::Type>,
3252 link: AssocItemLink) -> fmt::Result {
3253 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3254 naive_assoc_href(it, link),
3255 it.name.as_ref().unwrap())?;
3256 if !bounds.is_empty() {
3257 write!(w, ": {}", GenericBounds(bounds))?
3259 if let Some(default) = default {
3260 write!(w, " = {}", default)?;
3265 fn render_stability_since_raw<'a, T: fmt::Write>(
3267 ver: Option<&'a str>,
3268 containing_ver: Option<&'a str>,
3270 if let Some(v) = ver {
3271 if containing_ver != ver && v.len() > 0 {
3272 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3278 fn render_stability_since(w: &mut fmt::Formatter,
3280 containing_item: &clean::Item) -> fmt::Result {
3281 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3284 fn render_assoc_item(w: &mut fmt::Formatter,
3286 link: AssocItemLink,
3287 parent: ItemType) -> fmt::Result {
3288 fn method(w: &mut fmt::Formatter,
3290 header: hir::FnHeader,
3291 g: &clean::Generics,
3293 link: AssocItemLink,
3296 let name = meth.name.as_ref().unwrap();
3297 let anchor = format!("#{}.{}", meth.type_(), name);
3298 let href = match link {
3299 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3300 AssocItemLink::Anchor(None) => anchor,
3301 AssocItemLink::GotoSource(did, provided_methods) => {
3302 // We're creating a link from an impl-item to the corresponding
3303 // trait-item and need to map the anchored type accordingly.
3304 let ty = if provided_methods.contains(name) {
3310 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3313 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3314 VisSpace(&meth.visibility),
3315 ConstnessSpace(header.constness),
3316 UnsafetySpace(header.unsafety),
3317 AsyncSpace(header.asyncness),
3318 AbiSpace(header.abi),
3321 let (indent, end_newline) = if parent == ItemType::Trait {
3327 render_attributes(w, meth)?;
3328 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3329 {generics}{decl}{where_clause}",
3330 VisSpace(&meth.visibility),
3331 ConstnessSpace(header.constness),
3332 UnsafetySpace(header.unsafety),
3333 AsyncSpace(header.asyncness),
3334 AbiSpace(header.abi),
3343 where_clause = WhereClause {
3350 clean::StrippedItem(..) => Ok(()),
3351 clean::TyMethodItem(ref m) => {
3352 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3354 clean::MethodItem(ref m) => {
3355 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3357 clean::AssociatedConstItem(ref ty, ref default) => {
3358 assoc_const(w, item, ty, default.as_ref(), link)
3360 clean::AssociatedTypeItem(ref bounds, ref default) => {
3361 assoc_type(w, item, bounds, default.as_ref(), link)
3363 _ => panic!("render_assoc_item called on non-associated-item")
3367 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3368 s: &clean::Struct) -> fmt::Result {
3369 wrap_into_docblock(w, |w| {
3370 write!(w, "<pre class='rust struct'>")?;
3371 render_attributes(w, it)?;
3382 document(w, cx, it)?;
3383 let mut fields = s.fields.iter().filter_map(|f| {
3385 clean::StructFieldItem(ref ty) => Some((f, ty)),
3389 if let doctree::Plain = s.struct_type {
3390 if fields.peek().is_some() {
3391 write!(w, "<h2 id='fields' class='fields small-section-header'>
3392 Fields{}<a href='#fields' class='anchor'></a></h2>",
3393 document_non_exhaustive_header(it))?;
3394 document_non_exhaustive(w, it)?;
3395 for (field, ty) in fields {
3396 let id = cx.derive_id(format!("{}.{}",
3397 ItemType::StructField,
3398 field.name.as_ref().unwrap()));
3399 let ns_id = cx.derive_id(format!("{}.{}",
3400 field.name.as_ref().unwrap(),
3401 ItemType::StructField.name_space()));
3402 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3403 <a href=\"#{id}\" class=\"anchor field\"></a>\
3404 <code id=\"{ns_id}\">{name}: {ty}</code>\
3406 item_type = ItemType::StructField,
3409 name = field.name.as_ref().unwrap(),
3411 if let Some(stability_class) = field.stability_class() {
3412 write!(w, "<span class='stab {stab}'></span>",
3413 stab = stability_class)?;
3415 document(w, cx, field)?;
3419 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3422 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3423 s: &clean::Union) -> fmt::Result {
3424 wrap_into_docblock(w, |w| {
3425 write!(w, "<pre class='rust union'>")?;
3426 render_attributes(w, it)?;
3436 document(w, cx, it)?;
3437 let mut fields = s.fields.iter().filter_map(|f| {
3439 clean::StructFieldItem(ref ty) => Some((f, ty)),
3443 if fields.peek().is_some() {
3444 write!(w, "<h2 id='fields' class='fields small-section-header'>
3445 Fields<a href='#fields' class='anchor'></a></h2>")?;
3446 for (field, ty) in fields {
3447 let name = field.name.as_ref().expect("union field name");
3448 let id = format!("{}.{}", ItemType::StructField, name);
3449 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3450 <a href=\"#{id}\" class=\"anchor field\"></a>\
3451 <code>{name}: {ty}</code>\
3455 shortty = ItemType::StructField,
3457 if let Some(stability_class) = field.stability_class() {
3458 write!(w, "<span class='stab {stab}'></span>",
3459 stab = stability_class)?;
3461 document(w, cx, field)?;
3464 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3467 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3468 e: &clean::Enum) -> fmt::Result {
3469 wrap_into_docblock(w, |w| {
3470 write!(w, "<pre class='rust enum'>")?;
3471 render_attributes(w, it)?;
3472 write!(w, "{}enum {}{}{}",
3473 VisSpace(&it.visibility),
3474 it.name.as_ref().unwrap(),
3476 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3477 if e.variants.is_empty() && !e.variants_stripped {
3478 write!(w, " {{}}")?;
3480 write!(w, " {{\n")?;
3481 for v in &e.variants {
3483 let name = v.name.as_ref().unwrap();
3485 clean::VariantItem(ref var) => {
3487 clean::VariantKind::CLike => write!(w, "{}", name)?,
3488 clean::VariantKind::Tuple(ref tys) => {
3489 write!(w, "{}(", name)?;
3490 for (i, ty) in tys.iter().enumerate() {
3492 write!(w, ", ")?
3494 write!(w, "{}", *ty)?;
3498 clean::VariantKind::Struct(ref s) => {
3514 if e.variants_stripped {
3515 write!(w, " // some variants omitted\n")?;
3522 document(w, cx, it)?;
3523 if !e.variants.is_empty() {
3524 write!(w, "<h2 id='variants' class='variants small-section-header'>
3525 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3526 document_non_exhaustive_header(it))?;
3527 document_non_exhaustive(w, it)?;
3528 for variant in &e.variants {
3529 let id = cx.derive_id(format!("{}.{}",
3531 variant.name.as_ref().unwrap()));
3532 let ns_id = cx.derive_id(format!("{}.{}",
3533 variant.name.as_ref().unwrap(),
3534 ItemType::Variant.name_space()));
3535 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3536 <a href=\"#{id}\" class=\"anchor field\"></a>\
3537 <code id='{ns_id}'>{name}",
3540 name = variant.name.as_ref().unwrap())?;
3541 if let clean::VariantItem(ref var) = variant.inner {
3542 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3544 for (i, ty) in tys.iter().enumerate() {
3546 write!(w, ", ")?;
3548 write!(w, "{}", *ty)?;
3553 write!(w, "</code></span>")?;
3554 document(w, cx, variant)?;
3556 use clean::{Variant, VariantKind};
3557 if let clean::VariantItem(Variant {
3558 kind: VariantKind::Struct(ref s)
3559 }) = variant.inner {
3560 let variant_id = cx.derive_id(format!("{}.{}.fields",
3562 variant.name.as_ref().unwrap()));
3563 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3565 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3566 name = variant.name.as_ref().unwrap())?;
3567 for field in &s.fields {
3568 use clean::StructFieldItem;
3569 if let StructFieldItem(ref ty) = field.inner {
3570 let id = cx.derive_id(format!("variant.{}.field.{}",
3571 variant.name.as_ref().unwrap(),
3572 field.name.as_ref().unwrap()));
3573 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3574 variant.name.as_ref().unwrap(),
3575 ItemType::Variant.name_space(),
3576 field.name.as_ref().unwrap(),
3577 ItemType::StructField.name_space()));
3578 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3579 <a href=\"#{id}\" class=\"anchor field\"></a>\
3580 <code id='{ns_id}'>{f}: {t}\
3584 f = field.name.as_ref().unwrap(),
3586 document(w, cx, field)?;
3589 write!(w, "</div></span>")?;
3591 render_stability_since(w, variant, it)?;
3594 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3598 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3599 let name = attr.name();
3602 Some(name.to_string())
3603 } else if let Some(v) = attr.value_str() {
3604 Some(format!("{} = {:?}", name, v.as_str()))
3605 } else if let Some(values) = attr.meta_item_list() {
3606 let display: Vec<_> = values.iter().filter_map(|attr| {
3607 attr.meta_item().and_then(|mi| render_attribute(mi))
3610 if display.len() > 0 {
3611 Some(format!("{}({})", name, display.join(", ")))
3620 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3627 "unsafe_destructor_blind_to_params",
3631 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3632 let mut attrs = String::new();
3634 for attr in &it.attrs.other_attrs {
3635 let name = attr.name();
3636 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3639 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3640 attrs.push_str(&format!("#[{}]\n", s));
3643 if attrs.len() > 0 {
3644 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3649 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3650 g: Option<&clean::Generics>,
3651 ty: doctree::StructType,
3652 fields: &[clean::Item],
3654 structhead: bool) -> fmt::Result {
3656 VisSpace(&it.visibility),
3657 if structhead {"struct "} else {""},
3658 it.name.as_ref().unwrap())?;
3659 if let Some(g) = g {
3664 if let Some(g) = g {
3665 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3667 let mut has_visible_fields = false;
3669 for field in fields {
3670 if let clean::StructFieldItem(ref ty) = field.inner {
3671 write!(w, "\n{} {}{}: {},",
3673 VisSpace(&field.visibility),
3674 field.name.as_ref().unwrap(),
3676 has_visible_fields = true;
3680 if has_visible_fields {
3681 if it.has_stripped_fields().unwrap() {
3682 write!(w, "\n{} // some fields omitted", tab)?;
3684 write!(w, "\n{}", tab)?;
3685 } else if it.has_stripped_fields().unwrap() {
3686 // If there are no visible fields we can just display
3687 // `{ /* fields omitted */ }` to save space.
3688 write!(w, " /* fields omitted */ ")?;
3694 for (i, field) in fields.iter().enumerate() {
3699 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3702 clean::StructFieldItem(ref ty) => {
3703 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3709 if let Some(g) = g {
3710 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3715 // Needed for PhantomData.
3716 if let Some(g) = g {
3717 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3725 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3726 g: Option<&clean::Generics>,
3727 fields: &[clean::Item],
3729 structhead: bool) -> fmt::Result {
3731 VisSpace(&it.visibility),
3732 if structhead {"union "} else {""},
3733 it.name.as_ref().unwrap())?;
3734 if let Some(g) = g {
3735 write!(w, "{}", g)?;
3736 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3739 write!(w, " {{\n{}", tab)?;
3740 for field in fields {
3741 if let clean::StructFieldItem(ref ty) = field.inner {
3742 write!(w, " {}{}: {},\n{}",
3743 VisSpace(&field.visibility),
3744 field.name.as_ref().unwrap(),
3750 if it.has_stripped_fields().unwrap() {
3751 write!(w, " // some fields omitted\n{}", tab)?;
3757 #[derive(Copy, Clone)]
3758 enum AssocItemLink<'a> {
3759 Anchor(Option<&'a str>),
3760 GotoSource(DefId, &'a FxHashSet<String>),
3763 impl<'a> AssocItemLink<'a> {
3764 fn anchor(&self, id: &'a String) -> Self {
3766 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3767 ref other => *other,
3772 enum AssocItemRender<'a> {
3774 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3777 #[derive(Copy, Clone, PartialEq)]
3780 ForDeref { mut_: bool },
3783 fn render_assoc_items(w: &mut fmt::Formatter,
3785 containing_item: &clean::Item,
3787 what: AssocItemRender) -> fmt::Result {
3789 let v = match c.impls.get(&it) {
3791 None => return Ok(()),
3793 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3794 i.inner_impl().trait_.is_none()
3796 if !non_trait.is_empty() {
3797 let render_mode = match what {
3798 AssocItemRender::All => {
3800 <h2 id='methods' class='small-section-header'>\
3801 Methods<a href='#methods' class='anchor'></a>\
3806 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3808 <h2 id='deref-methods' class='small-section-header'>\
3809 Methods from {}<Target = {}>\
3810 <a href='#deref-methods' class='anchor'></a>\
3813 RenderMode::ForDeref { mut_: deref_mut_ }
3816 for i in &non_trait {
3817 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3818 containing_item.stable_since(), true, None)?;
3821 if let AssocItemRender::DerefFor { .. } = what {
3824 if !traits.is_empty() {
3825 let deref_impl = traits.iter().find(|t| {
3826 t.inner_impl().trait_.def_id() == c.deref_trait_did
3828 if let Some(impl_) = deref_impl {
3829 let has_deref_mut = traits.iter().find(|t| {
3830 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3832 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3835 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3837 .partition(|t| t.inner_impl().synthetic);
3838 let (blanket_impl, concrete) = concrete
3840 .partition(|t| t.inner_impl().blanket_impl.is_some());
3842 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3844 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3845 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3846 render_impls(self.0, fmt, &self.1, self.2)
3850 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3851 if !impls.is_empty() {
3853 <h2 id='implementations' class='small-section-header'>\
3854 Trait Implementations<a href='#implementations' class='anchor'></a>\
3856 <div id='implementations-list'>{}</div>", impls)?;
3859 if !synthetic.is_empty() {
3861 <h2 id='synthetic-implementations' class='small-section-header'>\
3862 Auto Trait Implementations\
3863 <a href='#synthetic-implementations' class='anchor'></a>\
3865 <div id='synthetic-implementations-list'>\
3867 render_impls(cx, w, &synthetic, containing_item)?;
3868 write!(w, "</div>")?;
3871 if !blanket_impl.is_empty() {
3873 <h2 id='blanket-implementations' class='small-section-header'>\
3874 Blanket Implementations\
3875 <a href='#blanket-implementations' class='anchor'></a>\
3877 <div id='blanket-implementations-list'>\
3879 render_impls(cx, w, &blanket_impl, containing_item)?;
3880 write!(w, "</div>")?;
3886 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3887 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3888 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3889 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3891 clean::TypedefItem(ref t, true) => Some(&t.type_),
3894 }).next().expect("Expected associated type binding");
3895 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3896 deref_mut_: deref_mut };
3897 if let Some(did) = target.def_id() {
3898 render_assoc_items(w, cx, container_item, did, what)
3900 if let Some(prim) = target.primitive_type() {
3901 if let Some(&did) = cache().primitive_locations.get(&prim) {
3902 render_assoc_items(w, cx, container_item, did, what)?;
3909 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3910 let self_type_opt = match item.inner {
3911 clean::MethodItem(ref method) => method.decl.self_type(),
3912 clean::TyMethodItem(ref method) => method.decl.self_type(),
3916 if let Some(self_ty) = self_type_opt {
3917 let (by_mut_ref, by_box, by_value) = match self_ty {
3918 SelfTy::SelfBorrowed(_, mutability) |
3919 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3920 (mutability == Mutability::Mutable, false, false)
3922 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3923 (false, Some(did) == cache().owned_box_did, false)
3925 SelfTy::SelfValue => (false, false, true),
3926 _ => (false, false, false),
3929 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3935 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3936 let mut out = String::new();
3939 clean::FunctionItem(clean::Function { ref decl, .. }) |
3940 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3941 clean::MethodItem(clean::Method { ref decl, .. }) |
3942 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3943 out = spotlight_decl(decl)?;
3951 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3952 let mut out = String::new();
3953 let mut trait_ = String::new();
3955 if let Some(did) = decl.output.def_id() {
3957 if let Some(impls) = c.impls.get(&did) {
3959 let impl_ = i.inner_impl();
3960 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3963 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3964 <code class=\"content\">",
3966 trait_.push_str(&impl_.for_.to_string());
3969 //use the "where" class here to make it small
3970 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3971 let t_did = impl_.trait_.def_id().unwrap();
3972 for it in &impl_.items {
3973 if let clean::TypedefItem(ref tydef, _) = it.inner {
3974 out.push_str("<span class=\"where fmt-newline\"> ");
3975 assoc_type(&mut out, it, &[],
3977 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
3978 out.push_str(";</span>");
3986 if !out.is_empty() {
3987 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3988 <span class='tooltiptext'>Important traits for {}</span></div>\
3989 <div class=\"content hidden\">",
3991 out.push_str("</code></div></div>");
3997 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3998 render_mode: RenderMode, outer_version: Option<&str>,
3999 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4000 if render_mode == RenderMode::Normal {
4001 let id = cx.derive_id(match i.inner_impl().trait_ {
4002 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4003 None => "impl".to_string(),
4005 if let Some(use_absolute) = use_absolute {
4006 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4007 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4009 for it in &i.inner_impl().items {
4010 if let clean::TypedefItem(ref tydef, _) = it.inner {
4011 write!(w, "<span class=\"where fmt-newline\"> ")?;
4012 assoc_type(w, it, &vec![], Some(&tydef.type_),
4013 AssocItemLink::Anchor(None))?;
4014 write!(w, ";</span>")?;
4018 write!(w, "</code>")?;
4020 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4024 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4025 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4026 render_stability_since_raw(w, since, outer_version)?;
4027 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4028 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4029 l, "goto source code")?;
4031 write!(w, "</h3>")?;
4032 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4033 let mut ids = cx.id_map.borrow_mut();
4034 write!(w, "<div class='docblock'>{}</div>",
4035 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4039 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4040 link: AssocItemLink, render_mode: RenderMode,
4041 is_default_item: bool, outer_version: Option<&str>,
4042 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4043 let item_type = item.type_();
4044 let name = item.name.as_ref().unwrap();
4046 let render_method_item: bool = match render_mode {
4047 RenderMode::Normal => true,
4048 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4051 let (is_hidden, extra_class) = if trait_.is_none() ||
4052 item.doc_value().is_some() ||
4053 item.inner.is_associated() {
4059 clean::MethodItem(clean::Method { ref decl, .. }) |
4060 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4061 // Only render when the method is not static or we allow static methods
4062 if render_method_item {
4063 let id = cx.derive_id(format!("{}.{}", item_type, name));
4064 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4065 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4066 write!(w, "{}", spotlight_decl(decl)?)?;
4067 write!(w, "<code id='{}'>", ns_id)?;
4068 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4069 write!(w, "</code>")?;
4070 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4071 if let Some(l) = (Item { cx, item }).src_href() {
4072 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4073 l, "goto source code")?;
4075 write!(w, "</h4>")?;
4078 clean::TypedefItem(ref tydef, _) => {
4079 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4080 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4081 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4082 write!(w, "<code id='{}'>", ns_id)?;
4083 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4084 write!(w, "</code></h4>")?;
4086 clean::AssociatedConstItem(ref ty, ref default) => {
4087 let id = cx.derive_id(format!("{}.{}", item_type, name));
4088 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4089 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4090 write!(w, "<code id='{}'>", ns_id)?;
4091 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4092 write!(w, "</code>")?;
4093 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4094 if let Some(l) = (Item { cx, item }).src_href() {
4095 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4096 l, "goto source code")?;
4098 write!(w, "</h4>")?;
4100 clean::AssociatedTypeItem(ref bounds, ref default) => {
4101 let id = cx.derive_id(format!("{}.{}", item_type, name));
4102 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4103 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4104 write!(w, "<code id='{}'>", ns_id)?;
4105 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4106 write!(w, "</code></h4>")?;
4108 clean::StrippedItem(..) => return Ok(()),
4109 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4112 if render_method_item || render_mode == RenderMode::Normal {
4113 if !is_default_item {
4114 if let Some(t) = trait_ {
4115 // The trait item may have been stripped so we might not
4116 // find any documentation or stability for it.
4117 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4118 // We need the stability of the item from the trait
4119 // because impls can't have a stability.
4120 document_stability(w, cx, it, is_hidden)?;
4121 if item.doc_value().is_some() {
4122 document_full(w, item, cx, "", is_hidden)?;
4123 } else if show_def_docs {
4124 // In case the item isn't documented,
4125 // provide short documentation from the trait.
4126 document_short(w, cx, it, link, "", is_hidden)?;
4130 document_stability(w, cx, item, is_hidden)?;
4132 document_full(w, item, cx, "", is_hidden)?;
4136 document_stability(w, cx, item, is_hidden)?;
4138 document_short(w, cx, item, link, "", is_hidden)?;
4145 let traits = &cache().traits;
4146 let trait_ = i.trait_did().map(|did| &traits[&did]);
4148 write!(w, "<div class='impl-items'>")?;
4149 for trait_item in &i.inner_impl().items {
4150 doc_impl_item(w, cx, trait_item, link, render_mode,
4151 false, outer_version, trait_, show_def_docs)?;
4154 fn render_default_items(w: &mut fmt::Formatter,
4158 render_mode: RenderMode,
4159 outer_version: Option<&str>,
4160 show_def_docs: bool) -> fmt::Result {
4161 for trait_item in &t.items {
4162 let n = trait_item.name.clone();
4163 if i.items.iter().find(|m| m.name == n).is_some() {
4166 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4167 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4169 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4170 outer_version, None, show_def_docs)?;
4175 // If we've implemented a trait, then also emit documentation for all
4176 // default items which weren't overridden in the implementation block.
4177 if let Some(t) = trait_ {
4178 render_default_items(w, cx, t, &i.inner_impl(),
4179 render_mode, outer_version, show_def_docs)?;
4181 write!(w, "</div>")?;
4186 fn item_existential(
4187 w: &mut fmt::Formatter,
4190 t: &clean::Existential,
4192 write!(w, "<pre class='rust existential'>")?;
4193 render_attributes(w, it)?;
4194 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4195 it.name.as_ref().unwrap(),
4197 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4198 bounds = bounds(&t.bounds))?;
4200 document(w, cx, it)?;
4202 // Render any items associated directly to this alias, as otherwise they
4203 // won't be visible anywhere in the docs. It would be nice to also show
4204 // associated items from the aliased type (see discussion in #32077), but
4205 // we need #14072 to make sense of the generics.
4206 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4209 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4210 t: &clean::Typedef) -> fmt::Result {
4211 write!(w, "<pre class='rust typedef'>")?;
4212 render_attributes(w, it)?;
4213 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4214 it.name.as_ref().unwrap(),
4216 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4219 document(w, cx, it)?;
4221 // Render any items associated directly to this alias, as otherwise they
4222 // won't be visible anywhere in the docs. It would be nice to also show
4223 // associated items from the aliased type (see discussion in #32077), but
4224 // we need #14072 to make sense of the generics.
4225 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4228 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4229 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4230 render_attributes(w, it)?;
4233 " {}type {};\n}}</pre>",
4234 VisSpace(&it.visibility),
4235 it.name.as_ref().unwrap(),
4238 document(w, cx, it)?;
4240 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4243 impl<'a> fmt::Display for Sidebar<'a> {
4244 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4247 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4249 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4250 || it.is_enum() || it.is_mod() || it.is_typedef() {
4251 write!(fmt, "<p class='location'>{}{}</p>",
4253 clean::StructItem(..) => "Struct ",
4254 clean::TraitItem(..) => "Trait ",
4255 clean::PrimitiveItem(..) => "Primitive Type ",
4256 clean::UnionItem(..) => "Union ",
4257 clean::EnumItem(..) => "Enum ",
4258 clean::TypedefItem(..) => "Type Definition ",
4259 clean::ForeignTypeItem => "Foreign Type ",
4260 clean::ModuleItem(..) => if it.is_crate() {
4267 it.name.as_ref().unwrap())?;
4271 if let Some(ref version) = cache().crate_version {
4273 "<div class='block version'>\
4280 write!(fmt, "<div class=\"sidebar-elems\">")?;
4282 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4283 it.name.as_ref().expect("crates always have a name"))?;
4286 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4287 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4288 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4289 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4290 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4291 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4292 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4293 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4297 // The sidebar is designed to display sibling functions, modules and
4298 // other miscellaneous information. since there are lots of sibling
4299 // items (and that causes quadratic growth in large modules),
4300 // we refactor common parts into a shared JavaScript file per module.
4301 // still, we don't move everything into JS because we want to preserve
4302 // as much HTML as possible in order to allow non-JS-enabled browsers
4303 // to navigate the documentation (though slightly inefficiently).
4305 write!(fmt, "<p class='location'>")?;
4306 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4308 write!(fmt, "::<wbr>")?;
4310 write!(fmt, "<a href='{}index.html'>{}</a>",
4311 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4314 write!(fmt, "</p>")?;
4316 // Sidebar refers to the enclosing module, not this module.
4317 let relpath = if it.is_mod() { "../" } else { "" };
4319 "<script>window.sidebarCurrent = {{\
4324 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4325 ty = it.type_().css_class(),
4328 // There is no sidebar-items.js beyond the crate root path
4329 // FIXME maybe dynamic crate loading can be merged here
4331 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4334 // Closes sidebar-elems div.
4335 write!(fmt, "</div>")?;
4341 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4342 if used_links.insert(url.clone()) {
4346 while used_links.insert(format!("{}-{}", url, add)) == false {
4349 format!("{}-{}", url, add)
4355 used_links: &mut FxHashSet<String>,
4357 i.items.iter().filter_map(|item| {
4359 // Maybe check with clean::Visibility::Public as well?
4360 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4361 if !for_deref || should_render_item(item, false) {
4362 Some(format!("<a href=\"#{}\">{}</a>",
4363 get_next_url(used_links, format!("method.{}", name)),
4371 }).collect::<Vec<_>>()
4374 // The point is to url encode any potential character from a type with genericity.
4375 fn small_url_encode(s: &str) -> String {
4376 s.replace("<", "%3C")
4377 .replace(">", "%3E")
4378 .replace(" ", "%20")
4379 .replace("?", "%3F")
4380 .replace("'", "%27")
4381 .replace("&", "%26")
4382 .replace(",", "%2C")
4383 .replace(":", "%3A")
4384 .replace(";", "%3B")
4385 .replace("[", "%5B")
4386 .replace("]", "%5D")
4387 .replace("\"", "%22")
4390 fn sidebar_assoc_items(it: &clean::Item) -> String {
4391 let mut out = String::new();
4393 if let Some(v) = c.impls.get(&it.def_id) {
4394 let mut used_links = FxHashSet::default();
4397 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4399 .filter(|i| i.inner_impl().trait_.is_none())
4400 .flat_map(move |i| get_methods(i.inner_impl(),
4402 &mut used_links_bor.borrow_mut()))
4403 .collect::<String>();
4404 if !ret.is_empty() {
4405 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4406 </a><div class=\"sidebar-links\">{}</div>", ret));
4410 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4411 if let Some(impl_) = v.iter()
4412 .filter(|i| i.inner_impl().trait_.is_some())
4413 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4414 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4416 clean::TypedefItem(ref t, true) => Some(&t.type_),
4420 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4421 c.primitive_locations.get(&prim).cloned()
4422 })).and_then(|did| c.impls.get(&did));
4423 if let Some(impls) = inner_impl {
4424 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4425 out.push_str(&format!("Methods from {}<Target={}>",
4426 Escape(&format!("{:#}",
4427 impl_.inner_impl().trait_.as_ref().unwrap())),
4428 Escape(&format!("{:#}", target))));
4429 out.push_str("</a>");
4430 let ret = impls.iter()
4431 .filter(|i| i.inner_impl().trait_.is_none())
4432 .flat_map(|i| get_methods(i.inner_impl(),
4435 .collect::<String>();
4436 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4440 let format_impls = |impls: Vec<&Impl>| {
4441 let mut links = FxHashSet::default();
4445 let is_negative_impl = is_negative_impl(i.inner_impl());
4446 if let Some(ref i) = i.inner_impl().trait_ {
4447 let i_display = format!("{:#}", i);
4448 let out = Escape(&i_display);
4449 let encoded = small_url_encode(&format!("{:#}", i));
4450 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4452 if is_negative_impl { "!" } else { "" },
4454 if links.insert(generated.clone()) {
4463 .collect::<String>()
4466 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4468 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4469 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4471 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4473 let concrete_format = format_impls(concrete);
4474 let synthetic_format = format_impls(synthetic);
4475 let blanket_format = format_impls(blanket_impl);
4477 if !concrete_format.is_empty() {
4478 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4479 Trait Implementations</a>");
4480 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4483 if !synthetic_format.is_empty() {
4484 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4485 Auto Trait Implementations</a>");
4486 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4489 if !blanket_format.is_empty() {
4490 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4491 Blanket Implementations</a>");
4492 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4500 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4501 s: &clean::Struct) -> fmt::Result {
4502 let mut sidebar = String::new();
4503 let fields = get_struct_fields_name(&s.fields);
4505 if !fields.is_empty() {
4506 if let doctree::Plain = s.struct_type {
4507 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4508 <div class=\"sidebar-links\">{}</div>", fields));
4512 sidebar.push_str(&sidebar_assoc_items(it));
4514 if !sidebar.is_empty() {
4515 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4520 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4522 clean::ItemEnum::ImplItem(ref i) => {
4523 if let Some(ref trait_) = i.trait_ {
4524 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4533 fn is_negative_impl(i: &clean::Impl) -> bool {
4534 i.polarity == Some(clean::ImplPolarity::Negative)
4537 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4538 t: &clean::Trait) -> fmt::Result {
4539 let mut sidebar = String::new();
4545 Some(ref name) if m.is_associated_type() => {
4546 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4552 .collect::<String>();
4553 let consts = t.items
4557 Some(ref name) if m.is_associated_const() => {
4558 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4564 .collect::<String>();
4565 let required = t.items
4569 Some(ref name) if m.is_ty_method() => {
4570 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4576 .collect::<String>();
4577 let provided = t.items
4581 Some(ref name) if m.is_method() => {
4582 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4587 .collect::<String>();
4589 if !types.is_empty() {
4590 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4591 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4594 if !consts.is_empty() {
4595 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4596 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4599 if !required.is_empty() {
4600 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4601 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4604 if !provided.is_empty() {
4605 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4606 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4612 if let Some(implementors) = c.implementors.get(&it.def_id) {
4613 let res = implementors.iter()
4614 .filter(|i| i.inner_impl().for_.def_id()
4615 .map_or(false, |d| !c.paths.contains_key(&d)))
4617 match extract_for_impl_name(&i.impl_item) {
4618 Some((ref name, ref url)) => {
4619 Some(format!("<a href=\"#impl-{}\">{}</a>",
4620 small_url_encode(url),
4626 .collect::<String>();
4627 if !res.is_empty() {
4628 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4629 Implementations on Foreign Types</a><div \
4630 class=\"sidebar-links\">{}</div>",
4635 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4637 sidebar.push_str("<a class=\"sidebar-title\" \
4638 href=\"#synthetic-implementors\">Auto Implementors</a>");
4641 sidebar.push_str(&sidebar_assoc_items(it));
4643 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4646 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4647 _p: &clean::PrimitiveType) -> fmt::Result {
4648 let sidebar = sidebar_assoc_items(it);
4650 if !sidebar.is_empty() {
4651 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4656 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4657 _t: &clean::Typedef) -> fmt::Result {
4658 let sidebar = sidebar_assoc_items(it);
4660 if !sidebar.is_empty() {
4661 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4666 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4668 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4673 .filter_map(|f| match f.name {
4674 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4675 {name}</a>", name=name)),
4681 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4682 u: &clean::Union) -> fmt::Result {
4683 let mut sidebar = String::new();
4684 let fields = get_struct_fields_name(&u.fields);
4686 if !fields.is_empty() {
4687 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4688 <div class=\"sidebar-links\">{}</div>", fields));
4691 sidebar.push_str(&sidebar_assoc_items(it));
4693 if !sidebar.is_empty() {
4694 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4699 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4700 e: &clean::Enum) -> fmt::Result {
4701 let mut sidebar = String::new();
4703 let variants = e.variants.iter()
4704 .filter_map(|v| match v.name {
4705 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4706 </a>", name = name)),
4709 .collect::<String>();
4710 if !variants.is_empty() {
4711 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4712 <div class=\"sidebar-links\">{}</div>", variants));
4715 sidebar.push_str(&sidebar_assoc_items(it));
4717 if !sidebar.is_empty() {
4718 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4723 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4725 ItemType::ExternCrate |
4726 ItemType::Import => ("reexports", "Re-exports"),
4727 ItemType::Module => ("modules", "Modules"),
4728 ItemType::Struct => ("structs", "Structs"),
4729 ItemType::Union => ("unions", "Unions"),
4730 ItemType::Enum => ("enums", "Enums"),
4731 ItemType::Function => ("functions", "Functions"),
4732 ItemType::Typedef => ("types", "Type Definitions"),
4733 ItemType::Static => ("statics", "Statics"),
4734 ItemType::Constant => ("constants", "Constants"),
4735 ItemType::Trait => ("traits", "Traits"),
4736 ItemType::Impl => ("impls", "Implementations"),
4737 ItemType::TyMethod => ("tymethods", "Type Methods"),
4738 ItemType::Method => ("methods", "Methods"),
4739 ItemType::StructField => ("fields", "Struct Fields"),
4740 ItemType::Variant => ("variants", "Variants"),
4741 ItemType::Macro => ("macros", "Macros"),
4742 ItemType::Primitive => ("primitives", "Primitive Types"),
4743 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4744 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4745 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4746 ItemType::Keyword => ("keywords", "Keywords"),
4747 ItemType::Existential => ("existentials", "Existentials"),
4748 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4749 ItemType::ProcDerive => ("derives", "Derive Macros"),
4753 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4754 items: &[clean::Item]) -> fmt::Result {
4755 let mut sidebar = String::new();
4757 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4758 it.type_() == ItemType::Import) {
4759 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4761 name = "Re-exports"));
4764 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4765 // to print its headings
4766 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4767 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4768 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4769 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4770 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4771 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4772 let (short, name) = item_ty_to_strs(&myty);
4773 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4779 if !sidebar.is_empty() {
4780 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4785 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4786 let sidebar = sidebar_assoc_items(it);
4787 if !sidebar.is_empty() {
4788 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4793 impl<'a> fmt::Display for Source<'a> {
4794 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4795 let Source(s) = *self;
4796 let lines = s.lines().count();
4798 let mut tmp = lines;
4803 write!(fmt, "<pre class=\"line-numbers\">")?;
4804 for i in 1..=lines {
4805 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4807 write!(fmt, "</pre>")?;
4809 highlight::render_with_highlighting(s, None, None, None))?;
4814 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4815 t: &clean::Macro) -> fmt::Result {
4816 wrap_into_docblock(w, |w| {
4817 w.write_str(&highlight::render_with_highlighting(&t.source,
4825 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4828 let name = it.name.as_ref().expect("proc-macros always have names");
4830 MacroKind::Bang => {
4831 write!(w, "<pre class='rust macro'>")?;
4832 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4833 write!(w, "</pre>")?;
4835 MacroKind::Attr => {
4836 write!(w, "<pre class='rust attr'>")?;
4837 write!(w, "#[{}]", name)?;
4838 write!(w, "</pre>")?;
4840 MacroKind::Derive => {
4841 write!(w, "<pre class='rust derive'>")?;
4842 write!(w, "#[derive({})]", name)?;
4843 if !m.helpers.is_empty() {
4844 writeln!(w, "\n{{")?;
4845 writeln!(w, " // Attributes available to this derive:")?;
4846 for attr in &m.helpers {
4847 writeln!(w, " #[{}]", attr)?;
4851 write!(w, "</pre>")?;
4858 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4860 _p: &clean::PrimitiveType) -> fmt::Result {
4861 document(w, cx, it)?;
4862 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4865 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4867 _p: &str) -> fmt::Result {
4871 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4873 fn make_item_keywords(it: &clean::Item) -> String {
4874 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4877 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4878 let decl = match item.inner {
4879 clean::FunctionItem(ref f) => &f.decl,
4880 clean::MethodItem(ref m) => &m.decl,
4881 clean::TyMethodItem(ref m) => &m.decl,
4885 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4886 let output = match decl.output {
4887 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4891 Some(IndexItemFunctionType { inputs: inputs, output: output })
4894 fn get_index_type(clean_type: &clean::Type) -> Type {
4896 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4897 generics: get_generics(clean_type),
4902 /// Returns a list of all paths used in the type.
4903 /// This is used to help deduplicate imported impls
4904 /// for reexported types. If any of the contained
4905 /// types are re-exported, we don't use the corresponding
4906 /// entry from the js file, as inlining will have already
4907 /// picked up the impl
4908 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4909 let mut out = Vec::new();
4910 let mut visited = FxHashSet::default();
4911 let mut work = VecDeque::new();
4912 let cache = cache();
4914 work.push_back(first_ty);
4916 while let Some(ty) = work.pop_front() {
4917 if !visited.insert(ty.clone()) {
4922 clean::Type::ResolvedPath { did, .. } => {
4923 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4924 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4928 out.push(path.join("::"));
4934 clean::Type::Tuple(tys) => {
4935 work.extend(tys.into_iter());
4937 clean::Type::Slice(ty) => {
4938 work.push_back(*ty);
4940 clean::Type::Array(ty, _) => {
4941 work.push_back(*ty);
4943 clean::Type::Unique(ty) => {
4944 work.push_back(*ty);
4946 clean::Type::RawPointer(_, ty) => {
4947 work.push_back(*ty);
4949 clean::Type::BorrowedRef { type_, .. } => {
4950 work.push_back(*type_);
4952 clean::Type::QPath { self_type, trait_, .. } => {
4953 work.push_back(*self_type);
4954 work.push_back(*trait_);
4962 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4964 clean::ResolvedPath { ref path, .. } => {
4965 let segments = &path.segments;
4966 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4967 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4968 clean_type, accept_generic
4970 Some(path_segment.name.clone())
4972 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4973 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4974 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4975 // FIXME: add all from clean::Type.
4980 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4981 clean_type.generics()
4983 let r = types.iter()
4984 .filter_map(|t| get_index_type_name(t, false))
4985 .map(|s| s.to_ascii_lowercase())
4986 .collect::<Vec<_>>();
4995 pub fn cache() -> Arc<Cache> {
4996 CACHE_KEY.with(|c| c.borrow().clone())
5001 fn test_name_key() {
5002 assert_eq!(name_key("0"), ("", 0, 1));
5003 assert_eq!(name_key("123"), ("", 123, 0));
5004 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5005 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5006 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5007 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5008 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5009 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5014 fn test_name_sorting() {
5015 let names = ["Apple",
5017 "Fruit", "Fruit0", "Fruit00",
5018 "Fruit1", "Fruit01",
5019 "Fruit2", "Fruit02",
5024 let mut sorted = names.to_owned();
5025 sorted.sort_by_key(|&s| name_key(s));
5026 assert_eq!(names, sorted);