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, Function, 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 pub struct SlashChecker<'a>(pub &'a str);
78 impl<'a> Display for SlashChecker<'a> {
79 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
80 if !self.0.ends_with("/") && !self.0.is_empty() {
81 write!(f, "{}/", self.0)
83 write!(f, "{}", self.0)
88 /// Major driving force in all rustdoc rendering. This contains information
89 /// about where in the tree-like hierarchy rendering is occurring and controls
90 /// how the current page is being rendered.
92 /// It is intended that this context is a lightweight object which can be fairly
93 /// easily cloned because it is cloned per work-job (about once per item in the
97 /// Current hierarchy of components leading down to what's currently being
99 pub current: Vec<String>,
100 /// The current destination folder of where HTML artifacts should be placed.
101 /// This changes as the context descends into the module hierarchy.
103 /// A flag, which when `true`, will render pages which redirect to the
104 /// real location of an item. This is used to allow external links to
105 /// publicly reused items to redirect to the right location.
106 pub render_redirect_pages: bool,
107 pub codes: ErrorCodes,
108 /// The map used to ensure all generated 'id=' attributes are unique.
109 id_map: Rc<RefCell<IdMap>>,
110 pub shared: Arc<SharedContext>,
113 struct SharedContext {
114 /// The path to the crate root source minus the file name.
115 /// Used for simplifying paths to the highlighted source code files.
116 pub src_root: PathBuf,
117 /// This describes the layout of each page, and is not modified after
118 /// creation of the context (contains info like the favicon and added html).
119 pub layout: layout::Layout,
120 /// This flag indicates whether `[src]` links should be generated or not. If
121 /// the source files are present in the html rendering, then this will be
123 pub include_sources: bool,
124 /// The local file sources we've emitted and their respective url-paths.
125 pub local_sources: FxHashMap<PathBuf, String>,
126 /// All the passes that were run on this crate.
127 pub passes: FxHashSet<String>,
128 /// The base-URL of the issue tracker for when an item has been tagged with
130 pub issue_tracker_base_url: Option<String>,
131 /// The given user css file which allow to customize the generated
132 /// documentation theme.
133 pub css_file_extension: Option<PathBuf>,
134 /// The directories that have already been created in this doc run. Used to reduce the number
135 /// of spurious `create_dir_all` calls.
136 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
137 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
138 /// should be ordered alphabetically or in order of appearance (in the source code).
139 pub sort_modules_alphabetically: bool,
140 /// Additional themes to be added to the generated docs.
141 pub themes: Vec<PathBuf>,
142 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
144 pub resource_suffix: String,
145 /// Optional path string to be used to load static files on output pages. If not set, uses
146 /// combinations of `../` to reach the documentation root.
147 pub static_root_path: Option<String>,
148 /// If false, the `select` element to have search filtering by crates on rendered docs
149 /// won't be generated.
150 pub generate_search_filter: bool,
154 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
155 let mut dirs = self.created_dirs.borrow_mut();
156 if !dirs.contains(dst) {
157 fs::create_dir_all(dst)?;
158 dirs.insert(dst.to_path_buf());
166 /// Returns `true` if the `collapse-docs` pass was run on this crate.
167 pub fn was_collapsed(&self) -> bool {
168 self.passes.contains("collapse-docs")
171 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
172 /// `collapsed_doc_value` of the given item.
173 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
174 if self.was_collapsed() {
175 item.collapsed_doc_value().map(|s| s.into())
177 item.doc_value().map(|s| s.into())
182 /// Indicates where an external crate can be found.
183 pub enum ExternalLocation {
184 /// Remote URL root of the external crate
186 /// This external crate can be found in the local doc/ folder
188 /// The external crate could not be found.
192 /// Metadata about implementations for a type or trait.
193 #[derive(Clone, Debug)]
195 pub impl_item: clean::Item,
199 fn inner_impl(&self) -> &clean::Impl {
200 match self.impl_item.inner {
201 clean::ImplItem(ref impl_) => impl_,
202 _ => panic!("non-impl item found in impl")
206 fn trait_did(&self) -> Option<DefId> {
207 self.inner_impl().trait_.def_id()
214 pub error: io::Error,
217 impl error::Error for Error {
218 fn description(&self) -> &str {
219 self.error.description()
223 impl Display for Error {
224 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
225 write!(f, "\"{}\": {}", self.file.display(), self.error)
230 pub fn new(e: io::Error, file: &Path) -> Error {
232 file: file.to_path_buf(),
238 macro_rules! try_none {
239 ($e:expr, $file:expr) => ({
243 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
249 macro_rules! try_err {
250 ($e:expr, $file:expr) => ({
253 Err(e) => return Err(Error::new(e, $file)),
258 /// This cache is used to store information about the `clean::Crate` being
259 /// rendered in order to provide more useful documentation. This contains
260 /// information like all implementors of a trait, all traits a type implements,
261 /// documentation for all known traits, etc.
263 /// This structure purposefully does not implement `Clone` because it's intended
264 /// to be a fairly large and expensive structure to clone. Instead this adheres
265 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
266 /// rendering threads.
269 /// Mapping of typaram ids to the name of the type parameter. This is used
270 /// when pretty-printing a type (so pretty-printing doesn't have to
271 /// painfully maintain a context like this)
272 pub typarams: FxHashMap<DefId, String>,
274 /// Maps a type ID to all known implementations for that type. This is only
275 /// recognized for intra-crate `ResolvedPath` types, and is used to print
276 /// out extra documentation on the page of an enum/struct.
278 /// The values of the map are a list of implementations and documentation
279 /// found on that implementation.
280 pub impls: FxHashMap<DefId, Vec<Impl>>,
282 /// Maintains a mapping of local crate `NodeId`s to the fully qualified name
283 /// and "short type description" of that node. This is used when generating
284 /// URLs when a type is being linked to. External paths are not located in
285 /// this map because the `External` type itself has all the information
287 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
289 /// Similar to `paths`, but only holds external paths. This is only used for
290 /// generating explicit hyperlinks to other crates.
291 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
293 /// Maps local `DefId`s of exported types to fully qualified paths.
294 /// Unlike 'paths', this mapping ignores any renames that occur
295 /// due to 'use' statements.
297 /// This map is used when writing out the special 'implementors'
298 /// javascript file. By using the exact path that the type
299 /// is declared with, we ensure that each path will be identical
300 /// to the path used if the corresponding type is inlined. By
301 /// doing this, we can detect duplicate impls on a trait page, and only display
302 /// the impl for the inlined type.
303 pub exact_paths: FxHashMap<DefId, Vec<String>>,
305 /// This map contains information about all known traits of this crate.
306 /// Implementations of a crate should inherit the documentation of the
307 /// parent trait if no extra documentation is specified, and default methods
308 /// should show up in documentation about trait implementations.
309 pub traits: FxHashMap<DefId, clean::Trait>,
311 /// When rendering traits, it's often useful to be able to list all
312 /// implementors of the trait, and this mapping is exactly, that: a mapping
313 /// of trait ids to the list of known implementors of the trait
314 pub implementors: FxHashMap<DefId, Vec<Impl>>,
316 /// Cache of where external crate documentation can be found.
317 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
319 /// Cache of where documentation for primitives can be found.
320 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
322 // Note that external items for which `doc(hidden)` applies to are shown as
323 // non-reachable while local items aren't. This is because we're reusing
324 // the access levels from the privacy check pass.
325 pub access_levels: AccessLevels<DefId>,
327 /// The version of the crate being documented, if given from the `--crate-version` flag.
328 pub crate_version: Option<String>,
330 // Private fields only used when initially crawling a crate to build a cache
333 parent_stack: Vec<DefId>,
334 parent_is_trait_impl: bool,
335 search_index: Vec<IndexItem>,
337 deref_trait_did: Option<DefId>,
338 deref_mut_trait_did: Option<DefId>,
339 owned_box_did: Option<DefId>,
340 masked_crates: FxHashSet<CrateNum>,
342 // In rare case where a structure is defined in one module but implemented
343 // in another, if the implementing module is parsed before defining module,
344 // then the fully qualified name of the structure isn't presented in `paths`
345 // yet when its implementation methods are being indexed. Caches such methods
346 // and their parent id here and indexes them at the end of crate parsing.
347 orphan_impl_items: Vec<(DefId, clean::Item)>,
349 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
350 // even though the trait itself is not exported. This can happen if a trait
351 // was defined in function/expression scope, since the impl will be picked
352 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
353 // crawl. In order to prevent crashes when looking for spotlight traits or
354 // when gathering trait documentation on a type, hold impls here while
355 // folding and add them to the cache later on if we find the trait.
356 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
358 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
359 /// we need the alias element to have an array of items.
360 aliases: FxHashMap<String, Vec<IndexItem>>,
363 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
364 /// Later on moved into `CACHE_KEY`.
366 pub struct RenderInfo {
367 pub inlined: FxHashSet<DefId>,
368 pub external_paths: ::core::ExternalPaths,
369 pub external_typarams: FxHashMap<DefId, String>,
370 pub exact_paths: FxHashMap<DefId, Vec<String>>,
371 pub access_levels: AccessLevels<DefId>,
372 pub deref_trait_did: Option<DefId>,
373 pub deref_mut_trait_did: Option<DefId>,
374 pub owned_box_did: Option<DefId>,
377 /// Helper struct to render all source code to HTML pages
378 struct SourceCollector<'a> {
379 scx: &'a mut SharedContext,
381 /// Root destination to place all HTML output into
385 /// Wrapper struct to render the source code of a file. This will do things like
386 /// adding line numbers to the left-hand side.
387 struct Source<'a>(&'a str);
389 // Helper structs for rendering items/sidebars and carrying along contextual
392 #[derive(Copy, Clone)]
395 item: &'a clean::Item,
398 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
400 /// Struct representing one entry in the JS search index. These are all emitted
401 /// by hand to a large JS file at the end of cache-creation.
408 parent: Option<DefId>,
409 parent_idx: Option<usize>,
410 search_type: Option<IndexItemFunctionType>,
413 impl ToJson for IndexItem {
414 fn to_json(&self) -> Json {
415 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
417 let mut data = Vec::with_capacity(6);
418 data.push((self.ty as usize).to_json());
419 data.push(self.name.to_json());
420 data.push(self.path.to_json());
421 data.push(self.desc.to_json());
422 data.push(self.parent_idx.to_json());
423 data.push(self.search_type.to_json());
429 /// A type used for the search index.
432 name: Option<String>,
433 generics: Option<Vec<String>>,
436 impl ToJson for Type {
437 fn to_json(&self) -> Json {
440 let mut data = Vec::with_capacity(2);
441 data.push(name.to_json());
442 if let Some(ref generics) = self.generics {
443 data.push(generics.to_json());
452 /// Full type of functions/methods in the search index.
454 struct IndexItemFunctionType {
456 output: Option<Type>,
459 impl ToJson for IndexItemFunctionType {
460 fn to_json(&self) -> Json {
461 // If we couldn't figure out a type, just write `null`.
462 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
465 let mut data = Vec::with_capacity(2);
466 data.push(self.inputs.to_json());
467 if let Some(ref output) = self.output {
468 data.push(output.to_json());
475 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
476 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
478 pub fn initial_ids() -> Vec<String> {
490 "synthetic-implementors",
492 "synthetic-implementors-list",
496 ].into_iter().map(|id| (String::from(*id))).collect()
499 /// Generates the documentation for `crate` into the directory `dst`
500 pub fn run(mut krate: clean::Crate,
501 options: RenderOptions,
502 passes: FxHashSet<String>,
503 renderinfo: RenderInfo,
504 diag: &errors::Handler) -> Result<(), Error> {
505 // need to save a copy of the options for rendering the index page
506 let md_opts = options.clone();
512 sort_modules_alphabetically,
515 extern_html_root_urls,
518 generate_search_filter,
522 let src_root = match krate.src {
523 FileName::Real(ref p) => match p.parent() {
524 Some(p) => p.to_path_buf(),
525 None => PathBuf::new(),
529 let mut scx = SharedContext {
532 include_sources: true,
533 local_sources: Default::default(),
534 issue_tracker_base_url: None,
535 layout: layout::Layout {
537 favicon: String::new(),
539 krate: krate.name.clone(),
541 css_file_extension: extension_css,
542 created_dirs: Default::default(),
543 sort_modules_alphabetically,
547 generate_search_filter,
550 // If user passed in `--playground-url` arg, we fill in crate name here
551 if let Some(url) = playground_url {
552 markdown::PLAYGROUND.with(|slot| {
553 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
557 // Crawl the crate attributes looking for attributes which control how we're
558 // going to emit HTML
559 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
560 for attr in attrs.lists("doc") {
561 let name = attr.name().map(|s| s.as_str());
562 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
563 (Some("html_favicon_url"), Some(s)) => {
564 scx.layout.favicon = s.to_string();
566 (Some("html_logo_url"), Some(s)) => {
567 scx.layout.logo = s.to_string();
569 (Some("html_playground_url"), Some(s)) => {
570 markdown::PLAYGROUND.with(|slot| {
571 let name = krate.name.clone();
572 *slot.borrow_mut() = Some((Some(name), s.to_string()));
575 (Some("issue_tracker_base_url"), Some(s)) => {
576 scx.issue_tracker_base_url = Some(s.to_string());
578 (Some("html_no_source"), None) if attr.is_word() => {
579 scx.include_sources = false;
586 try_err!(fs::create_dir_all(&dst), &dst);
587 krate = render_sources(&dst, &mut scx, krate)?;
591 render_redirect_pages: false,
592 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
593 id_map: Rc::new(RefCell::new(id_map)),
594 shared: Arc::new(scx),
597 // Crawl the crate to build various caches used for the output
609 let external_paths = external_paths.into_iter()
610 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
613 let mut cache = Cache {
614 impls: Default::default(),
617 paths: Default::default(),
618 implementors: Default::default(),
620 parent_stack: Vec::new(),
621 search_index: Vec::new(),
622 parent_is_trait_impl: false,
623 extern_locations: Default::default(),
624 primitive_locations: Default::default(),
627 crate_version: krate.version.take(),
628 orphan_impl_items: Vec::new(),
629 orphan_trait_impls: Vec::new(),
630 traits: krate.external_traits.lock().replace(Default::default()),
634 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
635 typarams: external_typarams,
636 aliases: Default::default(),
639 // Cache where all our extern crates are located
640 for &(n, ref e) in &krate.externs {
641 let src_root = match e.src {
642 FileName::Real(ref p) => match p.parent() {
643 Some(p) => p.to_path_buf(),
644 None => PathBuf::new(),
648 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
649 cache.extern_locations.insert(n, (e.name.clone(), src_root,
650 extern_location(e, extern_url, &cx.dst)));
652 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
653 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
656 // Cache where all known primitives have their documentation located.
658 // Favor linking to as local extern as possible, so iterate all crates in
659 // reverse topological order.
660 for &(_, ref e) in krate.externs.iter().rev() {
661 for &(def_id, prim, _) in &e.primitives {
662 cache.primitive_locations.insert(prim, def_id);
665 for &(def_id, prim, _) in &krate.primitives {
666 cache.primitive_locations.insert(prim, def_id);
669 cache.stack.push(krate.name.clone());
670 krate = cache.fold_crate(krate);
672 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
673 if cache.traits.contains_key(&trait_did) {
675 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
680 // Build our search index
681 let index = build_index(&krate, &mut cache);
683 // Freeze the cache now that the index has been built. Put an Arc into TLS
684 // for future parallelization opportunities
685 let cache = Arc::new(cache);
686 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
687 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
689 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
691 // And finally render the whole crate's documentation
695 /// Builds the search index from the collected metadata
696 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
697 let mut nodeid_to_pathid = FxHashMap::default();
698 let mut crate_items = Vec::with_capacity(cache.search_index.len());
699 let mut crate_paths = Vec::<Json>::new();
701 let Cache { ref mut search_index,
702 ref orphan_impl_items,
703 ref mut paths, .. } = *cache;
705 // Attach all orphan items to the type's definition if the type
706 // has since been learned.
707 for &(did, ref item) in orphan_impl_items {
708 if let Some(&(ref fqp, _)) = paths.get(&did) {
709 search_index.push(IndexItem {
711 name: item.name.clone().unwrap(),
712 path: fqp[..fqp.len() - 1].join("::"),
713 desc: plain_summary_line_short(item.doc_value()),
716 search_type: get_index_search_type(&item),
721 // Reduce `NodeId` in paths into smaller sequential numbers,
722 // and prune the paths that do not appear in the index.
723 let mut lastpath = String::new();
724 let mut lastpathid = 0usize;
726 for item in search_index {
727 item.parent_idx = item.parent.map(|nodeid| {
728 if nodeid_to_pathid.contains_key(&nodeid) {
729 *nodeid_to_pathid.get(&nodeid).unwrap()
731 let pathid = lastpathid;
732 nodeid_to_pathid.insert(nodeid, pathid);
735 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
736 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
741 // Omit the parent path if it is same to that of the prior item.
742 if lastpath == item.path {
745 lastpath = item.path.clone();
747 crate_items.push(item.to_json());
750 let crate_doc = krate.module.as_ref().map(|module| {
751 plain_summary_line_short(module.doc_value())
752 }).unwrap_or(String::new());
754 let mut crate_data = BTreeMap::new();
755 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
756 crate_data.insert("i".to_owned(), Json::Array(crate_items));
757 crate_data.insert("p".to_owned(), Json::Array(crate_paths));
759 // Collect the index into a string
760 format!("searchIndex[{}] = {};",
761 as_json(&krate.name),
762 Json::Object(crate_data))
767 krate: &clean::Crate,
769 search_index: String,
770 options: &RenderOptions,
771 diag: &errors::Handler,
772 ) -> Result<(), Error> {
773 // Write out the shared files. Note that these are shared among all rustdoc
774 // docs placed in the output directory, so this needs to be a synchronized
775 // operation with respect to all other rustdocs running around.
776 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
778 // Add all the static files. These may already exist, but we just
779 // overwrite them anyway to make sure that they're fresh and up-to-date.
781 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
782 static_files::RUSTDOC_CSS,
783 options.enable_minification)?;
784 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
785 static_files::SETTINGS_CSS,
786 options.enable_minification)?;
787 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
788 static_files::NOSCRIPT_CSS,
789 options.enable_minification)?;
791 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
792 // then we'll run over the "official" styles.
793 let mut themes: FxHashSet<String> = FxHashSet::default();
795 for entry in &cx.shared.themes {
796 let content = try_err!(fs::read(&entry), &entry);
797 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
798 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
799 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
800 content.as_slice())?;
801 themes.insert(theme.to_owned());
804 if (*cx.shared).layout.logo.is_empty() {
805 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
806 static_files::RUST_LOGO)?;
808 if (*cx.shared).layout.favicon.is_empty() {
809 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
810 static_files::RUST_FAVICON)?;
812 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
813 static_files::BRUSH_SVG)?;
814 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
815 static_files::WHEEL_SVG)?;
816 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
817 static_files::DOWN_ARROW_SVG)?;
818 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
819 static_files::themes::LIGHT,
820 options.enable_minification)?;
821 themes.insert("light".to_owned());
822 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
823 static_files::themes::DARK,
824 options.enable_minification)?;
825 themes.insert("dark".to_owned());
827 let mut themes: Vec<&String> = themes.iter().collect();
829 // To avoid theme switch latencies as much as possible, we put everything theme related
830 // at the beginning of the html files into another js file.
831 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
833 r#"var themes = document.getElementById("theme-choices");
834 var themePicker = document.getElementById("theme-picker");
836 function switchThemeButtonState() {{
837 if (themes.style.display === "block") {{
838 themes.style.display = "none";
839 themePicker.style.borderBottomRightRadius = "3px";
840 themePicker.style.borderBottomLeftRadius = "3px";
842 themes.style.display = "block";
843 themePicker.style.borderBottomRightRadius = "0";
844 themePicker.style.borderBottomLeftRadius = "0";
848 function handleThemeButtonsBlur(e) {{
849 var active = document.activeElement;
850 var related = e.relatedTarget;
852 if (active.id !== "themePicker" &&
853 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
855 (related.id !== "themePicker" &&
856 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
857 switchThemeButtonState();
861 themePicker.onclick = switchThemeButtonState;
862 themePicker.onblur = handleThemeButtonsBlur;
863 [{}].forEach(function(item) {{
864 var but = document.createElement('button');
865 but.innerHTML = item;
866 but.onclick = function(el) {{
867 switchTheme(currentTheme, mainTheme, item);
869 but.onblur = handleThemeButtonsBlur;
870 themes.appendChild(but);
873 .map(|s| format!("\"{}\"", s))
874 .collect::<Vec<String>>()
875 .join(",")).as_bytes(),
878 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
879 static_files::MAIN_JS,
880 options.enable_minification)?;
881 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
882 static_files::SETTINGS_JS,
883 options.enable_minification)?;
884 if cx.shared.include_sources {
885 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
886 static_files::sidebar::SOURCE_SCRIPT,
887 options.enable_minification)?;
891 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
892 &format!("var resourcesSuffix = \"{}\";{}",
893 cx.shared.resource_suffix,
894 static_files::STORAGE_JS),
895 options.enable_minification)?;
898 if let Some(ref css) = cx.shared.css_file_extension {
899 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
900 if !options.enable_minification {
901 try_err!(fs::copy(css, out), css);
903 let buffer = try_err!(fs::read_to_string(css), css);
904 write_minify(out, &buffer, options.enable_minification)?;
907 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
908 static_files::NORMALIZE_CSS,
909 options.enable_minification)?;
910 write(cx.dst.join("FiraSans-Regular.woff"),
911 static_files::fira_sans::REGULAR)?;
912 write(cx.dst.join("FiraSans-Medium.woff"),
913 static_files::fira_sans::MEDIUM)?;
914 write(cx.dst.join("FiraSans-LICENSE.txt"),
915 static_files::fira_sans::LICENSE)?;
916 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
917 static_files::source_serif_pro::REGULAR)?;
918 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
919 static_files::source_serif_pro::BOLD)?;
920 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
921 static_files::source_serif_pro::ITALIC)?;
922 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
923 static_files::source_serif_pro::LICENSE)?;
924 write(cx.dst.join("SourceCodePro-Regular.woff"),
925 static_files::source_code_pro::REGULAR)?;
926 write(cx.dst.join("SourceCodePro-Semibold.woff"),
927 static_files::source_code_pro::SEMIBOLD)?;
928 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
929 static_files::source_code_pro::LICENSE)?;
930 write(cx.dst.join("LICENSE-MIT.txt"),
931 static_files::LICENSE_MIT)?;
932 write(cx.dst.join("LICENSE-APACHE.txt"),
933 static_files::LICENSE_APACHE)?;
934 write(cx.dst.join("COPYRIGHT.txt"),
935 static_files::COPYRIGHT)?;
941 for_search_index: bool,
942 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
945 let mut ret = Vec::new();
946 let mut krates = Vec::new();
947 let mut variables = Vec::new();
949 let mut krate = krate.to_owned();
952 for line in BufReader::new(File::open(path)?).lines() {
954 if for_search_index && line.starts_with("var R") {
955 variables.push(line.clone());
956 // We need to check if the crate name has been put into a variable as well.
957 let tokens = js::simple_minify(&line).apply(js::clean_tokens);
959 while pos < tokens.len() {
960 if let Some((var_pos, Some(value_pos))) =
961 js::get_variable_name_and_value_positions(&tokens, pos) {
962 if let Some(s) = tokens.0[value_pos].get_string() {
963 if &s[1..s.len() - 1] == krate {
964 if let Some(var) = tokens[var_pos].get_other() {
965 krate = var.to_owned();
975 if !line.starts_with(key) {
978 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
981 ret.push(line.to_string());
982 krates.push(line[key.len() + 2..].split('"')
984 .map(|s| s.to_owned())
985 .unwrap_or_else(|| String::new()));
988 Ok((ret, krates, variables))
991 fn show_item(item: &IndexItem, krate: &str) -> String {
992 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
993 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
994 if let Some(p) = item.parent_idx {
995 format!(",'parent':{}", p)
1001 let dst = cx.dst.join("aliases.js");
1003 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
1004 let mut w = try_err!(File::create(&dst), &dst);
1005 let mut output = String::with_capacity(100);
1006 for (alias, items) in &cache.aliases {
1007 if items.is_empty() {
1010 output.push_str(&format!("\"{}\":[{}],",
1013 .map(|v| show_item(v, &krate.name))
1014 .collect::<Vec<_>>()
1017 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1019 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1020 for aliases in &all_aliases {
1021 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1025 use std::ffi::OsString;
1030 children: FxHashMap<OsString, Hierarchy>,
1031 elems: FxHashSet<OsString>,
1035 fn new(elem: OsString) -> Hierarchy {
1038 children: FxHashMap::default(),
1039 elems: FxHashSet::default(),
1043 fn to_json_string(&self) -> String {
1044 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1045 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1046 let mut files = self.elems.iter()
1047 .map(|s| format!("\"{}\"",
1049 .expect("invalid osstring conversion")))
1050 .collect::<Vec<_>>();
1051 files.sort_unstable_by(|a, b| a.cmp(b));
1052 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1053 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1054 name=self.elem.to_str().expect("invalid osstring conversion"),
1055 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1056 files=files.join(","))
1060 if cx.shared.include_sources {
1061 use std::path::Component;
1063 let mut hierarchy = Hierarchy::new(OsString::new());
1064 for source in cx.shared.local_sources.iter()
1065 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1067 let mut h = &mut hierarchy;
1068 let mut elems = source.components()
1071 Component::Normal(s) => Some(s.to_owned()),
1077 let cur_elem = elems.next().expect("empty file path");
1078 if elems.peek().is_none() {
1079 h.elems.insert(cur_elem);
1082 let e = cur_elem.clone();
1083 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1084 h = h.children.get_mut(&cur_elem).expect("not found child");
1089 let dst = cx.dst.join("source-files.js");
1090 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1093 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1095 hierarchy.to_json_string()));
1097 let mut w = try_err!(File::create(&dst), &dst);
1098 try_err!(writeln!(&mut w,
1099 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1100 all_sources.join("\n")),
1104 // Update the search index
1105 let dst = cx.dst.join("search-index.js");
1106 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1110 all_indexes.push(search_index);
1112 // Sort the indexes by crate so the file will be generated identically even
1113 // with rustdoc running in parallel.
1115 let mut w = try_err!(File::create(&dst), &dst);
1116 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1117 try_err!(write_minify_replacer(&mut w,
1118 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1119 options.enable_minification),
1121 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1123 if options.enable_index_page {
1124 if let Some(index_page) = options.index_page.clone() {
1125 let mut md_opts = options.clone();
1126 md_opts.output = cx.dst.clone();
1127 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1129 ::markdown::render(index_page, md_opts, diag);
1131 let dst = cx.dst.join("index.html");
1132 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1133 let page = layout::Page {
1134 title: "Index of crates",
1137 static_root_path: cx.shared.static_root_path.deref(),
1138 description: "List of crates",
1139 keywords: BASIC_KEYWORDS,
1140 resource_suffix: &cx.shared.resource_suffix,
1142 static_extra_scripts: &[],
1144 krates.push(krate.name.clone());
1148 let content = format!(
1150 <span class='in-band'>List of all crates</span>\
1151 </h1><ul class='mod'>{}</ul>",
1155 format!("<li><a href=\"{}index.html\">{}</li>",
1158 .collect::<String>());
1159 try_err!(layout::render(&mut w, &cx.shared.layout,
1160 &page, &(""), &content,
1161 cx.shared.css_file_extension.is_some(),
1163 cx.shared.generate_search_filter), &dst);
1164 try_err!(w.flush(), &dst);
1168 // Update the list of all implementors for traits
1169 let dst = cx.dst.join("implementors");
1170 for (&did, imps) in &cache.implementors {
1171 // Private modules can leak through to this phase of rustdoc, which
1172 // could contain implementations for otherwise private types. In some
1173 // rare cases we could find an implementation for an item which wasn't
1174 // indexed, so we just skip this step in that case.
1176 // FIXME: this is a vague explanation for why this can't be a `get`, in
1177 // theory it should be...
1178 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1180 None => match cache.external_paths.get(&did) {
1186 let mut have_impls = false;
1187 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1189 // If the trait and implementation are in the same crate, then
1190 // there's no need to emit information about it (there's inlining
1191 // going on). If they're in different crates then the crate defining
1192 // the trait will be interested in our implementation.
1193 if imp.impl_item.def_id.krate == did.krate { continue }
1194 // If the implementation is from another crate then that crate
1196 if !imp.impl_item.def_id.is_local() { continue }
1198 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1199 as_json(&imp.inner_impl().to_string()),
1200 imp.inner_impl().synthetic,
1201 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1203 implementors.push_str("];");
1205 // Only create a js file if we have impls to add to it. If the trait is
1206 // documented locally though we always create the file to avoid dead
1208 if !have_impls && !cache.paths.contains_key(&did) {
1212 let mut mydst = dst.clone();
1213 for part in &remote_path[..remote_path.len() - 1] {
1216 try_err!(fs::create_dir_all(&mydst), &mydst);
1217 mydst.push(&format!("{}.{}.js",
1218 remote_item_type.css_class(),
1219 remote_path[remote_path.len() - 1]));
1221 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1224 all_implementors.push(implementors);
1225 // Sort the implementors by crate so the file will be generated
1226 // identically even with rustdoc running in parallel.
1227 all_implementors.sort();
1229 let mut f = try_err!(File::create(&mydst), &mydst);
1230 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1231 for implementor in &all_implementors {
1232 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1234 try_err!(writeln!(&mut f, "{}", r"
1235 if (window.register_implementors) {
1236 window.register_implementors(implementors);
1238 window.pending_implementors = implementors;
1241 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1246 fn render_sources(dst: &Path, scx: &mut SharedContext,
1247 krate: clean::Crate) -> Result<clean::Crate, Error> {
1248 info!("emitting source files");
1249 let dst = dst.join("src").join(&krate.name);
1250 try_err!(fs::create_dir_all(&dst), &dst);
1251 let mut folder = SourceCollector {
1255 Ok(folder.fold_crate(krate))
1258 /// Writes the entire contents of a string to a destination, not attempting to
1259 /// catch any errors.
1260 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1261 Ok(try_err!(fs::write(&dst, contents), &dst))
1264 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1265 if enable_minification {
1266 if dst.extension() == Some(&OsStr::new("css")) {
1267 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1268 write(dst, res.as_bytes())
1270 write(dst, minifier::js::minify(contents).as_bytes())
1273 write(dst, contents.as_bytes())
1277 fn write_minify_replacer<W: Write>(
1280 enable_minification: bool,
1281 ) -> io::Result<()> {
1282 use minifier::js::{Keyword, ReservedChar, Token};
1284 if enable_minification {
1286 minifier::js::simple_minify(contents)
1288 // We keep backlines.
1289 minifier::js::clean_tokens_except(f, |c| {
1290 c.get_char() != Some(ReservedChar::Backline)
1294 minifier::js::replace_token_with(f, |t| {
1296 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1297 Token::String(s) => {
1298 let s = &s[1..s.len() -1]; // The quotes are included
1300 Some(Token::Other("E"))
1301 } else if s == "t" {
1302 Some(Token::Other("T"))
1303 } else if s == "u" {
1304 Some(Token::Other("U"))
1314 // We add a backline after the newly created variables.
1315 minifier::js::aggregate_strings_into_array_with_separation(
1318 Token::Char(ReservedChar::Backline),
1323 writeln!(dst, "{}", contents)
1327 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1328 /// things like ".." to components which preserve the "top down" hierarchy of a
1329 /// static HTML tree. Each component in the cleaned path will be passed as an
1330 /// argument to `f`. The very last component of the path (ie the file name) will
1331 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1332 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1335 // make it relative, if possible
1336 let p = p.strip_prefix(src_root).unwrap_or(p);
1338 let mut iter = p.components().peekable();
1340 while let Some(c) = iter.next() {
1341 if !keep_filename && iter.peek().is_none() {
1346 Component::ParentDir => f("up".as_ref()),
1347 Component::Normal(c) => f(c),
1353 /// Attempts to find where an external crate is located, given that we're
1354 /// rendering in to the specified source destination.
1355 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1358 // See if there's documentation generated into the local directory
1359 let local_location = dst.join(&e.name);
1360 if local_location.is_dir() {
1364 if let Some(url) = extern_url {
1365 let mut url = url.to_string();
1366 if !url.ends_with("/") {
1372 // Failing that, see if there's an attribute specifying where to find this
1374 e.attrs.lists("doc")
1375 .filter(|a| a.check_name("html_root_url"))
1376 .filter_map(|a| a.value_str())
1378 let mut url = url.to_string();
1379 if !url.ends_with("/") {
1383 }).next().unwrap_or(Unknown) // Well, at least we tried.
1386 impl<'a> DocFolder for SourceCollector<'a> {
1387 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1388 // If we're including source files, and we haven't seen this file yet,
1389 // then we need to render it out to the filesystem.
1390 if self.scx.include_sources
1391 // skip all invalid or macro spans
1392 && item.source.filename.is_real()
1393 // skip non-local items
1394 && item.def_id.is_local() {
1396 // If it turns out that we couldn't read this file, then we probably
1397 // can't read any of the files (generating html output from json or
1398 // something like that), so just don't include sources for the
1399 // entire crate. The other option is maintaining this mapping on a
1400 // per-file basis, but that's probably not worth it...
1402 .include_sources = match self.emit_source(&item.source.filename) {
1405 println!("warning: source code was requested to be rendered, \
1406 but processing `{}` had an error: {}",
1407 item.source.filename, e);
1408 println!(" skipping rendering of source code");
1413 self.fold_item_recur(item)
1417 impl<'a> SourceCollector<'a> {
1418 /// Renders the given filename into its corresponding HTML source file.
1419 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1420 let p = match *filename {
1421 FileName::Real(ref file) => file,
1424 if self.scx.local_sources.contains_key(&**p) {
1425 // We've already emitted this source
1429 let contents = fs::read_to_string(&p)?;
1431 // Remove the utf-8 BOM if any
1432 let contents = if contents.starts_with("\u{feff}") {
1438 // Create the intermediate directories
1439 let mut cur = self.dst.clone();
1440 let mut root_path = String::from("../../");
1441 let mut href = String::new();
1442 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1443 cur.push(component);
1444 fs::create_dir_all(&cur).unwrap();
1445 root_path.push_str("../");
1446 href.push_str(&component.to_string_lossy());
1449 let mut fname = p.file_name()
1450 .expect("source has no filename")
1452 fname.push(".html");
1454 href.push_str(&fname.to_string_lossy());
1456 let mut w = BufWriter::new(File::create(&cur)?);
1457 let title = format!("{} -- source", cur.file_name().unwrap()
1458 .to_string_lossy());
1459 let desc = format!("Source to the Rust file `{}`.", filename);
1460 let page = layout::Page {
1462 css_class: "source",
1463 root_path: &root_path,
1464 static_root_path: self.scx.static_root_path.deref(),
1466 keywords: BASIC_KEYWORDS,
1467 resource_suffix: &self.scx.resource_suffix,
1468 extra_scripts: &["source-files"],
1469 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1471 layout::render(&mut w, &self.scx.layout,
1472 &page, &(""), &Source(contents),
1473 self.scx.css_file_extension.is_some(),
1475 self.scx.generate_search_filter)?;
1477 self.scx.local_sources.insert(p.clone(), href);
1482 impl DocFolder for Cache {
1483 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1484 if item.def_id.is_local() {
1485 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1488 // If this is a stripped module,
1489 // we don't want it or its children in the search index.
1490 let orig_stripped_mod = match item.inner {
1491 clean::StrippedItem(box clean::ModuleItem(..)) => {
1492 mem::replace(&mut self.stripped_mod, true)
1494 _ => self.stripped_mod,
1497 // If the impl is from a masked crate or references something from a
1498 // masked crate then remove it completely.
1499 if let clean::ImplItem(ref i) = item.inner {
1500 if self.masked_crates.contains(&item.def_id.krate) ||
1501 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1502 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1507 // Register any generics to their corresponding string. This is used
1508 // when pretty-printing types.
1509 if let Some(generics) = item.inner.generics() {
1510 self.generics(generics);
1513 // Propagate a trait method's documentation to all implementors of the
1515 if let clean::TraitItem(ref t) = item.inner {
1516 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1519 // Collect all the implementors of traits.
1520 if let clean::ImplItem(ref i) = item.inner {
1521 if let Some(did) = i.trait_.def_id() {
1522 if i.blanket_impl.is_none() {
1523 self.implementors.entry(did).or_default().push(Impl {
1524 impl_item: item.clone(),
1530 // Index this method for searching later on.
1531 if let Some(ref s) = item.name {
1532 let (parent, is_inherent_impl_item) = match item.inner {
1533 clean::StrippedItem(..) => ((None, None), false),
1534 clean::AssociatedConstItem(..) |
1535 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1536 // skip associated items in trait impls
1537 ((None, None), false)
1539 clean::AssociatedTypeItem(..) |
1540 clean::TyMethodItem(..) |
1541 clean::StructFieldItem(..) |
1542 clean::VariantItem(..) => {
1543 ((Some(*self.parent_stack.last().unwrap()),
1544 Some(&self.stack[..self.stack.len() - 1])),
1547 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1548 if self.parent_stack.is_empty() {
1549 ((None, None), false)
1551 let last = self.parent_stack.last().unwrap();
1553 let path = match self.paths.get(&did) {
1554 // The current stack not necessarily has correlation
1555 // for where the type was defined. On the other
1556 // hand, `paths` always has the right
1557 // information if present.
1558 Some(&(ref fqp, ItemType::Trait)) |
1559 Some(&(ref fqp, ItemType::Struct)) |
1560 Some(&(ref fqp, ItemType::Union)) |
1561 Some(&(ref fqp, ItemType::Enum)) =>
1562 Some(&fqp[..fqp.len() - 1]),
1563 Some(..) => Some(&*self.stack),
1566 ((Some(*last), path), true)
1569 _ => ((None, Some(&*self.stack)), false)
1573 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1574 debug_assert!(!item.is_stripped());
1576 // A crate has a module at its root, containing all items,
1577 // which should not be indexed. The crate-item itself is
1578 // inserted later on when serializing the search-index.
1579 if item.def_id.index != CRATE_DEF_INDEX {
1580 self.search_index.push(IndexItem {
1582 name: s.to_string(),
1583 path: path.join("::"),
1584 desc: plain_summary_line_short(item.doc_value()),
1587 search_type: get_index_search_type(&item),
1591 (Some(parent), None) if is_inherent_impl_item => {
1592 // We have a parent, but we don't know where they're
1593 // defined yet. Wait for later to index this item.
1594 self.orphan_impl_items.push((parent, item.clone()));
1600 // Keep track of the fully qualified path for this item.
1601 let pushed = match item.name {
1602 Some(ref n) if !n.is_empty() => {
1603 self.stack.push(n.to_string());
1610 clean::StructItem(..) | clean::EnumItem(..) |
1611 clean::TypedefItem(..) | clean::TraitItem(..) |
1612 clean::FunctionItem(..) | clean::ModuleItem(..) |
1613 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1614 clean::ConstantItem(..) | clean::StaticItem(..) |
1615 clean::UnionItem(..) | clean::ForeignTypeItem |
1616 clean::MacroItem(..) | clean::ProcMacroItem(..)
1617 if !self.stripped_mod => {
1618 // Re-exported items mean that the same id can show up twice
1619 // in the rustdoc ast that we're looking at. We know,
1620 // however, that a re-exported item doesn't show up in the
1621 // `public_items` map, so we can skip inserting into the
1622 // paths map if there was already an entry present and we're
1623 // not a public item.
1624 if !self.paths.contains_key(&item.def_id) ||
1625 self.access_levels.is_public(item.def_id)
1627 self.paths.insert(item.def_id,
1628 (self.stack.clone(), item.type_()));
1630 self.add_aliases(&item);
1632 // Link variants to their parent enum because pages aren't emitted
1633 // for each variant.
1634 clean::VariantItem(..) if !self.stripped_mod => {
1635 let mut stack = self.stack.clone();
1637 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1640 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1641 self.add_aliases(&item);
1642 self.paths.insert(item.def_id, (self.stack.clone(),
1649 // Maintain the parent stack
1650 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1651 let parent_pushed = match item.inner {
1652 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1653 clean::StructItem(..) | clean::UnionItem(..) => {
1654 self.parent_stack.push(item.def_id);
1655 self.parent_is_trait_impl = false;
1658 clean::ImplItem(ref i) => {
1659 self.parent_is_trait_impl = i.trait_.is_some();
1661 clean::ResolvedPath{ did, .. } => {
1662 self.parent_stack.push(did);
1666 let prim_did = t.primitive_type().and_then(|t| {
1667 self.primitive_locations.get(&t).cloned()
1671 self.parent_stack.push(did);
1682 // Once we've recursively found all the generics, hoard off all the
1683 // implementations elsewhere.
1684 let ret = self.fold_item_recur(item).and_then(|item| {
1685 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1686 // Figure out the id of this impl. This may map to a
1687 // primitive rather than always to a struct/enum.
1688 // Note: matching twice to restrict the lifetime of the `i` borrow.
1689 let mut dids = FxHashSet::default();
1690 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1692 clean::ResolvedPath { did, .. } |
1693 clean::BorrowedRef {
1694 type_: box clean::ResolvedPath { did, .. }, ..
1699 let did = t.primitive_type().and_then(|t| {
1700 self.primitive_locations.get(&t).cloned()
1703 if let Some(did) = did {
1709 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1710 for bound in generics {
1711 if let Some(did) = bound.def_id() {
1719 let impl_item = Impl {
1722 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1724 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1727 let trait_did = impl_item.trait_did().unwrap();
1728 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1736 if pushed { self.stack.pop().unwrap(); }
1737 if parent_pushed { self.parent_stack.pop().unwrap(); }
1738 self.stripped_mod = orig_stripped_mod;
1739 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1745 fn generics(&mut self, generics: &clean::Generics) {
1746 for param in &generics.params {
1748 clean::GenericParamDefKind::Lifetime => {}
1749 clean::GenericParamDefKind::Type { did, .. } => {
1750 self.typarams.insert(did, param.name.clone());
1756 fn add_aliases(&mut self, item: &clean::Item) {
1757 if item.def_id.index == CRATE_DEF_INDEX {
1760 if let Some(ref item_name) = item.name {
1761 let path = self.paths.get(&item.def_id)
1762 .map(|p| p.0[..p.0.len() - 1].join("::"))
1763 .unwrap_or("std".to_owned());
1764 for alias in item.attrs.lists("doc")
1765 .filter(|a| a.check_name("alias"))
1766 .filter_map(|a| a.value_str()
1767 .map(|s| s.to_string().replace("\"", "")))
1768 .filter(|v| !v.is_empty())
1769 .collect::<FxHashSet<_>>()
1771 self.aliases.entry(alias)
1772 .or_insert(Vec::with_capacity(1))
1775 name: item_name.to_string(),
1777 desc: plain_summary_line_short(item.doc_value()),
1780 search_type: get_index_search_type(&item),
1787 #[derive(Debug, Eq, PartialEq, Hash)]
1794 fn new(mut url: String, name: String) -> ItemEntry {
1795 while url.starts_with('/') {
1805 impl fmt::Display for ItemEntry {
1806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1807 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1811 impl PartialOrd for ItemEntry {
1812 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1813 Some(self.cmp(other))
1817 impl Ord for ItemEntry {
1818 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1819 self.name.cmp(&other.name)
1825 structs: FxHashSet<ItemEntry>,
1826 enums: FxHashSet<ItemEntry>,
1827 unions: FxHashSet<ItemEntry>,
1828 primitives: FxHashSet<ItemEntry>,
1829 traits: FxHashSet<ItemEntry>,
1830 macros: FxHashSet<ItemEntry>,
1831 functions: FxHashSet<ItemEntry>,
1832 typedefs: FxHashSet<ItemEntry>,
1833 existentials: FxHashSet<ItemEntry>,
1834 statics: FxHashSet<ItemEntry>,
1835 constants: FxHashSet<ItemEntry>,
1836 keywords: FxHashSet<ItemEntry>,
1837 attributes: FxHashSet<ItemEntry>,
1838 derives: FxHashSet<ItemEntry>,
1839 trait_aliases: FxHashSet<ItemEntry>,
1843 fn new() -> AllTypes {
1844 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1846 structs: new_set(100),
1847 enums: new_set(100),
1848 unions: new_set(100),
1849 primitives: new_set(26),
1850 traits: new_set(100),
1851 macros: new_set(100),
1852 functions: new_set(100),
1853 typedefs: new_set(100),
1854 existentials: new_set(100),
1855 statics: new_set(100),
1856 constants: new_set(100),
1857 keywords: new_set(100),
1858 attributes: new_set(100),
1859 derives: new_set(100),
1860 trait_aliases: new_set(100),
1864 fn append(&mut self, item_name: String, item_type: &ItemType) {
1865 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1866 if let Some(name) = url.pop() {
1867 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1869 let name = url.join("::");
1871 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1872 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1873 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1874 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1875 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1876 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1877 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1878 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1879 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1880 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1881 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1882 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1883 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1884 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1891 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1892 class: &str) -> fmt::Result {
1894 let mut e: Vec<&ItemEntry> = e.iter().collect();
1896 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1900 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1905 impl fmt::Display for AllTypes {
1906 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1909 <span class='out-of-band'>\
1910 <span id='render-detail'>\
1911 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1912 [<span class='inner'>−</span>]\
1916 <span class='in-band'>List of all items</span>\
1918 print_entries(f, &self.structs, "Structs", "structs")?;
1919 print_entries(f, &self.enums, "Enums", "enums")?;
1920 print_entries(f, &self.unions, "Unions", "unions")?;
1921 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1922 print_entries(f, &self.traits, "Traits", "traits")?;
1923 print_entries(f, &self.macros, "Macros", "macros")?;
1924 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1925 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1926 print_entries(f, &self.functions, "Functions", "functions")?;
1927 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1928 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
1929 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1930 print_entries(f, &self.statics, "Statics", "statics")?;
1931 print_entries(f, &self.constants, "Constants", "constants")
1936 struct Settings<'a> {
1937 // (id, explanation, default value)
1938 settings: Vec<(&'static str, &'static str, bool)>,
1943 impl<'a> Settings<'a> {
1944 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1947 ("item-declarations", "Auto-hide item declarations.", true),
1948 ("item-attributes", "Auto-hide item attributes.", true),
1949 ("trait-implementations", "Auto-hide trait implementations documentation",
1951 ("method-docs", "Auto-hide item methods' documentation", false),
1952 ("go-to-only-result", "Directly go to item in search if there is only one result",
1954 ("line-numbers", "Show line numbers on code examples", false),
1962 impl<'a> fmt::Display for Settings<'a> {
1963 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1966 <span class='in-band'>Rustdoc settings</span>\
1968 <div class='settings'>{}</div>\
1969 <script src='{}settings{}.js'></script>",
1970 self.settings.iter()
1971 .map(|(id, text, enabled)| {
1972 format!("<div class='setting-line'>\
1973 <label class='toggle'>\
1974 <input type='checkbox' id='{}' {}>\
1975 <span class='slider'></span>\
1978 </div>", id, if *enabled { " checked" } else { "" }, text)
1980 .collect::<String>(),
1987 fn derive_id(&self, id: String) -> String {
1988 let mut map = self.id_map.borrow_mut();
1992 /// String representation of how to get back to the root path of the 'doc/'
1993 /// folder in terms of a relative URL.
1994 fn root_path(&self) -> String {
1995 "../".repeat(self.current.len())
1998 /// Recurse in the directory structure and change the "root path" to make
1999 /// sure it always points to the top (relatively).
2000 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
2001 F: FnOnce(&mut Context) -> T,
2004 panic!("Unexpected empty destination: {:?}", self.current);
2006 let prev = self.dst.clone();
2008 self.current.push(s);
2010 info!("Recursing into {}", self.dst.display());
2014 info!("Recursed; leaving {}", self.dst.display());
2016 // Go back to where we were at
2018 self.current.pop().unwrap();
2023 /// Main method for rendering a crate.
2025 /// This currently isn't parallelized, but it'd be pretty easy to add
2026 /// parallelization to this function.
2027 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2028 let mut item = match krate.module.take() {
2030 None => return Ok(()),
2032 let final_file = self.dst.join(&krate.name)
2034 let settings_file = self.dst.join("settings.html");
2036 let crate_name = krate.name.clone();
2037 item.name = Some(krate.name);
2039 let mut all = AllTypes::new();
2042 // Render the crate documentation
2043 let mut work = vec![(self.clone(), item)];
2045 while let Some((mut cx, item)) = work.pop() {
2046 cx.item(item, &mut all, |cx, item| {
2047 work.push((cx.clone(), item))
2052 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2053 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2054 if !root_path.ends_with('/') {
2055 root_path.push('/');
2057 let mut page = layout::Page {
2058 title: "List of all items in this crate",
2061 static_root_path: self.shared.static_root_path.deref(),
2062 description: "List of all items in this crate",
2063 keywords: BASIC_KEYWORDS,
2064 resource_suffix: &self.shared.resource_suffix,
2066 static_extra_scripts: &[],
2068 let sidebar = if let Some(ref version) = cache().crate_version {
2069 format!("<p class='location'>Crate {}</p>\
2070 <div class='block version'>\
2073 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2074 crate_name, version)
2078 try_err!(layout::render(&mut w, &self.shared.layout,
2079 &page, &sidebar, &all,
2080 self.shared.css_file_extension.is_some(),
2081 &self.shared.themes,
2082 self.shared.generate_search_filter),
2085 // Generating settings page.
2086 let settings = Settings::new("./", &self.shared.resource_suffix);
2087 page.title = "Rustdoc settings";
2088 page.description = "Settings of Rustdoc";
2089 page.root_path = "./";
2091 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2092 let mut themes = self.shared.themes.clone();
2093 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2094 themes.push(PathBuf::from("settings.css"));
2095 let layout = self.shared.layout.clone();
2096 try_err!(layout::render(&mut w, &layout,
2097 &page, &sidebar, &settings,
2098 self.shared.css_file_extension.is_some(),
2100 self.shared.generate_search_filter),
2106 fn render_item(&self,
2107 writer: &mut dyn io::Write,
2111 // A little unfortunate that this is done like this, but it sure
2112 // does make formatting *a lot* nicer.
2113 CURRENT_LOCATION_KEY.with(|slot| {
2114 *slot.borrow_mut() = self.current.clone();
2117 let mut title = if it.is_primitive() || it.is_keyword() {
2118 // No need to include the namespace for primitive types and keywords
2121 self.current.join("::")
2124 if !title.is_empty() {
2125 title.push_str("::");
2127 title.push_str(it.name.as_ref().unwrap());
2129 title.push_str(" - Rust");
2130 let tyname = it.type_().css_class();
2131 let desc = if it.is_crate() {
2132 format!("API documentation for the Rust `{}` crate.",
2133 self.shared.layout.krate)
2135 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2136 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2138 let keywords = make_item_keywords(it);
2139 let page = layout::Page {
2141 root_path: &self.root_path(),
2142 static_root_path: self.shared.static_root_path.deref(),
2145 keywords: &keywords,
2146 resource_suffix: &self.shared.resource_suffix,
2148 static_extra_scripts: &[],
2152 self.id_map.borrow_mut().reset();
2153 self.id_map.borrow_mut().populate(initial_ids());
2156 if !self.render_redirect_pages {
2157 layout::render(writer, &self.shared.layout, &page,
2158 &Sidebar{ cx: self, item: it },
2159 &Item{ cx: self, item: it },
2160 self.shared.css_file_extension.is_some(),
2161 &self.shared.themes,
2162 self.shared.generate_search_filter)?;
2164 let mut url = self.root_path();
2165 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2166 for name in &names[..names.len() - 1] {
2170 url.push_str(&item_path(ty, names.last().unwrap()));
2171 layout::redirect(writer, &url)?;
2177 /// Non-parallelized version of rendering an item. This will take the input
2178 /// item, render its contents, and then invoke the specified closure with
2179 /// all sub-items which need to be rendered.
2181 /// The rendering driver uses this closure to queue up more work.
2182 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2183 where F: FnMut(&mut Context, clean::Item),
2185 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2186 // if they contain impls for public types. These modules can also
2187 // contain items such as publicly re-exported structures.
2189 // External crates will provide links to these structures, so
2190 // these modules are recursed into, but not rendered normally
2191 // (a flag on the context).
2192 if !self.render_redirect_pages {
2193 self.render_redirect_pages = item.is_stripped();
2197 // modules are special because they add a namespace. We also need to
2198 // recurse into the items of the module as well.
2199 let name = item.name.as_ref().unwrap().to_string();
2200 let mut item = Some(item);
2201 self.recurse(name, |this| {
2202 let item = item.take().unwrap();
2204 let mut buf = Vec::new();
2205 this.render_item(&mut buf, &item, false).unwrap();
2206 // buf will be empty if the module is stripped and there is no redirect for it
2207 if !buf.is_empty() {
2208 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2209 let joint_dst = this.dst.join("index.html");
2210 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2213 let m = match item.inner {
2214 clean::StrippedItem(box clean::ModuleItem(m)) |
2215 clean::ModuleItem(m) => m,
2219 // Render sidebar-items.js used throughout this module.
2220 if !this.render_redirect_pages {
2221 let items = this.build_sidebar_items(&m);
2222 let js_dst = this.dst.join("sidebar-items.js");
2223 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2224 try_err!(write!(&mut js_out, "initSidebarItems({});",
2225 as_json(&items)), &js_dst);
2228 for item in m.items {
2234 } else if item.name.is_some() {
2235 let mut buf = Vec::new();
2236 self.render_item(&mut buf, &item, true).unwrap();
2237 // buf will be empty if the item is stripped and there is no redirect for it
2238 if !buf.is_empty() {
2239 let name = item.name.as_ref().unwrap();
2240 let item_type = item.type_();
2241 let file_name = &item_path(item_type, name);
2242 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2243 let joint_dst = self.dst.join(file_name);
2244 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2246 if !self.render_redirect_pages {
2247 all.append(full_path(self, &item), &item_type);
2249 // Redirect from a sane URL using the namespace to Rustdoc's
2250 // URL for the page.
2251 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2252 let redir_dst = self.dst.join(redir_name);
2253 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2256 let mut redirect_out = BufWriter::new(redirect_out);
2257 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2260 // If the item is a macro, redirect from the old macro URL (with !)
2261 // to the new one (without).
2262 if item_type == ItemType::Macro {
2263 let redir_name = format!("{}.{}!.html", item_type, name);
2264 let redir_dst = self.dst.join(redir_name);
2265 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2266 let mut redirect_out = BufWriter::new(redirect_out);
2267 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2274 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2275 // BTreeMap instead of HashMap to get a sorted output
2276 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2277 for item in &m.items {
2278 if item.is_stripped() { continue }
2280 let short = item.type_().css_class();
2281 let myname = match item.name {
2283 Some(ref s) => s.to_string(),
2285 let short = short.to_string();
2286 map.entry(short).or_default()
2287 .push((myname, Some(plain_summary_line(item.doc_value()))));
2290 if self.shared.sort_modules_alphabetically {
2291 for (_, items) in &mut map {
2300 /// Generates a url appropriate for an `href` attribute back to the source of
2303 /// The url generated, when clicked, will redirect the browser back to the
2304 /// original source code.
2306 /// If `None` is returned, then a source link couldn't be generated. This
2307 /// may happen, for example, with externally inlined items where the source
2308 /// of their crate documentation isn't known.
2309 fn src_href(&self) -> Option<String> {
2310 let mut root = self.cx.root_path();
2312 let cache = cache();
2313 let mut path = String::new();
2315 // We can safely ignore macros from other libraries
2316 let file = match self.item.source.filename {
2317 FileName::Real(ref path) => path,
2321 let (krate, path) = if self.item.def_id.is_local() {
2322 if let Some(path) = self.cx.shared.local_sources.get(file) {
2323 (&self.cx.shared.layout.krate, path)
2328 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2329 (ref name, ref src, Local) => (name, src),
2330 (ref name, ref src, Remote(ref s)) => {
2331 root = s.to_string();
2334 (_, _, Unknown) => return None,
2337 clean_srcpath(&src_root, file, false, |component| {
2338 path.push_str(&component.to_string_lossy());
2341 let mut fname = file.file_name().expect("source has no filename")
2343 fname.push(".html");
2344 path.push_str(&fname.to_string_lossy());
2348 let lines = if self.item.source.loline == self.item.source.hiline {
2349 self.item.source.loline.to_string()
2351 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2353 Some(format!("{root}src/{krate}/{path}#{lines}",
2354 root = Escape(&root),
2361 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2362 f: F) -> fmt::Result
2363 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2364 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2369 impl<'a> fmt::Display for Item<'a> {
2370 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2371 debug_assert!(!self.item.is_stripped());
2372 // Write the breadcrumb trail header for the top
2373 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2374 if let Some(version) = self.item.stable_since() {
2375 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2379 "<span id='render-detail'>\
2380 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2381 title=\"collapse all docs\">\
2382 [<span class='inner'>−</span>]\
2388 // When this item is part of a `pub use` in a downstream crate, the
2389 // [src] link in the downstream documentation will actually come back to
2390 // this page, and this link will be auto-clicked. The `id` attribute is
2391 // used to find the link to auto-click.
2392 if self.cx.shared.include_sources && !self.item.is_primitive() {
2393 if let Some(l) = self.src_href() {
2394 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2395 l, "goto source code")?;
2399 write!(fmt, "</span>")?; // out-of-band
2400 write!(fmt, "<span class='in-band'>")?;
2401 match self.item.inner {
2402 clean::ModuleItem(ref m) => if m.is_crate {
2403 write!(fmt, "Crate ")?;
2405 write!(fmt, "Module ")?;
2407 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2408 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2409 clean::StructItem(..) => write!(fmt, "Struct ")?,
2410 clean::UnionItem(..) => write!(fmt, "Union ")?,
2411 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2412 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2413 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2414 clean::ProcMacroItem(ref mac) => match mac.kind {
2415 MacroKind::Bang => write!(fmt, "Macro ")?,
2416 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2417 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2418 MacroKind::ProcMacroStub => unreachable!(),
2420 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2421 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2422 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2423 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2424 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2425 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2426 clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
2428 // We don't generate pages for any other type.
2432 if !self.item.is_primitive() && !self.item.is_keyword() {
2433 let cur = &self.cx.current;
2434 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2435 for (i, component) in cur.iter().enumerate().take(amt) {
2436 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2437 "../".repeat(cur.len() - i - 1),
2441 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2442 self.item.type_(), self.item.name.as_ref().unwrap())?;
2444 write!(fmt, "</span></h1>")?; // in-band
2446 match self.item.inner {
2447 clean::ModuleItem(ref m) =>
2448 item_module(fmt, self.cx, self.item, &m.items),
2449 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2450 item_function(fmt, self.cx, self.item, f),
2451 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2452 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2453 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2454 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2455 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2456 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2457 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2458 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2459 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2460 item_static(fmt, self.cx, self.item, i),
2461 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2462 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2463 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2464 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2465 clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
2467 // We don't generate pages for any other type.
2474 fn item_path(ty: ItemType, name: &str) -> String {
2476 ItemType::Module => format!("{}index.html", SlashChecker(name)),
2477 _ => format!("{}.{}.html", ty.css_class(), name),
2481 fn full_path(cx: &Context, item: &clean::Item) -> String {
2482 let mut s = cx.current.join("::");
2484 s.push_str(item.name.as_ref().unwrap());
2488 fn shorter<'a>(s: Option<&'a str>) -> String {
2490 Some(s) => s.lines()
2491 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2493 (*line).chars().any(|chr|{
2494 !chr.is_whitespace()
2496 }).collect::<Vec<_>>().join("\n"),
2497 None => String::new()
2502 fn plain_summary_line(s: Option<&str>) -> String {
2503 let line = shorter(s).replace("\n", " ");
2504 markdown::plain_summary_line_full(&line[..], false)
2508 fn plain_summary_line_short(s: Option<&str>) -> String {
2509 let line = shorter(s).replace("\n", " ");
2510 markdown::plain_summary_line_full(&line[..], true)
2513 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2514 if let Some(ref name) = item.name {
2515 info!("Documenting {}", name);
2517 document_stability(w, cx, item, false)?;
2518 document_full(w, item, cx, "", false)?;
2522 /// Render md_text as markdown.
2523 fn render_markdown(w: &mut fmt::Formatter,
2526 links: Vec<(String, String)>,
2530 let mut ids = cx.id_map.borrow_mut();
2531 write!(w, "<div class='docblock{}'>{}{}</div>",
2532 if is_hidden { " hidden" } else { "" },
2534 Markdown(md_text, &links, RefCell::new(&mut ids),
2538 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2539 prefix: &str, is_hidden: bool) -> fmt::Result {
2540 if let Some(s) = item.doc_value() {
2541 let markdown = if s.contains('\n') {
2542 format!("{} [Read more]({})",
2543 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2545 plain_summary_line(Some(s))
2547 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2548 } else if !prefix.is_empty() {
2549 write!(w, "<div class='docblock{}'>{}</div>",
2550 if is_hidden { " hidden" } else { "" },
2556 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2557 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2558 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2559 debug!("Doc block: =====\n{}\n=====", s);
2560 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2561 } else if !prefix.is_empty() {
2562 write!(w, "<div class='docblock{}'>{}</div>",
2563 if is_hidden { " hidden" } else { "" },
2569 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2570 is_hidden: bool) -> fmt::Result {
2571 let stabilities = short_stability(item, cx);
2572 if !stabilities.is_empty() {
2573 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2574 for stability in stabilities {
2575 write!(w, "{}", stability)?;
2577 write!(w, "</div>")?;
2582 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2583 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2586 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2587 if item.is_non_exhaustive() {
2588 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2589 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2592 if item.is_struct() {
2593 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2594 Therefore, non-exhaustive structs cannot be constructed in external crates \
2595 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2596 matched against without a wildcard <code>..</code>; and \
2597 struct update syntax will not work.")?;
2598 } else if item.is_enum() {
2599 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2600 Therefore, when matching against variants of non-exhaustive enums, an \
2601 extra wildcard arm must be added to account for any future variants.")?;
2603 write!(w, "This type will require a wildcard arm in any match statements or \
2607 write!(w, "</div>")?;
2613 fn name_key(name: &str) -> (&str, u64, usize) {
2614 let end = name.bytes()
2615 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2617 // find number at end
2618 let split = name[0..end].bytes()
2619 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2621 // count leading zeroes
2623 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2625 // sort leading zeroes last
2626 let num_zeroes = after_zeroes - split;
2628 match name[split..end].parse() {
2629 Ok(n) => (&name[..split], n, num_zeroes),
2630 Err(_) => (name, 0, num_zeroes),
2634 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2635 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2636 document(w, cx, item)?;
2638 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2640 // the order of item types in the listing
2641 fn reorder(ty: ItemType) -> u8 {
2643 ItemType::ExternCrate => 0,
2644 ItemType::Import => 1,
2645 ItemType::Primitive => 2,
2646 ItemType::Module => 3,
2647 ItemType::Macro => 4,
2648 ItemType::Struct => 5,
2649 ItemType::Enum => 6,
2650 ItemType::Constant => 7,
2651 ItemType::Static => 8,
2652 ItemType::Trait => 9,
2653 ItemType::Function => 10,
2654 ItemType::Typedef => 12,
2655 ItemType::Union => 13,
2660 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2661 let ty1 = i1.type_();
2662 let ty2 = i2.type_();
2664 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2666 let s1 = i1.stability.as_ref().map(|s| s.level);
2667 let s2 = i2.stability.as_ref().map(|s| s.level);
2669 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2670 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2673 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2674 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2675 name_key(lhs).cmp(&name_key(rhs))
2678 if cx.shared.sort_modules_alphabetically {
2679 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2681 // This call is to remove re-export duplicates in cases such as:
2686 // pub trait Double { fn foo(); }
2690 // pub use foo::bar::*;
2694 // `Double` will appear twice in the generated docs.
2696 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2697 // can be identical even if the elements are different (mostly in imports).
2698 // So in case this is an import, we keep everything by adding a "unique id"
2699 // (which is the position in the vector).
2700 indices.dedup_by_key(|i| (items[*i].def_id,
2701 if items[*i].name.as_ref().is_some() {
2702 Some(full_path(cx, &items[*i]))
2707 if items[*i].is_import() {
2713 debug!("{:?}", indices);
2714 let mut curty = None;
2715 for &idx in &indices {
2716 let myitem = &items[idx];
2717 if myitem.is_stripped() {
2721 let myty = Some(myitem.type_());
2722 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2723 // Put `extern crate` and `use` re-exports in the same section.
2725 } else if myty != curty {
2726 if curty.is_some() {
2727 write!(w, "</table>")?;
2730 let (short, name) = item_ty_to_strs(&myty.unwrap());
2731 write!(w, "<h2 id='{id}' class='section-header'>\
2732 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2733 id = cx.derive_id(short.to_owned()), name = name)?;
2736 match myitem.inner {
2737 clean::ExternCrateItem(ref name, ref src) => {
2738 use html::format::HRef;
2742 write!(w, "<tr><td><code>{}extern crate {} as {};",
2743 VisSpace(&myitem.visibility),
2744 HRef::new(myitem.def_id, src),
2748 write!(w, "<tr><td><code>{}extern crate {};",
2749 VisSpace(&myitem.visibility),
2750 HRef::new(myitem.def_id, name))?
2753 write!(w, "</code></td></tr>")?;
2756 clean::ImportItem(ref import) => {
2757 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2758 VisSpace(&myitem.visibility), *import)?;
2762 if myitem.name.is_none() { continue }
2764 let unsafety_flag = match myitem.inner {
2765 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2766 if func.header.unsafety == hir::Unsafety::Unsafe => {
2767 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2772 let stab = myitem.stability_class();
2773 let add = if stab.is_some() {
2779 let doc_value = myitem.doc_value().unwrap_or("");
2781 <tr class='{stab}{add}module-item'>\
2782 <td><a class=\"{class}\" href=\"{href}\" \
2783 title='{title}'>{name}</a>{unsafety_flag}</td>\
2784 <td class='docblock-short'>{stab_tags}{docs}\
2787 name = *myitem.name.as_ref().unwrap(),
2788 stab_tags = stability_tags(myitem),
2789 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2790 class = myitem.type_(),
2792 stab = stab.unwrap_or_else(|| String::new()),
2793 unsafety_flag = unsafety_flag,
2794 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2795 title = [full_path(cx, myitem), myitem.type_().to_string()]
2797 .filter_map(|s| if !s.is_empty() {
2802 .collect::<Vec<_>>()
2809 if curty.is_some() {
2810 write!(w, "</table>")?;
2815 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2817 fn stability_tags(item: &clean::Item) -> String {
2818 let mut tags = String::new();
2820 fn tag_html(class: &str, contents: &str) -> String {
2821 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2824 // The trailing space after each tag is to space it properly against the rest of the docs.
2825 if item.deprecation().is_some() {
2826 tags += &tag_html("deprecated", "Deprecated");
2829 if let Some(stab) = item
2832 .filter(|s| s.level == stability::Unstable)
2834 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2835 tags += &tag_html("internal", "Internal");
2837 tags += &tag_html("unstable", "Experimental");
2841 if let Some(ref cfg) = item.attrs.cfg {
2842 tags += &tag_html("portability", &cfg.render_short_html());
2848 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2850 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2851 let mut stability = vec![];
2852 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2854 if let Some(Deprecation { since, note }) = &item.deprecation() {
2855 let mut message = if let Some(since) = since {
2856 if stability::deprecation_in_effect(since) {
2857 format!("Deprecated since {}", Escape(since))
2859 format!("Deprecating in {}", Escape(since))
2862 String::from("Deprecated")
2865 if let Some(note) = note {
2866 let mut ids = cx.id_map.borrow_mut();
2867 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2868 message.push_str(&format!(": {}", html));
2870 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2873 if let Some(stab) = item
2876 .filter(|stab| stab.level == stability::Unstable)
2878 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2880 let mut message = if is_rustc_private {
2881 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2883 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2887 if let Some(feature) = stab.feature.as_ref() {
2888 let mut feature = format!("<code>{}</code>", Escape(&feature));
2889 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2890 feature.push_str(&format!(
2891 " <a href=\"{url}{issue}\">#{issue}</a>",
2897 message.push_str(&format!(" ({})", feature));
2900 if let Some(unstable_reason) = &stab.unstable_reason {
2901 // Provide a more informative message than the compiler help.
2902 let unstable_reason = if is_rustc_private {
2903 "This crate is being loaded from the sysroot, a permanently unstable location \
2904 for private compiler dependencies. It is not intended for general use. Prefer \
2905 using a public version of this crate from \
2906 [crates.io](https://crates.io) via [`Cargo.toml`]\
2907 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2912 let mut ids = cx.id_map.borrow_mut();
2914 "<details><summary>{}</summary>{}</details>",
2916 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2920 let class = if is_rustc_private {
2925 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2928 if let Some(ref cfg) = item.attrs.cfg {
2929 stability.push(format!(
2930 "<div class='stab portability'>{}</div>",
2931 cfg.render_long_html()
2938 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2939 c: &clean::Constant) -> fmt::Result {
2940 write!(w, "<pre class='rust const'>")?;
2941 render_attributes(w, it)?;
2942 write!(w, "{vis}const \
2943 {name}: {typ}</pre>",
2944 vis = VisSpace(&it.visibility),
2945 name = it.name.as_ref().unwrap(),
2950 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2951 s: &clean::Static) -> fmt::Result {
2952 write!(w, "<pre class='rust static'>")?;
2953 render_attributes(w, it)?;
2954 write!(w, "{vis}static {mutability}\
2955 {name}: {typ}</pre>",
2956 vis = VisSpace(&it.visibility),
2957 mutability = MutableSpace(s.mutability),
2958 name = it.name.as_ref().unwrap(),
2963 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2964 f: &clean::Function) -> fmt::Result {
2965 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2966 VisSpace(&it.visibility),
2967 ConstnessSpace(f.header.constness),
2968 UnsafetySpace(f.header.unsafety),
2969 AsyncSpace(f.header.asyncness),
2970 AbiSpace(f.header.abi),
2971 it.name.as_ref().unwrap(),
2973 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2974 render_attributes(w, it)?;
2976 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2977 {name}{generics}{decl}{where_clause}</pre>",
2978 vis = VisSpace(&it.visibility),
2979 constness = ConstnessSpace(f.header.constness),
2980 unsafety = UnsafetySpace(f.header.unsafety),
2981 asyncness = AsyncSpace(f.header.asyncness),
2982 abi = AbiSpace(f.header.abi),
2983 name = it.name.as_ref().unwrap(),
2984 generics = f.generics,
2985 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2990 asyncness: f.header.asyncness,
2995 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2996 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2997 // If there's already another implementor that has the same abbridged name, use the
2998 // full path, for example in `std::iter::ExactSizeIterator`
2999 let use_absolute = match implementor.inner_impl().for_ {
3000 clean::ResolvedPath { ref path, is_generic: false, .. } |
3001 clean::BorrowedRef {
3002 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
3004 } => implementor_dups[path.last_name()].1,
3007 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3008 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
3012 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
3014 containing_item: &clean::Item) -> fmt::Result {
3016 let did = i.trait_did().unwrap();
3017 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3018 render_impl(w, cx, i, assoc_link,
3019 RenderMode::Normal, containing_item.stable_since(), true, None)?;
3024 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
3025 let mut bounds = String::new();
3026 if !t_bounds.is_empty() {
3028 bounds.push_str(": ");
3030 for (i, p) in t_bounds.iter().enumerate() {
3032 bounds.push_str(" + ");
3034 bounds.push_str(&(*p).to_string());
3040 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3041 let lhs = format!("{}", lhs.inner_impl());
3042 let rhs = format!("{}", rhs.inner_impl());
3044 // lhs and rhs are formatted as HTML, which may be unnecessary
3045 name_key(&lhs).cmp(&name_key(&rhs))
3049 w: &mut fmt::Formatter,
3054 let bounds = bounds(&t.bounds, false);
3055 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3056 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3057 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3058 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3060 // Output the trait definition
3061 wrap_into_docblock(w, |w| {
3062 write!(w, "<pre class='rust trait'>")?;
3063 render_attributes(w, it)?;
3064 write!(w, "{}{}{}trait {}{}{}",
3065 VisSpace(&it.visibility),
3066 UnsafetySpace(t.unsafety),
3067 if t.is_auto { "auto " } else { "" },
3068 it.name.as_ref().unwrap(),
3072 if !t.generics.where_predicates.is_empty() {
3073 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3078 if t.items.is_empty() {
3079 write!(w, "{{ }}")?;
3081 // FIXME: we should be using a derived_id for the Anchors here
3085 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3088 if !types.is_empty() && !consts.is_empty() {
3093 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3096 if !consts.is_empty() && !required.is_empty() {
3099 for (pos, m) in required.iter().enumerate() {
3101 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3104 if pos < required.len() - 1 {
3105 write!(w, "<div class='item-spacer'></div>")?;
3108 if !required.is_empty() && !provided.is_empty() {
3111 for (pos, m) in provided.iter().enumerate() {
3113 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3115 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3116 write!(w, ",\n {{ ... }}\n")?;
3119 write!(w, " {{ ... }}\n")?;
3122 if pos < provided.len() - 1 {
3123 write!(w, "<div class='item-spacer'></div>")?;
3131 // Trait documentation
3132 document(w, cx, it)?;
3134 fn write_small_section_header(
3135 w: &mut fmt::Formatter,
3138 extra_content: &str,
3141 <h2 id='{0}' class='small-section-header'>\
3142 {1}<a href='#{0}' class='anchor'></a>\
3143 </h2>{2}", id, title, extra_content)
3146 fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3147 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3150 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3152 let name = m.name.as_ref().unwrap();
3153 let item_type = m.type_();
3154 let id = cx.derive_id(format!("{}.{}", item_type, name));
3155 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3156 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3157 extra = render_spotlight_traits(m)?,
3160 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3161 write!(w, "</code>")?;
3162 render_stability_since(w, m, t)?;
3163 write!(w, "</h3>")?;
3164 document(w, cx, m)?;
3168 if !types.is_empty() {
3169 write_small_section_header(w, "associated-types", "Associated Types",
3170 "<div class='methods'>")?;
3172 trait_item(w, cx, *t, it)?;
3174 write_loading_content(w, "</div>")?;
3177 if !consts.is_empty() {
3178 write_small_section_header(w, "associated-const", "Associated Constants",
3179 "<div class='methods'>")?;
3181 trait_item(w, cx, *t, it)?;
3183 write_loading_content(w, "</div>")?;
3186 // Output the documentation for each function individually
3187 if !required.is_empty() {
3188 write_small_section_header(w, "required-methods", "Required methods",
3189 "<div class='methods'>")?;
3190 for m in &required {
3191 trait_item(w, cx, *m, it)?;
3193 write_loading_content(w, "</div>")?;
3195 if !provided.is_empty() {
3196 write_small_section_header(w, "provided-methods", "Provided methods",
3197 "<div class='methods'>")?;
3198 for m in &provided {
3199 trait_item(w, cx, *m, it)?;
3201 write_loading_content(w, "</div>")?;
3204 // If there are methods directly on this trait object, render them here.
3205 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3207 let cache = cache();
3209 let mut synthetic_types = Vec::new();
3211 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3212 // The DefId is for the first Type found with that name. The bool is
3213 // if any Types with the same name but different DefId have been found.
3214 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3215 for implementor in implementors {
3216 match implementor.inner_impl().for_ {
3217 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3218 clean::BorrowedRef {
3219 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3222 let &mut (prev_did, ref mut has_duplicates) =
3223 implementor_dups.entry(path.last_name()).or_insert((did, false));
3224 if prev_did != did {
3225 *has_duplicates = true;
3232 let (local, foreign) = implementors.iter()
3233 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3234 .map_or(true, |d| cache.paths.contains_key(&d)));
3237 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3238 .partition(|i| i.inner_impl().synthetic);
3240 synthetic.sort_by(compare_impl);
3241 concrete.sort_by(compare_impl);
3243 if !foreign.is_empty() {
3244 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3246 for implementor in foreign {
3247 let assoc_link = AssocItemLink::GotoSource(
3248 implementor.impl_item.def_id,
3249 &implementor.inner_impl().provided_trait_methods
3251 render_impl(w, cx, &implementor, assoc_link,
3252 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3255 write_loading_content(w, "")?;
3258 write_small_section_header(w, "implementors", "Implementors",
3259 "<div class='item-list' id='implementors-list'>")?;
3260 for implementor in concrete {
3261 render_implementor(cx, implementor, w, &implementor_dups)?;
3263 write_loading_content(w, "</div>")?;
3266 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3267 "<div class='item-list' id='synthetic-implementors-list'>")?;
3268 for implementor in synthetic {
3269 synthetic_types.extend(
3270 collect_paths_for_type(implementor.inner_impl().for_.clone())
3272 render_implementor(cx, implementor, w, &implementor_dups)?;
3274 write_loading_content(w, "</div>")?;
3277 // even without any implementations to write in, we still want the heading and list, so the
3278 // implementors javascript file pulled in below has somewhere to write the impls into
3279 write_small_section_header(w, "implementors", "Implementors",
3280 "<div class='item-list' id='implementors-list'>")?;
3281 write_loading_content(w, "</div>")?;
3284 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3285 "<div class='item-list' id='synthetic-implementors-list'>")?;
3286 write_loading_content(w, "</div>")?;
3289 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3290 as_json(&synthetic_types))?;
3292 write!(w, r#"<script type="text/javascript" async
3293 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3295 root_path = vec![".."; cx.current.len()].join("/"),
3296 path = if it.def_id.is_local() {
3297 cx.current.join("/")
3299 let (ref path, _) = cache.external_paths[&it.def_id];
3300 path[..path.len() - 1].join("/")
3302 ty = it.type_().css_class(),
3303 name = *it.name.as_ref().unwrap())?;
3307 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3308 use html::item_type::ItemType::*;
3310 let name = it.name.as_ref().unwrap();
3311 let ty = match it.type_() {
3312 Typedef | AssociatedType => AssociatedType,
3316 let anchor = format!("#{}.{}", ty, name);
3318 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3319 AssocItemLink::Anchor(None) => anchor,
3320 AssocItemLink::GotoSource(did, _) => {
3321 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3326 fn assoc_const(w: &mut fmt::Formatter,
3329 _default: Option<&String>,
3330 link: AssocItemLink) -> fmt::Result {
3331 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3332 VisSpace(&it.visibility),
3333 naive_assoc_href(it, link),
3334 it.name.as_ref().unwrap(),
3339 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3340 bounds: &[clean::GenericBound],
3341 default: Option<&clean::Type>,
3342 link: AssocItemLink) -> fmt::Result {
3343 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3344 naive_assoc_href(it, link),
3345 it.name.as_ref().unwrap())?;
3346 if !bounds.is_empty() {
3347 write!(w, ": {}", GenericBounds(bounds))?
3349 if let Some(default) = default {
3350 write!(w, " = {}", default)?;
3355 fn render_stability_since_raw<'a, T: fmt::Write>(
3357 ver: Option<&'a str>,
3358 containing_ver: Option<&'a str>,
3360 if let Some(v) = ver {
3361 if containing_ver != ver && v.len() > 0 {
3362 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3368 fn render_stability_since(w: &mut fmt::Formatter,
3370 containing_item: &clean::Item) -> fmt::Result {
3371 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3374 fn render_assoc_item(w: &mut fmt::Formatter,
3376 link: AssocItemLink,
3377 parent: ItemType) -> fmt::Result {
3378 fn method(w: &mut fmt::Formatter,
3380 header: hir::FnHeader,
3381 g: &clean::Generics,
3383 link: AssocItemLink,
3386 let name = meth.name.as_ref().unwrap();
3387 let anchor = format!("#{}.{}", meth.type_(), name);
3388 let href = match link {
3389 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3390 AssocItemLink::Anchor(None) => anchor,
3391 AssocItemLink::GotoSource(did, provided_methods) => {
3392 // We're creating a link from an impl-item to the corresponding
3393 // trait-item and need to map the anchored type accordingly.
3394 let ty = if provided_methods.contains(name) {
3400 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3403 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3404 VisSpace(&meth.visibility),
3405 ConstnessSpace(header.constness),
3406 UnsafetySpace(header.unsafety),
3407 AsyncSpace(header.asyncness),
3408 AbiSpace(header.abi),
3411 let (indent, end_newline) = if parent == ItemType::Trait {
3417 render_attributes(w, meth)?;
3418 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3419 {generics}{decl}{where_clause}",
3420 VisSpace(&meth.visibility),
3421 ConstnessSpace(header.constness),
3422 UnsafetySpace(header.unsafety),
3423 AsyncSpace(header.asyncness),
3424 AbiSpace(header.abi),
3432 asyncness: header.asyncness,
3434 where_clause = WhereClause {
3441 clean::StrippedItem(..) => Ok(()),
3442 clean::TyMethodItem(ref m) => {
3443 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3445 clean::MethodItem(ref m) => {
3446 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3448 clean::AssociatedConstItem(ref ty, ref default) => {
3449 assoc_const(w, item, ty, default.as_ref(), link)
3451 clean::AssociatedTypeItem(ref bounds, ref default) => {
3452 assoc_type(w, item, bounds, default.as_ref(), link)
3454 _ => panic!("render_assoc_item called on non-associated-item")
3458 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3459 s: &clean::Struct) -> fmt::Result {
3460 wrap_into_docblock(w, |w| {
3461 write!(w, "<pre class='rust struct'>")?;
3462 render_attributes(w, it)?;
3473 document(w, cx, it)?;
3474 let mut fields = s.fields.iter().filter_map(|f| {
3476 clean::StructFieldItem(ref ty) => Some((f, ty)),
3480 if let doctree::Plain = s.struct_type {
3481 if fields.peek().is_some() {
3482 write!(w, "<h2 id='fields' class='fields small-section-header'>
3483 Fields{}<a href='#fields' class='anchor'></a></h2>",
3484 document_non_exhaustive_header(it))?;
3485 document_non_exhaustive(w, it)?;
3486 for (field, ty) in fields {
3487 let id = cx.derive_id(format!("{}.{}",
3488 ItemType::StructField,
3489 field.name.as_ref().unwrap()));
3490 let ns_id = cx.derive_id(format!("{}.{}",
3491 field.name.as_ref().unwrap(),
3492 ItemType::StructField.name_space()));
3493 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3494 <a href=\"#{id}\" class=\"anchor field\"></a>\
3495 <code id=\"{ns_id}\">{name}: {ty}</code>\
3497 item_type = ItemType::StructField,
3500 name = field.name.as_ref().unwrap(),
3502 document(w, cx, field)?;
3506 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3509 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3510 s: &clean::Union) -> fmt::Result {
3511 wrap_into_docblock(w, |w| {
3512 write!(w, "<pre class='rust union'>")?;
3513 render_attributes(w, it)?;
3523 document(w, cx, it)?;
3524 let mut fields = s.fields.iter().filter_map(|f| {
3526 clean::StructFieldItem(ref ty) => Some((f, ty)),
3530 if fields.peek().is_some() {
3531 write!(w, "<h2 id='fields' class='fields small-section-header'>
3532 Fields<a href='#fields' class='anchor'></a></h2>")?;
3533 for (field, ty) in fields {
3534 let name = field.name.as_ref().expect("union field name");
3535 let id = format!("{}.{}", ItemType::StructField, name);
3536 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3537 <a href=\"#{id}\" class=\"anchor field\"></a>\
3538 <code>{name}: {ty}</code>\
3542 shortty = ItemType::StructField,
3544 if let Some(stability_class) = field.stability_class() {
3545 write!(w, "<span class='stab {stab}'></span>",
3546 stab = stability_class)?;
3548 document(w, cx, field)?;
3551 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3554 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3555 e: &clean::Enum) -> fmt::Result {
3556 wrap_into_docblock(w, |w| {
3557 write!(w, "<pre class='rust enum'>")?;
3558 render_attributes(w, it)?;
3559 write!(w, "{}enum {}{}{}",
3560 VisSpace(&it.visibility),
3561 it.name.as_ref().unwrap(),
3563 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3564 if e.variants.is_empty() && !e.variants_stripped {
3565 write!(w, " {{}}")?;
3567 write!(w, " {{\n")?;
3568 for v in &e.variants {
3570 let name = v.name.as_ref().unwrap();
3572 clean::VariantItem(ref var) => {
3574 clean::VariantKind::CLike => write!(w, "{}", name)?,
3575 clean::VariantKind::Tuple(ref tys) => {
3576 write!(w, "{}(", name)?;
3577 for (i, ty) in tys.iter().enumerate() {
3579 write!(w, ", ")?
3581 write!(w, "{}", *ty)?;
3585 clean::VariantKind::Struct(ref s) => {
3601 if e.variants_stripped {
3602 write!(w, " // some variants omitted\n")?;
3609 document(w, cx, it)?;
3610 if !e.variants.is_empty() {
3611 write!(w, "<h2 id='variants' class='variants small-section-header'>
3612 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3613 document_non_exhaustive_header(it))?;
3614 document_non_exhaustive(w, it)?;
3615 for variant in &e.variants {
3616 let id = cx.derive_id(format!("{}.{}",
3618 variant.name.as_ref().unwrap()));
3619 let ns_id = cx.derive_id(format!("{}.{}",
3620 variant.name.as_ref().unwrap(),
3621 ItemType::Variant.name_space()));
3622 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3623 <a href=\"#{id}\" class=\"anchor field\"></a>\
3624 <code id='{ns_id}'>{name}",
3627 name = variant.name.as_ref().unwrap())?;
3628 if let clean::VariantItem(ref var) = variant.inner {
3629 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3631 for (i, ty) in tys.iter().enumerate() {
3633 write!(w, ", ")?;
3635 write!(w, "{}", *ty)?;
3640 write!(w, "</code></span>")?;
3641 document(w, cx, variant)?;
3643 use clean::{Variant, VariantKind};
3644 if let clean::VariantItem(Variant {
3645 kind: VariantKind::Struct(ref s)
3646 }) = variant.inner {
3647 let variant_id = cx.derive_id(format!("{}.{}.fields",
3649 variant.name.as_ref().unwrap()));
3650 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3652 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3653 name = variant.name.as_ref().unwrap())?;
3654 for field in &s.fields {
3655 use clean::StructFieldItem;
3656 if let StructFieldItem(ref ty) = field.inner {
3657 let id = cx.derive_id(format!("variant.{}.field.{}",
3658 variant.name.as_ref().unwrap(),
3659 field.name.as_ref().unwrap()));
3660 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3661 variant.name.as_ref().unwrap(),
3662 ItemType::Variant.name_space(),
3663 field.name.as_ref().unwrap(),
3664 ItemType::StructField.name_space()));
3665 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3666 <a href=\"#{id}\" class=\"anchor field\"></a>\
3667 <code id='{ns_id}'>{f}: {t}\
3671 f = field.name.as_ref().unwrap(),
3673 document(w, cx, field)?;
3676 write!(w, "</div></span>")?;
3678 render_stability_since(w, variant, it)?;
3681 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3685 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3686 let name = attr.name();
3689 Some(name.to_string())
3690 } else if let Some(v) = attr.value_str() {
3691 Some(format!("{} = {:?}", name, v.as_str()))
3692 } else if let Some(values) = attr.meta_item_list() {
3693 let display: Vec<_> = values.iter().filter_map(|attr| {
3694 attr.meta_item().and_then(|mi| render_attribute(mi))
3697 if display.len() > 0 {
3698 Some(format!("{}({})", name, display.join(", ")))
3707 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3714 "unsafe_destructor_blind_to_params",
3718 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3719 let mut attrs = String::new();
3721 for attr in &it.attrs.other_attrs {
3722 let name = attr.name();
3723 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3726 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3727 attrs.push_str(&format!("#[{}]\n", s));
3730 if attrs.len() > 0 {
3731 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3736 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3737 g: Option<&clean::Generics>,
3738 ty: doctree::StructType,
3739 fields: &[clean::Item],
3741 structhead: bool) -> fmt::Result {
3743 VisSpace(&it.visibility),
3744 if structhead {"struct "} else {""},
3745 it.name.as_ref().unwrap())?;
3746 if let Some(g) = g {
3751 if let Some(g) = g {
3752 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3754 let mut has_visible_fields = false;
3756 for field in fields {
3757 if let clean::StructFieldItem(ref ty) = field.inner {
3758 write!(w, "\n{} {}{}: {},",
3760 VisSpace(&field.visibility),
3761 field.name.as_ref().unwrap(),
3763 has_visible_fields = true;
3767 if has_visible_fields {
3768 if it.has_stripped_fields().unwrap() {
3769 write!(w, "\n{} // some fields omitted", tab)?;
3771 write!(w, "\n{}", tab)?;
3772 } else if it.has_stripped_fields().unwrap() {
3773 // If there are no visible fields we can just display
3774 // `{ /* fields omitted */ }` to save space.
3775 write!(w, " /* fields omitted */ ")?;
3781 for (i, field) in fields.iter().enumerate() {
3786 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3789 clean::StructFieldItem(ref ty) => {
3790 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3796 if let Some(g) = g {
3797 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3802 // Needed for PhantomData.
3803 if let Some(g) = g {
3804 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3812 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3813 g: Option<&clean::Generics>,
3814 fields: &[clean::Item],
3816 structhead: bool) -> fmt::Result {
3818 VisSpace(&it.visibility),
3819 if structhead {"union "} else {""},
3820 it.name.as_ref().unwrap())?;
3821 if let Some(g) = g {
3822 write!(w, "{}", g)?;
3823 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3826 write!(w, " {{\n{}", tab)?;
3827 for field in fields {
3828 if let clean::StructFieldItem(ref ty) = field.inner {
3829 write!(w, " {}{}: {},\n{}",
3830 VisSpace(&field.visibility),
3831 field.name.as_ref().unwrap(),
3837 if it.has_stripped_fields().unwrap() {
3838 write!(w, " // some fields omitted\n{}", tab)?;
3844 #[derive(Copy, Clone)]
3845 enum AssocItemLink<'a> {
3846 Anchor(Option<&'a str>),
3847 GotoSource(DefId, &'a FxHashSet<String>),
3850 impl<'a> AssocItemLink<'a> {
3851 fn anchor(&self, id: &'a String) -> Self {
3853 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3854 ref other => *other,
3859 enum AssocItemRender<'a> {
3861 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3864 #[derive(Copy, Clone, PartialEq)]
3867 ForDeref { mut_: bool },
3870 fn render_assoc_items(w: &mut fmt::Formatter,
3872 containing_item: &clean::Item,
3874 what: AssocItemRender) -> fmt::Result {
3876 let v = match c.impls.get(&it) {
3878 None => return Ok(()),
3880 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3881 i.inner_impl().trait_.is_none()
3883 if !non_trait.is_empty() {
3884 let render_mode = match what {
3885 AssocItemRender::All => {
3887 <h2 id='methods' class='small-section-header'>\
3888 Methods<a href='#methods' class='anchor'></a>\
3893 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3895 <h2 id='deref-methods' class='small-section-header'>\
3896 Methods from {}<Target = {}>\
3897 <a href='#deref-methods' class='anchor'></a>\
3900 RenderMode::ForDeref { mut_: deref_mut_ }
3903 for i in &non_trait {
3904 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3905 containing_item.stable_since(), true, None)?;
3908 if let AssocItemRender::DerefFor { .. } = what {
3911 if !traits.is_empty() {
3912 let deref_impl = traits.iter().find(|t| {
3913 t.inner_impl().trait_.def_id() == c.deref_trait_did
3915 if let Some(impl_) = deref_impl {
3916 let has_deref_mut = traits.iter().find(|t| {
3917 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3919 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3922 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3924 .partition(|t| t.inner_impl().synthetic);
3925 let (blanket_impl, concrete) = concrete
3927 .partition(|t| t.inner_impl().blanket_impl.is_some());
3929 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3931 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3932 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3933 render_impls(self.0, fmt, &self.1, self.2)
3937 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3938 if !impls.is_empty() {
3940 <h2 id='implementations' class='small-section-header'>\
3941 Trait Implementations<a href='#implementations' class='anchor'></a>\
3943 <div id='implementations-list'>{}</div>", impls)?;
3946 if !synthetic.is_empty() {
3948 <h2 id='synthetic-implementations' class='small-section-header'>\
3949 Auto Trait Implementations\
3950 <a href='#synthetic-implementations' class='anchor'></a>\
3952 <div id='synthetic-implementations-list'>\
3954 render_impls(cx, w, &synthetic, containing_item)?;
3955 write!(w, "</div>")?;
3958 if !blanket_impl.is_empty() {
3960 <h2 id='blanket-implementations' class='small-section-header'>\
3961 Blanket Implementations\
3962 <a href='#blanket-implementations' class='anchor'></a>\
3964 <div id='blanket-implementations-list'>\
3966 render_impls(cx, w, &blanket_impl, containing_item)?;
3967 write!(w, "</div>")?;
3973 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3974 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3975 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3976 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3978 clean::TypedefItem(ref t, true) => Some(&t.type_),
3981 }).next().expect("Expected associated type binding");
3982 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3983 deref_mut_: deref_mut };
3984 if let Some(did) = target.def_id() {
3985 render_assoc_items(w, cx, container_item, did, what)
3987 if let Some(prim) = target.primitive_type() {
3988 if let Some(&did) = cache().primitive_locations.get(&prim) {
3989 render_assoc_items(w, cx, container_item, did, what)?;
3996 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3997 let self_type_opt = match item.inner {
3998 clean::MethodItem(ref method) => method.decl.self_type(),
3999 clean::TyMethodItem(ref method) => method.decl.self_type(),
4003 if let Some(self_ty) = self_type_opt {
4004 let (by_mut_ref, by_box, by_value) = match self_ty {
4005 SelfTy::SelfBorrowed(_, mutability) |
4006 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4007 (mutability == Mutability::Mutable, false, false)
4009 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4010 (false, Some(did) == cache().owned_box_did, false)
4012 SelfTy::SelfValue => (false, false, true),
4013 _ => (false, false, false),
4016 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4022 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4023 let mut out = String::new();
4026 clean::FunctionItem(clean::Function { ref decl, .. }) |
4027 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4028 clean::MethodItem(clean::Method { ref decl, .. }) |
4029 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4030 out = spotlight_decl(decl)?;
4038 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4039 let mut out = String::new();
4040 let mut trait_ = String::new();
4042 if let Some(did) = decl.output.def_id() {
4044 if let Some(impls) = c.impls.get(&did) {
4046 let impl_ = i.inner_impl();
4047 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4050 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4051 <code class=\"content\">",
4053 trait_.push_str(&impl_.for_.to_string());
4056 //use the "where" class here to make it small
4057 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4058 let t_did = impl_.trait_.def_id().unwrap();
4059 for it in &impl_.items {
4060 if let clean::TypedefItem(ref tydef, _) = it.inner {
4061 out.push_str("<span class=\"where fmt-newline\"> ");
4062 assoc_type(&mut out, it, &[],
4064 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4065 out.push_str(";</span>");
4073 if !out.is_empty() {
4074 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4075 <span class='tooltiptext'>Important traits for {}</span></div>\
4076 <div class=\"content hidden\">",
4078 out.push_str("</code></div></div>");
4084 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
4085 render_mode: RenderMode, outer_version: Option<&str>,
4086 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4087 if render_mode == RenderMode::Normal {
4088 let id = cx.derive_id(match i.inner_impl().trait_ {
4089 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4090 None => "impl".to_string(),
4092 if let Some(use_absolute) = use_absolute {
4093 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4094 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4096 for it in &i.inner_impl().items {
4097 if let clean::TypedefItem(ref tydef, _) = it.inner {
4098 write!(w, "<span class=\"where fmt-newline\"> ")?;
4099 assoc_type(w, it, &vec![], Some(&tydef.type_),
4100 AssocItemLink::Anchor(None))?;
4101 write!(w, ";</span>")?;
4105 write!(w, "</code>")?;
4107 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4111 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4112 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4113 render_stability_since_raw(w, since, outer_version)?;
4114 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4115 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4116 l, "goto source code")?;
4118 write!(w, "</h3>")?;
4119 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4120 let mut ids = cx.id_map.borrow_mut();
4121 write!(w, "<div class='docblock'>{}</div>",
4122 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4126 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4127 link: AssocItemLink, render_mode: RenderMode,
4128 is_default_item: bool, outer_version: Option<&str>,
4129 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4130 let item_type = item.type_();
4131 let name = item.name.as_ref().unwrap();
4133 let render_method_item: bool = match render_mode {
4134 RenderMode::Normal => true,
4135 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4138 let (is_hidden, extra_class) = if trait_.is_none() ||
4139 item.doc_value().is_some() ||
4140 item.inner.is_associated() {
4146 clean::MethodItem(clean::Method { ref decl, .. }) |
4147 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4148 // Only render when the method is not static or we allow static methods
4149 if render_method_item {
4150 let id = cx.derive_id(format!("{}.{}", item_type, name));
4151 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4152 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4153 write!(w, "{}", spotlight_decl(decl)?)?;
4154 write!(w, "<code id='{}'>", ns_id)?;
4155 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4156 write!(w, "</code>")?;
4157 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4158 if let Some(l) = (Item { cx, item }).src_href() {
4159 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4160 l, "goto source code")?;
4162 write!(w, "</h4>")?;
4165 clean::TypedefItem(ref tydef, _) => {
4166 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4167 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4168 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4169 write!(w, "<code id='{}'>", ns_id)?;
4170 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4171 write!(w, "</code></h4>")?;
4173 clean::AssociatedConstItem(ref ty, ref default) => {
4174 let id = cx.derive_id(format!("{}.{}", item_type, name));
4175 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4176 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4177 write!(w, "<code id='{}'>", ns_id)?;
4178 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4179 write!(w, "</code>")?;
4180 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4181 if let Some(l) = (Item { cx, item }).src_href() {
4182 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4183 l, "goto source code")?;
4185 write!(w, "</h4>")?;
4187 clean::AssociatedTypeItem(ref bounds, ref default) => {
4188 let id = cx.derive_id(format!("{}.{}", item_type, name));
4189 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4190 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4191 write!(w, "<code id='{}'>", ns_id)?;
4192 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4193 write!(w, "</code></h4>")?;
4195 clean::StrippedItem(..) => return Ok(()),
4196 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4199 if render_method_item || render_mode == RenderMode::Normal {
4200 if !is_default_item {
4201 if let Some(t) = trait_ {
4202 // The trait item may have been stripped so we might not
4203 // find any documentation or stability for it.
4204 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4205 // We need the stability of the item from the trait
4206 // because impls can't have a stability.
4207 document_stability(w, cx, it, is_hidden)?;
4208 if item.doc_value().is_some() {
4209 document_full(w, item, cx, "", is_hidden)?;
4210 } else if show_def_docs {
4211 // In case the item isn't documented,
4212 // provide short documentation from the trait.
4213 document_short(w, cx, it, link, "", is_hidden)?;
4217 document_stability(w, cx, item, is_hidden)?;
4219 document_full(w, item, cx, "", is_hidden)?;
4223 document_stability(w, cx, item, is_hidden)?;
4225 document_short(w, cx, item, link, "", is_hidden)?;
4232 let traits = &cache().traits;
4233 let trait_ = i.trait_did().map(|did| &traits[&did]);
4235 write!(w, "<div class='impl-items'>")?;
4236 for trait_item in &i.inner_impl().items {
4237 doc_impl_item(w, cx, trait_item, link, render_mode,
4238 false, outer_version, trait_, show_def_docs)?;
4241 fn render_default_items(w: &mut fmt::Formatter,
4245 render_mode: RenderMode,
4246 outer_version: Option<&str>,
4247 show_def_docs: bool) -> fmt::Result {
4248 for trait_item in &t.items {
4249 let n = trait_item.name.clone();
4250 if i.items.iter().find(|m| m.name == n).is_some() {
4253 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4254 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4256 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4257 outer_version, None, show_def_docs)?;
4262 // If we've implemented a trait, then also emit documentation for all
4263 // default items which weren't overridden in the implementation block.
4264 if let Some(t) = trait_ {
4265 render_default_items(w, cx, t, &i.inner_impl(),
4266 render_mode, outer_version, show_def_docs)?;
4268 write!(w, "</div>")?;
4273 fn item_existential(
4274 w: &mut fmt::Formatter,
4277 t: &clean::Existential,
4279 write!(w, "<pre class='rust existential'>")?;
4280 render_attributes(w, it)?;
4281 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4282 it.name.as_ref().unwrap(),
4284 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4285 bounds = bounds(&t.bounds, false))?;
4287 document(w, cx, it)?;
4289 // Render any items associated directly to this alias, as otherwise they
4290 // won't be visible anywhere in the docs. It would be nice to also show
4291 // associated items from the aliased type (see discussion in #32077), but
4292 // we need #14072 to make sense of the generics.
4293 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4296 fn item_trait_alias(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4297 t: &clean::TraitAlias) -> fmt::Result {
4298 write!(w, "<pre class='rust trait-alias'>")?;
4299 render_attributes(w, it)?;
4300 write!(w, "trait {}{}{} = {};</pre>",
4301 it.name.as_ref().unwrap(),
4303 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4304 bounds(&t.bounds, true))?;
4306 document(w, cx, it)?;
4308 // Render any items associated directly to this alias, as otherwise they
4309 // won't be visible anywhere in the docs. It would be nice to also show
4310 // associated items from the aliased type (see discussion in #32077), but
4311 // we need #14072 to make sense of the generics.
4312 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4315 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4316 t: &clean::Typedef) -> fmt::Result {
4317 write!(w, "<pre class='rust typedef'>")?;
4318 render_attributes(w, it)?;
4319 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4320 it.name.as_ref().unwrap(),
4322 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4325 document(w, cx, it)?;
4327 // Render any items associated directly to this alias, as otherwise they
4328 // won't be visible anywhere in the docs. It would be nice to also show
4329 // associated items from the aliased type (see discussion in #32077), but
4330 // we need #14072 to make sense of the generics.
4331 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4334 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4335 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4336 render_attributes(w, it)?;
4339 " {}type {};\n}}</pre>",
4340 VisSpace(&it.visibility),
4341 it.name.as_ref().unwrap(),
4344 document(w, cx, it)?;
4346 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4349 impl<'a> fmt::Display for Sidebar<'a> {
4350 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4353 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4355 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4356 || it.is_enum() || it.is_mod() || it.is_typedef() {
4357 write!(fmt, "<p class='location'>{}{}</p>",
4359 clean::StructItem(..) => "Struct ",
4360 clean::TraitItem(..) => "Trait ",
4361 clean::PrimitiveItem(..) => "Primitive Type ",
4362 clean::UnionItem(..) => "Union ",
4363 clean::EnumItem(..) => "Enum ",
4364 clean::TypedefItem(..) => "Type Definition ",
4365 clean::ForeignTypeItem => "Foreign Type ",
4366 clean::ModuleItem(..) => if it.is_crate() {
4373 it.name.as_ref().unwrap())?;
4377 if let Some(ref version) = cache().crate_version {
4379 "<div class='block version'>\
4386 write!(fmt, "<div class=\"sidebar-elems\">")?;
4388 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4389 it.name.as_ref().expect("crates always have a name"))?;
4392 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4393 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4394 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4395 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4396 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4397 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4398 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4399 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4403 // The sidebar is designed to display sibling functions, modules and
4404 // other miscellaneous information. since there are lots of sibling
4405 // items (and that causes quadratic growth in large modules),
4406 // we refactor common parts into a shared JavaScript file per module.
4407 // still, we don't move everything into JS because we want to preserve
4408 // as much HTML as possible in order to allow non-JS-enabled browsers
4409 // to navigate the documentation (though slightly inefficiently).
4411 write!(fmt, "<p class='location'>")?;
4412 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4414 write!(fmt, "::<wbr>")?;
4416 write!(fmt, "<a href='{}index.html'>{}</a>",
4417 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4420 write!(fmt, "</p>")?;
4422 // Sidebar refers to the enclosing module, not this module.
4423 let relpath = if it.is_mod() { "../" } else { "" };
4425 "<script>window.sidebarCurrent = {{\
4430 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4431 ty = it.type_().css_class(),
4434 // There is no sidebar-items.js beyond the crate root path
4435 // FIXME maybe dynamic crate loading can be merged here
4437 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4440 // Closes sidebar-elems div.
4441 write!(fmt, "</div>")?;
4447 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4448 if used_links.insert(url.clone()) {
4452 while used_links.insert(format!("{}-{}", url, add)) == false {
4455 format!("{}-{}", url, add)
4461 used_links: &mut FxHashSet<String>,
4463 i.items.iter().filter_map(|item| {
4465 // Maybe check with clean::Visibility::Public as well?
4466 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4467 if !for_deref || should_render_item(item, false) {
4468 Some(format!("<a href=\"#{}\">{}</a>",
4469 get_next_url(used_links, format!("method.{}", name)),
4477 }).collect::<Vec<_>>()
4480 // The point is to url encode any potential character from a type with genericity.
4481 fn small_url_encode(s: &str) -> String {
4482 s.replace("<", "%3C")
4483 .replace(">", "%3E")
4484 .replace(" ", "%20")
4485 .replace("?", "%3F")
4486 .replace("'", "%27")
4487 .replace("&", "%26")
4488 .replace(",", "%2C")
4489 .replace(":", "%3A")
4490 .replace(";", "%3B")
4491 .replace("[", "%5B")
4492 .replace("]", "%5D")
4493 .replace("\"", "%22")
4496 fn sidebar_assoc_items(it: &clean::Item) -> String {
4497 let mut out = String::new();
4499 if let Some(v) = c.impls.get(&it.def_id) {
4500 let mut used_links = FxHashSet::default();
4503 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4504 let mut ret = v.iter()
4505 .filter(|i| i.inner_impl().trait_.is_none())
4506 .flat_map(move |i| get_methods(i.inner_impl(),
4508 &mut used_links_bor.borrow_mut()))
4509 .collect::<Vec<_>>();
4510 // We want links' order to be reproducible so we don't use unstable sort.
4512 if !ret.is_empty() {
4513 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4514 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4518 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4519 if let Some(impl_) = v.iter()
4520 .filter(|i| i.inner_impl().trait_.is_some())
4521 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4522 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4524 clean::TypedefItem(ref t, true) => Some(&t.type_),
4528 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4529 c.primitive_locations.get(&prim).cloned()
4530 })).and_then(|did| c.impls.get(&did));
4531 if let Some(impls) = inner_impl {
4532 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4533 out.push_str(&format!("Methods from {}<Target={}>",
4534 Escape(&format!("{:#}",
4535 impl_.inner_impl().trait_.as_ref().unwrap())),
4536 Escape(&format!("{:#}", target))));
4537 out.push_str("</a>");
4538 let mut ret = impls.iter()
4539 .filter(|i| i.inner_impl().trait_.is_none())
4540 .flat_map(|i| get_methods(i.inner_impl(),
4543 .collect::<Vec<_>>();
4544 // We want links' order to be reproducible so we don't use unstable sort.
4546 if !ret.is_empty() {
4547 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4553 let format_impls = |impls: Vec<&Impl>| {
4554 let mut links = FxHashSet::default();
4556 let mut ret = impls.iter()
4558 let is_negative_impl = is_negative_impl(i.inner_impl());
4559 if let Some(ref i) = i.inner_impl().trait_ {
4560 let i_display = format!("{:#}", i);
4561 let out = Escape(&i_display);
4562 let encoded = small_url_encode(&format!("{:#}", i));
4563 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4565 if is_negative_impl { "!" } else { "" },
4567 if links.insert(generated.clone()) {
4576 .collect::<Vec<String>>();
4581 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4583 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4584 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4586 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4588 let concrete_format = format_impls(concrete);
4589 let synthetic_format = format_impls(synthetic);
4590 let blanket_format = format_impls(blanket_impl);
4592 if !concrete_format.is_empty() {
4593 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4594 Trait Implementations</a>");
4595 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4598 if !synthetic_format.is_empty() {
4599 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4600 Auto Trait Implementations</a>");
4601 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4604 if !blanket_format.is_empty() {
4605 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4606 Blanket Implementations</a>");
4607 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4615 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4616 s: &clean::Struct) -> fmt::Result {
4617 let mut sidebar = String::new();
4618 let fields = get_struct_fields_name(&s.fields);
4620 if !fields.is_empty() {
4621 if let doctree::Plain = s.struct_type {
4622 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4623 <div class=\"sidebar-links\">{}</div>", fields));
4627 sidebar.push_str(&sidebar_assoc_items(it));
4629 if !sidebar.is_empty() {
4630 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4635 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4637 clean::ItemEnum::ImplItem(ref i) => {
4638 if let Some(ref trait_) = i.trait_ {
4639 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4648 fn is_negative_impl(i: &clean::Impl) -> bool {
4649 i.polarity == Some(clean::ImplPolarity::Negative)
4652 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4653 t: &clean::Trait) -> fmt::Result {
4654 let mut sidebar = String::new();
4660 Some(ref name) if m.is_associated_type() => {
4661 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4667 .collect::<String>();
4668 let consts = t.items
4672 Some(ref name) if m.is_associated_const() => {
4673 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4679 .collect::<String>();
4680 let mut required = t.items
4684 Some(ref name) if m.is_ty_method() => {
4685 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4691 .collect::<Vec<String>>();
4692 let mut provided = t.items
4696 Some(ref name) if m.is_method() => {
4697 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4702 .collect::<Vec<String>>();
4704 if !types.is_empty() {
4705 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4706 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4709 if !consts.is_empty() {
4710 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4711 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4714 if !required.is_empty() {
4716 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4717 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4718 required.join("")));
4720 if !provided.is_empty() {
4722 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4723 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4724 provided.join("")));
4729 if let Some(implementors) = c.implementors.get(&it.def_id) {
4730 let mut res = implementors.iter()
4731 .filter(|i| i.inner_impl().for_.def_id()
4732 .map_or(false, |d| !c.paths.contains_key(&d)))
4734 match extract_for_impl_name(&i.impl_item) {
4735 Some((ref name, ref url)) => {
4736 Some(format!("<a href=\"#impl-{}\">{}</a>",
4737 small_url_encode(url),
4743 .collect::<Vec<String>>();
4744 if !res.is_empty() {
4746 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4747 Implementations on Foreign Types</a><div \
4748 class=\"sidebar-links\">{}</div>",
4753 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4755 sidebar.push_str("<a class=\"sidebar-title\" \
4756 href=\"#synthetic-implementors\">Auto Implementors</a>");
4759 sidebar.push_str(&sidebar_assoc_items(it));
4761 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4764 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4765 _p: &clean::PrimitiveType) -> fmt::Result {
4766 let sidebar = sidebar_assoc_items(it);
4768 if !sidebar.is_empty() {
4769 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4774 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4775 _t: &clean::Typedef) -> fmt::Result {
4776 let sidebar = sidebar_assoc_items(it);
4778 if !sidebar.is_empty() {
4779 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4784 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4786 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4791 .filter_map(|f| match f.name {
4792 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4793 {name}</a>", name=name)),
4799 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4800 u: &clean::Union) -> fmt::Result {
4801 let mut sidebar = String::new();
4802 let fields = get_struct_fields_name(&u.fields);
4804 if !fields.is_empty() {
4805 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4806 <div class=\"sidebar-links\">{}</div>", fields));
4809 sidebar.push_str(&sidebar_assoc_items(it));
4811 if !sidebar.is_empty() {
4812 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4817 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4818 e: &clean::Enum) -> fmt::Result {
4819 let mut sidebar = String::new();
4821 let variants = e.variants.iter()
4822 .filter_map(|v| match v.name {
4823 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4824 </a>", name = name)),
4827 .collect::<String>();
4828 if !variants.is_empty() {
4829 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4830 <div class=\"sidebar-links\">{}</div>", variants));
4833 sidebar.push_str(&sidebar_assoc_items(it));
4835 if !sidebar.is_empty() {
4836 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4841 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4843 ItemType::ExternCrate |
4844 ItemType::Import => ("reexports", "Re-exports"),
4845 ItemType::Module => ("modules", "Modules"),
4846 ItemType::Struct => ("structs", "Structs"),
4847 ItemType::Union => ("unions", "Unions"),
4848 ItemType::Enum => ("enums", "Enums"),
4849 ItemType::Function => ("functions", "Functions"),
4850 ItemType::Typedef => ("types", "Type Definitions"),
4851 ItemType::Static => ("statics", "Statics"),
4852 ItemType::Constant => ("constants", "Constants"),
4853 ItemType::Trait => ("traits", "Traits"),
4854 ItemType::Impl => ("impls", "Implementations"),
4855 ItemType::TyMethod => ("tymethods", "Type Methods"),
4856 ItemType::Method => ("methods", "Methods"),
4857 ItemType::StructField => ("fields", "Struct Fields"),
4858 ItemType::Variant => ("variants", "Variants"),
4859 ItemType::Macro => ("macros", "Macros"),
4860 ItemType::Primitive => ("primitives", "Primitive Types"),
4861 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4862 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4863 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4864 ItemType::Keyword => ("keywords", "Keywords"),
4865 ItemType::Existential => ("existentials", "Existentials"),
4866 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4867 ItemType::ProcDerive => ("derives", "Derive Macros"),
4868 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4872 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4873 items: &[clean::Item]) -> fmt::Result {
4874 let mut sidebar = String::new();
4876 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4877 it.type_() == ItemType::Import) {
4878 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4880 name = "Re-exports"));
4883 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4884 // to print its headings
4885 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4886 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4887 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4888 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4889 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4890 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4891 let (short, name) = item_ty_to_strs(&myty);
4892 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4898 if !sidebar.is_empty() {
4899 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4904 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4905 let sidebar = sidebar_assoc_items(it);
4906 if !sidebar.is_empty() {
4907 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4912 impl<'a> fmt::Display for Source<'a> {
4913 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4914 let Source(s) = *self;
4915 let lines = s.lines().count();
4917 let mut tmp = lines;
4922 write!(fmt, "<pre class=\"line-numbers\">")?;
4923 for i in 1..=lines {
4924 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4926 write!(fmt, "</pre>")?;
4928 highlight::render_with_highlighting(s, None, None, None))?;
4933 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4934 t: &clean::Macro) -> fmt::Result {
4935 wrap_into_docblock(w, |w| {
4936 w.write_str(&highlight::render_with_highlighting(&t.source,
4944 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4947 let name = it.name.as_ref().expect("proc-macros always have names");
4949 MacroKind::Bang => {
4950 write!(w, "<pre class='rust macro'>")?;
4951 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4952 write!(w, "</pre>")?;
4954 MacroKind::Attr => {
4955 write!(w, "<pre class='rust attr'>")?;
4956 write!(w, "#[{}]", name)?;
4957 write!(w, "</pre>")?;
4959 MacroKind::Derive => {
4960 write!(w, "<pre class='rust derive'>")?;
4961 write!(w, "#[derive({})]", name)?;
4962 if !m.helpers.is_empty() {
4963 writeln!(w, "\n{{")?;
4964 writeln!(w, " // Attributes available to this derive:")?;
4965 for attr in &m.helpers {
4966 writeln!(w, " #[{}]", attr)?;
4970 write!(w, "</pre>")?;
4977 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4979 _p: &clean::PrimitiveType) -> fmt::Result {
4980 document(w, cx, it)?;
4981 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4984 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4986 _p: &str) -> fmt::Result {
4990 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4992 fn make_item_keywords(it: &clean::Item) -> String {
4993 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4996 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4997 let decl = match item.inner {
4998 clean::FunctionItem(ref f) => &f.decl,
4999 clean::MethodItem(ref m) => &m.decl,
5000 clean::TyMethodItem(ref m) => &m.decl,
5004 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
5005 let output = match decl.output {
5006 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
5010 Some(IndexItemFunctionType { inputs: inputs, output: output })
5013 fn get_index_type(clean_type: &clean::Type) -> Type {
5015 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
5016 generics: get_generics(clean_type),
5021 /// Returns a list of all paths used in the type.
5022 /// This is used to help deduplicate imported impls
5023 /// for reexported types. If any of the contained
5024 /// types are re-exported, we don't use the corresponding
5025 /// entry from the js file, as inlining will have already
5026 /// picked up the impl
5027 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5028 let mut out = Vec::new();
5029 let mut visited = FxHashSet::default();
5030 let mut work = VecDeque::new();
5031 let cache = cache();
5033 work.push_back(first_ty);
5035 while let Some(ty) = work.pop_front() {
5036 if !visited.insert(ty.clone()) {
5041 clean::Type::ResolvedPath { did, .. } => {
5042 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5043 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5047 out.push(path.join("::"));
5053 clean::Type::Tuple(tys) => {
5054 work.extend(tys.into_iter());
5056 clean::Type::Slice(ty) => {
5057 work.push_back(*ty);
5059 clean::Type::Array(ty, _) => {
5060 work.push_back(*ty);
5062 clean::Type::Unique(ty) => {
5063 work.push_back(*ty);
5065 clean::Type::RawPointer(_, ty) => {
5066 work.push_back(*ty);
5068 clean::Type::BorrowedRef { type_, .. } => {
5069 work.push_back(*type_);
5071 clean::Type::QPath { self_type, trait_, .. } => {
5072 work.push_back(*self_type);
5073 work.push_back(*trait_);
5081 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5083 clean::ResolvedPath { ref path, .. } => {
5084 let segments = &path.segments;
5085 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5086 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5087 clean_type, accept_generic
5089 Some(path_segment.name.clone())
5091 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5092 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5093 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5094 // FIXME: add all from clean::Type.
5099 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5100 clean_type.generics()
5102 let r = types.iter()
5103 .filter_map(|t| get_index_type_name(t, false))
5104 .map(|s| s.to_ascii_lowercase())
5105 .collect::<Vec<_>>();
5114 pub fn cache() -> Arc<Cache> {
5115 CACHE_KEY.with(|c| c.borrow().clone())
5120 fn test_name_key() {
5121 assert_eq!(name_key("0"), ("", 0, 1));
5122 assert_eq!(name_key("123"), ("", 123, 0));
5123 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5124 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5125 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5126 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5127 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5128 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5133 fn test_name_sorting() {
5134 let names = ["Apple",
5136 "Fruit", "Fruit0", "Fruit00",
5137 "Fruit1", "Fruit01",
5138 "Fruit2", "Fruit02",
5143 let mut sorted = names.to_owned();
5144 sorted.sort_by_key(|&s| name_key(s));
5145 assert_eq!(names, sorted);