1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
36 pub use self::ExternalLocation::*;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, VecDeque};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
46 use std::fs::{self, File, OpenOptions};
47 use std::io::prelude::*;
48 use std::io::{self, BufWriter, BufReader};
50 use std::path::{PathBuf, Path, Component};
55 use externalfiles::ExternalHtml;
57 use serialize::json::{ToJson, Json, as_json};
59 use syntax::source_map::FileName;
60 use syntax::feature_gate::UnstableFeatures;
61 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
62 use rustc::middle::privacy::AccessLevels;
63 use rustc::middle::stability;
65 use rustc::util::nodemap::{FxHashMap, FxHashSet};
66 use rustc_data_structures::flock;
68 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
71 use html::escape::Escape;
72 use html::format::{AsyncSpace, ConstnessSpace};
73 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
74 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
75 use html::format::fmt_impl_for_trait_page;
76 use html::item_type::ItemType;
77 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
78 use html::{highlight, layout};
82 /// A pair of name and its optional document.
83 pub type NameDoc = (String, Option<String>);
85 /// Major driving force in all rustdoc rendering. This contains information
86 /// about where in the tree-like hierarchy rendering is occurring and controls
87 /// how the current page is being rendered.
89 /// It is intended that this context is a lightweight object which can be fairly
90 /// easily cloned because it is cloned per work-job (about once per item in the
94 /// Current hierarchy of components leading down to what's currently being
96 pub current: Vec<String>,
97 /// The current destination folder of where HTML artifacts should be placed.
98 /// This changes as the context descends into the module hierarchy.
100 /// A flag, which when `true`, will render pages which redirect to the
101 /// real location of an item. This is used to allow external links to
102 /// publicly reused items to redirect to the right location.
103 pub render_redirect_pages: bool,
104 pub codes: ErrorCodes,
105 /// The map used to ensure all generated 'id=' attributes are unique.
106 id_map: Rc<RefCell<IdMap>>,
107 pub shared: Arc<SharedContext>,
110 struct SharedContext {
111 /// The path to the crate root source minus the file name.
112 /// Used for simplifying paths to the highlighted source code files.
113 pub src_root: PathBuf,
114 /// This describes the layout of each page, and is not modified after
115 /// creation of the context (contains info like the favicon and added html).
116 pub layout: layout::Layout,
117 /// This flag indicates whether `[src]` links should be generated or not. If
118 /// the source files are present in the html rendering, then this will be
120 pub include_sources: bool,
121 /// The local file sources we've emitted and their respective url-paths.
122 pub local_sources: FxHashMap<PathBuf, String>,
123 /// All the passes that were run on this crate.
124 pub passes: FxHashSet<String>,
125 /// The base-URL of the issue tracker for when an item has been tagged with
127 pub issue_tracker_base_url: Option<String>,
128 /// The given user css file which allow to customize the generated
129 /// documentation theme.
130 pub css_file_extension: Option<PathBuf>,
131 /// The directories that have already been created in this doc run. Used to reduce the number
132 /// of spurious `create_dir_all` calls.
133 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
134 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
135 /// should be ordered alphabetically or in order of appearance (in the source code).
136 pub sort_modules_alphabetically: bool,
137 /// Additional themes to be added to the generated docs.
138 pub themes: Vec<PathBuf>,
139 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
141 pub resource_suffix: String,
145 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
146 let mut dirs = self.created_dirs.borrow_mut();
147 if !dirs.contains(dst) {
148 fs::create_dir_all(dst)?;
149 dirs.insert(dst.to_path_buf());
157 /// Returns whether the `collapse-docs` pass was run on this crate.
158 pub fn was_collapsed(&self) -> bool {
159 self.passes.contains("collapse-docs")
162 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
163 /// `collapsed_doc_value` of the given item.
164 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
165 if self.was_collapsed() {
166 item.collapsed_doc_value().map(|s| s.into())
168 item.doc_value().map(|s| s.into())
173 /// Indicates where an external crate can be found.
174 pub enum ExternalLocation {
175 /// Remote URL root of the external crate
177 /// This external crate can be found in the local doc/ folder
179 /// The external crate could not be found.
183 /// Metadata about implementations for a type or trait.
184 #[derive(Clone, Debug)]
186 pub impl_item: clean::Item,
190 fn inner_impl(&self) -> &clean::Impl {
191 match self.impl_item.inner {
192 clean::ImplItem(ref impl_) => impl_,
193 _ => panic!("non-impl item found in impl")
197 fn trait_did(&self) -> Option<DefId> {
198 self.inner_impl().trait_.def_id()
208 impl error::Error for Error {
209 fn description(&self) -> &str {
210 self.error.description()
214 impl Display for Error {
215 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
216 write!(f, "\"{}\": {}", self.file.display(), self.error)
221 pub fn new(e: io::Error, file: &Path) -> Error {
223 file: file.to_path_buf(),
229 macro_rules! try_none {
230 ($e:expr, $file:expr) => ({
234 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
240 macro_rules! try_err {
241 ($e:expr, $file:expr) => ({
244 Err(e) => return Err(Error::new(e, $file)),
249 /// This cache is used to store information about the `clean::Crate` being
250 /// rendered in order to provide more useful documentation. This contains
251 /// information like all implementors of a trait, all traits a type implements,
252 /// documentation for all known traits, etc.
254 /// This structure purposefully does not implement `Clone` because it's intended
255 /// to be a fairly large and expensive structure to clone. Instead this adheres
256 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
257 /// rendering threads.
260 /// Mapping of typaram ids to the name of the type parameter. This is used
261 /// when pretty-printing a type (so pretty printing doesn't have to
262 /// painfully maintain a context like this)
263 pub typarams: FxHashMap<DefId, String>,
265 /// Maps a type id to all known implementations for that type. This is only
266 /// recognized for intra-crate `ResolvedPath` types, and is used to print
267 /// out extra documentation on the page of an enum/struct.
269 /// The values of the map are a list of implementations and documentation
270 /// found on that implementation.
271 pub impls: FxHashMap<DefId, Vec<Impl>>,
273 /// Maintains a mapping of local crate node ids to the fully qualified name
274 /// and "short type description" of that node. This is used when generating
275 /// URLs when a type is being linked to. External paths are not located in
276 /// this map because the `External` type itself has all the information
278 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
280 /// Similar to `paths`, but only holds external paths. This is only used for
281 /// generating explicit hyperlinks to other crates.
282 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
284 /// Maps local def ids of exported types to fully qualified paths.
285 /// Unlike 'paths', this mapping ignores any renames that occur
286 /// due to 'use' statements.
288 /// This map is used when writing out the special 'implementors'
289 /// javascript file. By using the exact path that the type
290 /// is declared with, we ensure that each path will be identical
291 /// to the path used if the corresponding type is inlined. By
292 /// doing this, we can detect duplicate impls on a trait page, and only display
293 /// the impl for the inlined type.
294 pub exact_paths: FxHashMap<DefId, Vec<String>>,
296 /// This map contains information about all known traits of this crate.
297 /// Implementations of a crate should inherit the documentation of the
298 /// parent trait if no extra documentation is specified, and default methods
299 /// should show up in documentation about trait implementations.
300 pub traits: FxHashMap<DefId, clean::Trait>,
302 /// When rendering traits, it's often useful to be able to list all
303 /// implementors of the trait, and this mapping is exactly, that: a mapping
304 /// of trait ids to the list of known implementors of the trait
305 pub implementors: FxHashMap<DefId, Vec<Impl>>,
307 /// Cache of where external crate documentation can be found.
308 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
310 /// Cache of where documentation for primitives can be found.
311 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
313 // Note that external items for which `doc(hidden)` applies to are shown as
314 // non-reachable while local items aren't. This is because we're reusing
315 // the access levels from crateanalysis.
316 pub access_levels: Arc<AccessLevels<DefId>>,
318 /// The version of the crate being documented, if given from the `--crate-version` flag.
319 pub crate_version: Option<String>,
321 // Private fields only used when initially crawling a crate to build a cache
324 parent_stack: Vec<DefId>,
325 parent_is_trait_impl: bool,
326 search_index: Vec<IndexItem>,
328 deref_trait_did: Option<DefId>,
329 deref_mut_trait_did: Option<DefId>,
330 owned_box_did: Option<DefId>,
331 masked_crates: FxHashSet<CrateNum>,
333 // In rare case where a structure is defined in one module but implemented
334 // in another, if the implementing module is parsed before defining module,
335 // then the fully qualified name of the structure isn't presented in `paths`
336 // yet when its implementation methods are being indexed. Caches such methods
337 // and their parent id here and indexes them at the end of crate parsing.
338 orphan_impl_items: Vec<(DefId, clean::Item)>,
340 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
341 /// we need the alias element to have an array of items.
342 aliases: FxHashMap<String, Vec<IndexItem>>,
345 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
346 /// Later on moved into `CACHE_KEY`.
348 pub struct RenderInfo {
349 pub inlined: FxHashSet<DefId>,
350 pub external_paths: ::core::ExternalPaths,
351 pub external_typarams: FxHashMap<DefId, String>,
352 pub exact_paths: FxHashMap<DefId, Vec<String>>,
353 pub deref_trait_did: Option<DefId>,
354 pub deref_mut_trait_did: Option<DefId>,
355 pub owned_box_did: Option<DefId>,
358 /// Helper struct to render all source code to HTML pages
359 struct SourceCollector<'a> {
360 scx: &'a mut SharedContext,
362 /// Root destination to place all HTML output into
366 /// Wrapper struct to render the source code of a file. This will do things like
367 /// adding line numbers to the left-hand side.
368 struct Source<'a>(&'a str);
370 // Helper structs for rendering items/sidebars and carrying along contextual
373 #[derive(Copy, Clone)]
376 item: &'a clean::Item,
379 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
381 /// Struct representing one entry in the JS search index. These are all emitted
382 /// by hand to a large JS file at the end of cache-creation.
389 parent: Option<DefId>,
390 parent_idx: Option<usize>,
391 search_type: Option<IndexItemFunctionType>,
394 impl ToJson for IndexItem {
395 fn to_json(&self) -> Json {
396 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
398 let mut data = Vec::with_capacity(6);
399 data.push((self.ty as usize).to_json());
400 data.push(self.name.to_json());
401 data.push(self.path.to_json());
402 data.push(self.desc.to_json());
403 data.push(self.parent_idx.to_json());
404 data.push(self.search_type.to_json());
410 /// A type used for the search index.
413 name: Option<String>,
414 generics: Option<Vec<String>>,
417 impl ToJson for Type {
418 fn to_json(&self) -> Json {
421 let mut data = Vec::with_capacity(2);
422 data.push(name.to_json());
423 if let Some(ref generics) = self.generics {
424 data.push(generics.to_json());
433 /// Full type of functions/methods in the search index.
435 struct IndexItemFunctionType {
437 output: Option<Type>,
440 impl ToJson for IndexItemFunctionType {
441 fn to_json(&self) -> Json {
442 // If we couldn't figure out a type, just write `null`.
443 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
446 let mut data = Vec::with_capacity(2);
447 data.push(self.inputs.to_json());
448 if let Some(ref output) = self.output {
449 data.push(output.to_json());
456 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
457 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
459 pub fn initial_ids() -> Vec<String> {
471 "synthetic-implementors",
473 "synthetic-implementors-list",
477 ].into_iter().map(|id| (String::from(*id))).collect()
480 /// Generates the documentation for `crate` into the directory `dst`
481 pub fn run(mut krate: clean::Crate,
482 extern_urls: BTreeMap<String, String>,
483 external_html: &ExternalHtml,
484 playground_url: Option<String>,
486 resource_suffix: String,
487 passes: FxHashSet<String>,
488 css_file_extension: Option<PathBuf>,
489 renderinfo: RenderInfo,
490 sort_modules_alphabetically: bool,
491 themes: Vec<PathBuf>,
492 enable_minification: bool,
493 id_map: IdMap) -> Result<(), Error> {
494 let src_root = match krate.src {
495 FileName::Real(ref p) => match p.parent() {
496 Some(p) => p.to_path_buf(),
497 None => PathBuf::new(),
501 let mut scx = SharedContext {
504 include_sources: true,
505 local_sources: FxHashMap(),
506 issue_tracker_base_url: None,
507 layout: layout::Layout {
509 favicon: String::new(),
510 external_html: external_html.clone(),
511 krate: krate.name.clone(),
513 css_file_extension: css_file_extension.clone(),
514 created_dirs: RefCell::new(FxHashSet()),
515 sort_modules_alphabetically,
520 // If user passed in `--playground-url` arg, we fill in crate name here
521 if let Some(url) = playground_url {
522 markdown::PLAYGROUND.with(|slot| {
523 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
527 // Crawl the crate attributes looking for attributes which control how we're
528 // going to emit HTML
529 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
530 for attr in attrs.lists("doc") {
531 let name = attr.name().map(|s| s.as_str());
532 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
533 (Some("html_favicon_url"), Some(s)) => {
534 scx.layout.favicon = s.to_string();
536 (Some("html_logo_url"), Some(s)) => {
537 scx.layout.logo = s.to_string();
539 (Some("html_playground_url"), Some(s)) => {
540 markdown::PLAYGROUND.with(|slot| {
541 let name = krate.name.clone();
542 *slot.borrow_mut() = Some((Some(name), s.to_string()));
545 (Some("issue_tracker_base_url"), Some(s)) => {
546 scx.issue_tracker_base_url = Some(s.to_string());
548 (Some("html_no_source"), None) if attr.is_word() => {
549 scx.include_sources = false;
555 try_err!(fs::create_dir_all(&dst), &dst);
556 krate = render_sources(&dst, &mut scx, krate)?;
560 render_redirect_pages: false,
561 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
562 id_map: Rc::new(RefCell::new(id_map)),
563 shared: Arc::new(scx),
566 // Crawl the crate to build various caches used for the output
577 let external_paths = external_paths.into_iter()
578 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
581 let mut cache = Cache {
586 implementors: FxHashMap(),
588 parent_stack: Vec::new(),
589 search_index: Vec::new(),
590 parent_is_trait_impl: false,
591 extern_locations: FxHashMap(),
592 primitive_locations: FxHashMap(),
594 access_levels: krate.access_levels.clone(),
595 crate_version: krate.version.take(),
596 orphan_impl_items: Vec::new(),
597 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
601 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
602 typarams: external_typarams,
603 aliases: FxHashMap(),
606 // Cache where all our extern crates are located
607 for &(n, ref e) in &krate.externs {
608 let src_root = match e.src {
609 FileName::Real(ref p) => match p.parent() {
610 Some(p) => p.to_path_buf(),
611 None => PathBuf::new(),
615 let extern_url = extern_urls.get(&e.name).map(|u| &**u);
616 cache.extern_locations.insert(n, (e.name.clone(), src_root,
617 extern_location(e, extern_url, &cx.dst)));
619 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
620 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
623 // Cache where all known primitives have their documentation located.
625 // Favor linking to as local extern as possible, so iterate all crates in
626 // reverse topological order.
627 for &(_, ref e) in krate.externs.iter().rev() {
628 for &(def_id, prim, _) in &e.primitives {
629 cache.primitive_locations.insert(prim, def_id);
632 for &(def_id, prim, _) in &krate.primitives {
633 cache.primitive_locations.insert(prim, def_id);
636 cache.stack.push(krate.name.clone());
637 krate = cache.fold_crate(krate);
639 // Build our search index
640 let index = build_index(&krate, &mut cache);
642 // Freeze the cache now that the index has been built. Put an Arc into TLS
643 // for future parallelization opportunities
644 let cache = Arc::new(cache);
645 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
646 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
648 write_shared(&cx, &krate, &*cache, index, enable_minification)?;
650 // And finally render the whole crate's documentation
654 /// Build the search index from the collected metadata
655 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
656 let mut nodeid_to_pathid = FxHashMap();
657 let mut crate_items = Vec::with_capacity(cache.search_index.len());
658 let mut crate_paths = Vec::<Json>::new();
660 let Cache { ref mut search_index,
661 ref orphan_impl_items,
662 ref mut paths, .. } = *cache;
664 // Attach all orphan items to the type's definition if the type
665 // has since been learned.
666 for &(did, ref item) in orphan_impl_items {
667 if let Some(&(ref fqp, _)) = paths.get(&did) {
668 search_index.push(IndexItem {
670 name: item.name.clone().unwrap(),
671 path: fqp[..fqp.len() - 1].join("::"),
672 desc: plain_summary_line(item.doc_value()),
675 search_type: get_index_search_type(&item),
680 // Reduce `NodeId` in paths into smaller sequential numbers,
681 // and prune the paths that do not appear in the index.
682 let mut lastpath = String::new();
683 let mut lastpathid = 0usize;
685 for item in search_index {
686 item.parent_idx = item.parent.map(|nodeid| {
687 if nodeid_to_pathid.contains_key(&nodeid) {
688 *nodeid_to_pathid.get(&nodeid).unwrap()
690 let pathid = lastpathid;
691 nodeid_to_pathid.insert(nodeid, pathid);
694 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
695 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
700 // Omit the parent path if it is same to that of the prior item.
701 if lastpath == item.path {
704 lastpath = item.path.clone();
706 crate_items.push(item.to_json());
709 let crate_doc = krate.module.as_ref().map(|module| {
710 plain_summary_line(module.doc_value())
711 }).unwrap_or(String::new());
713 let mut crate_data = BTreeMap::new();
714 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
715 crate_data.insert("items".to_owned(), Json::Array(crate_items));
716 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
718 // Collect the index into a string
719 format!("searchIndex[{}] = {};",
720 as_json(&krate.name),
721 Json::Object(crate_data))
724 fn write_shared(cx: &Context,
725 krate: &clean::Crate,
727 search_index: String,
728 enable_minification: bool) -> Result<(), Error> {
729 // Write out the shared files. Note that these are shared among all rustdoc
730 // docs placed in the output directory, so this needs to be a synchronized
731 // operation with respect to all other rustdocs running around.
732 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
734 // Add all the static files. These may already exist, but we just
735 // overwrite them anyway to make sure that they're fresh and up-to-date.
737 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
738 include_str!("static/rustdoc.css"),
739 enable_minification)?;
740 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
741 include_str!("static/settings.css"),
742 enable_minification)?;
744 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
745 // then we'll run over the "official" styles.
746 let mut themes: FxHashSet<String> = FxHashSet::default();
748 for entry in &cx.shared.themes {
749 let mut content = Vec::with_capacity(100000);
751 let mut f = try_err!(File::open(&entry), &entry);
752 try_err!(f.read_to_end(&mut content), &entry);
753 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
754 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
755 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
756 content.as_slice())?;
757 themes.insert(theme.to_owned());
760 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
761 include_bytes!("static/brush.svg"))?;
762 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
763 include_bytes!("static/wheel.svg"))?;
764 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
765 include_str!("static/themes/light.css"),
766 enable_minification)?;
767 themes.insert("light".to_owned());
768 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
769 include_str!("static/themes/dark.css"),
770 enable_minification)?;
771 themes.insert("dark".to_owned());
773 let mut themes: Vec<&String> = themes.iter().collect();
775 // To avoid theme switch latencies as much as possible, we put everything theme related
776 // at the beginning of the html files into another js file.
777 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
779 r#"var themes = document.getElementById("theme-choices");
780 var themePicker = document.getElementById("theme-picker");
782 function switchThemeButtonState() {{
783 if (themes.style.display === "block") {{
784 themes.style.display = "none";
785 themePicker.style.borderBottomRightRadius = "3px";
786 themePicker.style.borderBottomLeftRadius = "3px";
788 themes.style.display = "block";
789 themePicker.style.borderBottomRightRadius = "0";
790 themePicker.style.borderBottomLeftRadius = "0";
794 function handleThemeButtonsBlur(e) {{
795 var active = document.activeElement;
796 var related = e.relatedTarget;
798 if (active.id !== "themePicker" &&
799 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
801 (related.id !== "themePicker" &&
802 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
803 switchThemeButtonState();
807 themePicker.onclick = switchThemeButtonState;
808 themePicker.onblur = handleThemeButtonsBlur;
809 [{}].forEach(function(item) {{
810 var but = document.createElement('button');
811 but.innerHTML = item;
812 but.onclick = function(el) {{
813 switchTheme(currentTheme, mainTheme, item);
815 but.onblur = handleThemeButtonsBlur;
816 themes.appendChild(but);
819 .map(|s| format!("\"{}\"", s))
820 .collect::<Vec<String>>()
821 .join(",")).as_bytes(),
824 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
825 include_str!("static/main.js"),
826 enable_minification)?;
827 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
828 include_str!("static/settings.js"),
829 enable_minification)?;
832 let mut data = format!("var resourcesSuffix = \"{}\";\n",
833 cx.shared.resource_suffix);
834 data.push_str(include_str!("static/storage.js"));
835 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
837 enable_minification)?;
840 if let Some(ref css) = cx.shared.css_file_extension {
841 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
842 if !enable_minification {
843 try_err!(fs::copy(css, out), css);
845 let mut f = try_err!(File::open(css), css);
846 let mut buffer = String::with_capacity(1000);
848 try_err!(f.read_to_string(&mut buffer), css);
849 write_minify(out, &buffer, enable_minification)?;
852 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
853 include_str!("static/normalize.css"),
854 enable_minification)?;
855 write(cx.dst.join("FiraSans-Regular.woff"),
856 include_bytes!("static/FiraSans-Regular.woff"))?;
857 write(cx.dst.join("FiraSans-Medium.woff"),
858 include_bytes!("static/FiraSans-Medium.woff"))?;
859 write(cx.dst.join("FiraSans-LICENSE.txt"),
860 include_bytes!("static/FiraSans-LICENSE.txt"))?;
861 write(cx.dst.join("Heuristica-Italic.woff"),
862 include_bytes!("static/Heuristica-Italic.woff"))?;
863 write(cx.dst.join("Heuristica-LICENSE.txt"),
864 include_bytes!("static/Heuristica-LICENSE.txt"))?;
865 write(cx.dst.join("SourceSerifPro-Regular.woff"),
866 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
867 write(cx.dst.join("SourceSerifPro-Bold.woff"),
868 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
869 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
870 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
871 write(cx.dst.join("SourceCodePro-Regular.woff"),
872 include_bytes!("static/SourceCodePro-Regular.woff"))?;
873 write(cx.dst.join("SourceCodePro-Semibold.woff"),
874 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
875 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
876 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
877 write(cx.dst.join("LICENSE-MIT.txt"),
878 include_bytes!("static/LICENSE-MIT.txt"))?;
879 write(cx.dst.join("LICENSE-APACHE.txt"),
880 include_bytes!("static/LICENSE-APACHE.txt"))?;
881 write(cx.dst.join("COPYRIGHT.txt"),
882 include_bytes!("static/COPYRIGHT.txt"))?;
884 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
885 let mut ret = Vec::new();
887 for line in BufReader::new(File::open(path)?).lines() {
889 if !line.starts_with(key) {
892 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
895 ret.push(line.to_string());
901 fn show_item(item: &IndexItem, krate: &str) -> String {
902 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
903 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
904 if let Some(p) = item.parent_idx {
905 format!(",'parent':{}", p)
911 let dst = cx.dst.join("aliases.js");
913 let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
914 let mut w = try_err!(File::create(&dst), &dst);
915 let mut output = String::with_capacity(100);
916 for (alias, items) in &cache.aliases {
917 if items.is_empty() {
920 output.push_str(&format!("\"{}\":[{}],",
923 .map(|v| show_item(v, &krate.name))
927 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
929 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
930 for aliases in &all_aliases {
931 try_err!(writeln!(&mut w, "{}", aliases), &dst);
935 // Update the search index
936 let dst = cx.dst.join("search-index.js");
937 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
938 all_indexes.push(search_index);
939 // Sort the indexes by crate so the file will be generated identically even
940 // with rustdoc running in parallel.
942 let mut w = try_err!(File::create(&dst), &dst);
943 try_err!(writeln!(&mut w, "var N = null;var searchIndex = {{}};"), &dst);
944 for index in &all_indexes {
945 try_err!(write_minify_replacer(&mut w, &*index, enable_minification,
946 &[(minifier::js::Keyword::Null, "N")]),
949 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
951 // Update the list of all implementors for traits
952 let dst = cx.dst.join("implementors");
953 for (&did, imps) in &cache.implementors {
954 // Private modules can leak through to this phase of rustdoc, which
955 // could contain implementations for otherwise private types. In some
956 // rare cases we could find an implementation for an item which wasn't
957 // indexed, so we just skip this step in that case.
959 // FIXME: this is a vague explanation for why this can't be a `get`, in
960 // theory it should be...
961 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
963 None => match cache.external_paths.get(&did) {
969 let mut have_impls = false;
970 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
972 // If the trait and implementation are in the same crate, then
973 // there's no need to emit information about it (there's inlining
974 // going on). If they're in different crates then the crate defining
975 // the trait will be interested in our implementation.
976 if imp.impl_item.def_id.krate == did.krate { continue }
977 // If the implementation is from another crate then that crate
979 if !imp.impl_item.def_id.is_local() { continue }
981 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
982 as_json(&imp.inner_impl().to_string()),
983 imp.inner_impl().synthetic,
984 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
986 implementors.push_str("];");
988 // Only create a js file if we have impls to add to it. If the trait is
989 // documented locally though we always create the file to avoid dead
991 if !have_impls && !cache.paths.contains_key(&did) {
995 let mut mydst = dst.clone();
996 for part in &remote_path[..remote_path.len() - 1] {
999 try_err!(fs::create_dir_all(&mydst), &mydst);
1000 mydst.push(&format!("{}.{}.js",
1001 remote_item_type.css_class(),
1002 remote_path[remote_path.len() - 1]));
1004 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1005 all_implementors.push(implementors);
1006 // Sort the implementors by crate so the file will be generated
1007 // identically even with rustdoc running in parallel.
1008 all_implementors.sort();
1010 let mut f = try_err!(File::create(&mydst), &mydst);
1011 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1012 for implementor in &all_implementors {
1013 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1015 try_err!(writeln!(&mut f, "{}", r"
1016 if (window.register_implementors) {
1017 window.register_implementors(implementors);
1019 window.pending_implementors = implementors;
1022 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1027 fn render_sources(dst: &Path, scx: &mut SharedContext,
1028 krate: clean::Crate) -> Result<clean::Crate, Error> {
1029 info!("emitting source files");
1030 let dst = dst.join("src").join(&krate.name);
1031 try_err!(fs::create_dir_all(&dst), &dst);
1032 let mut folder = SourceCollector {
1036 Ok(folder.fold_crate(krate))
1039 /// Writes the entire contents of a string to a destination, not attempting to
1040 /// catch any errors.
1041 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1042 Ok(try_err!(fs::write(&dst, contents), &dst))
1045 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1046 if enable_minification {
1047 if dst.extension() == Some(&OsStr::new("css")) {
1048 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1049 write(dst, res.as_bytes())
1051 write(dst, minifier::js::minify(contents).as_bytes())
1054 write(dst, contents.as_bytes())
1058 fn write_minify_replacer<W: Write>(dst: &mut W,
1060 enable_minification: bool,
1061 keywords_to_replace: &[(minifier::js::Keyword, &str)])
1063 if enable_minification {
1065 minifier::js::minify_and_replace_keywords(contents, keywords_to_replace))
1067 writeln!(dst, "{}", contents)
1071 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1072 /// things like ".." to components which preserve the "top down" hierarchy of a
1073 /// static HTML tree. Each component in the cleaned path will be passed as an
1074 /// argument to `f`. The very last component of the path (ie the file name) will
1075 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1076 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1077 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1078 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1081 // make it relative, if possible
1082 let p = p.strip_prefix(src_root).unwrap_or(p);
1084 let mut iter = p.components().peekable();
1086 while let Some(c) = iter.next() {
1087 if !keep_filename && iter.peek().is_none() {
1092 Component::ParentDir => f("up"),
1093 Component::Normal(c) => f(c.to_str().unwrap()),
1099 /// Attempts to find where an external crate is located, given that we're
1100 /// rendering in to the specified source destination.
1101 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1104 // See if there's documentation generated into the local directory
1105 let local_location = dst.join(&e.name);
1106 if local_location.is_dir() {
1110 if let Some(url) = extern_url {
1111 let mut url = url.to_string();
1112 if !url.ends_with("/") {
1118 // Failing that, see if there's an attribute specifying where to find this
1120 e.attrs.lists("doc")
1121 .filter(|a| a.check_name("html_root_url"))
1122 .filter_map(|a| a.value_str())
1124 let mut url = url.to_string();
1125 if !url.ends_with("/") {
1129 }).next().unwrap_or(Unknown) // Well, at least we tried.
1132 impl<'a> DocFolder for SourceCollector<'a> {
1133 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1134 // If we're including source files, and we haven't seen this file yet,
1135 // then we need to render it out to the filesystem.
1136 if self.scx.include_sources
1137 // skip all invalid or macro spans
1138 && item.source.filename.is_real()
1139 // skip non-local items
1140 && item.def_id.is_local() {
1142 // If it turns out that we couldn't read this file, then we probably
1143 // can't read any of the files (generating html output from json or
1144 // something like that), so just don't include sources for the
1145 // entire crate. The other option is maintaining this mapping on a
1146 // per-file basis, but that's probably not worth it...
1148 .include_sources = match self.emit_source(&item.source.filename) {
1151 println!("warning: source code was requested to be rendered, \
1152 but processing `{}` had an error: {}",
1153 item.source.filename, e);
1154 println!(" skipping rendering of source code");
1159 self.fold_item_recur(item)
1163 impl<'a> SourceCollector<'a> {
1164 /// Renders the given filename into its corresponding HTML source file.
1165 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1166 let p = match *filename {
1167 FileName::Real(ref file) => file,
1170 if self.scx.local_sources.contains_key(&**p) {
1171 // We've already emitted this source
1175 let contents = fs::read_to_string(&p)?;
1177 // Remove the utf-8 BOM if any
1178 let contents = if contents.starts_with("\u{feff}") {
1184 // Create the intermediate directories
1185 let mut cur = self.dst.clone();
1186 let mut root_path = String::from("../../");
1187 let mut href = String::new();
1188 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1189 cur.push(component);
1190 fs::create_dir_all(&cur).unwrap();
1191 root_path.push_str("../");
1192 href.push_str(component);
1195 let mut fname = p.file_name()
1196 .expect("source has no filename")
1198 fname.push(".html");
1200 href.push_str(&fname.to_string_lossy());
1202 let mut w = BufWriter::new(File::create(&cur)?);
1203 let title = format!("{} -- source", cur.file_name().unwrap()
1204 .to_string_lossy());
1205 let desc = format!("Source to the Rust file `{}`.", filename);
1206 let page = layout::Page {
1208 css_class: "source",
1209 root_path: &root_path,
1211 keywords: BASIC_KEYWORDS,
1212 resource_suffix: &self.scx.resource_suffix,
1214 layout::render(&mut w, &self.scx.layout,
1215 &page, &(""), &Source(contents),
1216 self.scx.css_file_extension.is_some(),
1219 self.scx.local_sources.insert(p.clone(), href);
1224 impl DocFolder for Cache {
1225 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1226 // If this is a stripped module,
1227 // we don't want it or its children in the search index.
1228 let orig_stripped_mod = match item.inner {
1229 clean::StrippedItem(box clean::ModuleItem(..)) => {
1230 mem::replace(&mut self.stripped_mod, true)
1232 _ => self.stripped_mod,
1235 // If the impl is from a masked crate or references something from a
1236 // masked crate then remove it completely.
1237 if let clean::ImplItem(ref i) = item.inner {
1238 if self.masked_crates.contains(&item.def_id.krate) ||
1239 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1240 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1245 // Register any generics to their corresponding string. This is used
1246 // when pretty-printing types.
1247 if let Some(generics) = item.inner.generics() {
1248 self.generics(generics);
1251 // Propagate a trait method's documentation to all implementors of the
1253 if let clean::TraitItem(ref t) = item.inner {
1254 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1257 // Collect all the implementors of traits.
1258 if let clean::ImplItem(ref i) = item.inner {
1259 if let Some(did) = i.trait_.def_id() {
1260 if i.blanket_impl.is_none() {
1261 self.implementors.entry(did).or_default().push(Impl {
1262 impl_item: item.clone(),
1268 // Index this method for searching later on.
1269 if let Some(ref s) = item.name {
1270 let (parent, is_inherent_impl_item) = match item.inner {
1271 clean::StrippedItem(..) => ((None, None), false),
1272 clean::AssociatedConstItem(..) |
1273 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1274 // skip associated items in trait impls
1275 ((None, None), false)
1277 clean::AssociatedTypeItem(..) |
1278 clean::TyMethodItem(..) |
1279 clean::StructFieldItem(..) |
1280 clean::VariantItem(..) => {
1281 ((Some(*self.parent_stack.last().unwrap()),
1282 Some(&self.stack[..self.stack.len() - 1])),
1285 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1286 if self.parent_stack.is_empty() {
1287 ((None, None), false)
1289 let last = self.parent_stack.last().unwrap();
1291 let path = match self.paths.get(&did) {
1292 // The current stack not necessarily has correlation
1293 // for where the type was defined. On the other
1294 // hand, `paths` always has the right
1295 // information if present.
1296 Some(&(ref fqp, ItemType::Trait)) |
1297 Some(&(ref fqp, ItemType::Struct)) |
1298 Some(&(ref fqp, ItemType::Union)) |
1299 Some(&(ref fqp, ItemType::Enum)) =>
1300 Some(&fqp[..fqp.len() - 1]),
1301 Some(..) => Some(&*self.stack),
1304 ((Some(*last), path), true)
1307 _ => ((None, Some(&*self.stack)), false)
1311 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1312 debug_assert!(!item.is_stripped());
1314 // A crate has a module at its root, containing all items,
1315 // which should not be indexed. The crate-item itself is
1316 // inserted later on when serializing the search-index.
1317 if item.def_id.index != CRATE_DEF_INDEX {
1318 self.search_index.push(IndexItem {
1320 name: s.to_string(),
1321 path: path.join("::").to_string(),
1322 desc: plain_summary_line(item.doc_value()),
1325 search_type: get_index_search_type(&item),
1329 (Some(parent), None) if is_inherent_impl_item => {
1330 // We have a parent, but we don't know where they're
1331 // defined yet. Wait for later to index this item.
1332 self.orphan_impl_items.push((parent, item.clone()));
1338 // Keep track of the fully qualified path for this item.
1339 let pushed = match item.name {
1340 Some(ref n) if !n.is_empty() => {
1341 self.stack.push(n.to_string());
1348 clean::StructItem(..) | clean::EnumItem(..) |
1349 clean::TypedefItem(..) | clean::TraitItem(..) |
1350 clean::FunctionItem(..) | clean::ModuleItem(..) |
1351 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1352 clean::ConstantItem(..) | clean::StaticItem(..) |
1353 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1354 if !self.stripped_mod => {
1355 // Re-exported items mean that the same id can show up twice
1356 // in the rustdoc ast that we're looking at. We know,
1357 // however, that a re-exported item doesn't show up in the
1358 // `public_items` map, so we can skip inserting into the
1359 // paths map if there was already an entry present and we're
1360 // not a public item.
1361 if !self.paths.contains_key(&item.def_id) ||
1362 self.access_levels.is_public(item.def_id)
1364 self.paths.insert(item.def_id,
1365 (self.stack.clone(), item.type_()));
1367 self.add_aliases(&item);
1369 // Link variants to their parent enum because pages aren't emitted
1370 // for each variant.
1371 clean::VariantItem(..) if !self.stripped_mod => {
1372 let mut stack = self.stack.clone();
1374 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1377 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1378 self.add_aliases(&item);
1379 self.paths.insert(item.def_id, (self.stack.clone(),
1386 // Maintain the parent stack
1387 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1388 let parent_pushed = match item.inner {
1389 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1390 clean::StructItem(..) | clean::UnionItem(..) => {
1391 self.parent_stack.push(item.def_id);
1392 self.parent_is_trait_impl = false;
1395 clean::ImplItem(ref i) => {
1396 self.parent_is_trait_impl = i.trait_.is_some();
1398 clean::ResolvedPath{ did, .. } => {
1399 self.parent_stack.push(did);
1403 let prim_did = t.primitive_type().and_then(|t| {
1404 self.primitive_locations.get(&t).cloned()
1408 self.parent_stack.push(did);
1419 // Once we've recursively found all the generics, hoard off all the
1420 // implementations elsewhere.
1421 let ret = self.fold_item_recur(item).and_then(|item| {
1422 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1423 // Figure out the id of this impl. This may map to a
1424 // primitive rather than always to a struct/enum.
1425 // Note: matching twice to restrict the lifetime of the `i` borrow.
1426 let mut dids = FxHashSet();
1427 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1429 clean::ResolvedPath { did, .. } |
1430 clean::BorrowedRef {
1431 type_: box clean::ResolvedPath { did, .. }, ..
1436 let did = t.primitive_type().and_then(|t| {
1437 self.primitive_locations.get(&t).cloned()
1440 if let Some(did) = did {
1446 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1447 for bound in generics {
1448 if let Some(did) = bound.def_id() {
1457 self.impls.entry(did).or_default().push(Impl {
1458 impl_item: item.clone(),
1467 if pushed { self.stack.pop().unwrap(); }
1468 if parent_pushed { self.parent_stack.pop().unwrap(); }
1469 self.stripped_mod = orig_stripped_mod;
1470 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1476 fn generics(&mut self, generics: &clean::Generics) {
1477 for param in &generics.params {
1479 clean::GenericParamDefKind::Lifetime => {}
1480 clean::GenericParamDefKind::Type { did, .. } => {
1481 self.typarams.insert(did, param.name.clone());
1487 fn add_aliases(&mut self, item: &clean::Item) {
1488 if item.def_id.index == CRATE_DEF_INDEX {
1491 if let Some(ref item_name) = item.name {
1492 let path = self.paths.get(&item.def_id)
1493 .map(|p| p.0[..p.0.len() - 1].join("::"))
1494 .unwrap_or("std".to_owned());
1495 for alias in item.attrs.lists("doc")
1496 .filter(|a| a.check_name("alias"))
1497 .filter_map(|a| a.value_str()
1498 .map(|s| s.to_string().replace("\"", "")))
1499 .filter(|v| !v.is_empty())
1500 .collect::<FxHashSet<_>>()
1502 self.aliases.entry(alias)
1503 .or_insert(Vec::with_capacity(1))
1506 name: item_name.to_string(),
1508 desc: plain_summary_line(item.doc_value()),
1511 search_type: get_index_search_type(&item),
1518 #[derive(Debug, Eq, PartialEq, Hash)]
1525 fn new(mut url: String, name: String) -> ItemEntry {
1526 while url.starts_with('/') {
1536 impl fmt::Display for ItemEntry {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1538 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1542 impl PartialOrd for ItemEntry {
1543 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1544 Some(self.cmp(other))
1548 impl Ord for ItemEntry {
1549 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1550 self.name.cmp(&other.name)
1556 structs: FxHashSet<ItemEntry>,
1557 enums: FxHashSet<ItemEntry>,
1558 unions: FxHashSet<ItemEntry>,
1559 primitives: FxHashSet<ItemEntry>,
1560 traits: FxHashSet<ItemEntry>,
1561 macros: FxHashSet<ItemEntry>,
1562 functions: FxHashSet<ItemEntry>,
1563 typedefs: FxHashSet<ItemEntry>,
1564 existentials: FxHashSet<ItemEntry>,
1565 statics: FxHashSet<ItemEntry>,
1566 constants: FxHashSet<ItemEntry>,
1567 keywords: FxHashSet<ItemEntry>,
1571 fn new() -> AllTypes {
1572 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1574 structs: new_set(100),
1575 enums: new_set(100),
1576 unions: new_set(100),
1577 primitives: new_set(26),
1578 traits: new_set(100),
1579 macros: new_set(100),
1580 functions: new_set(100),
1581 typedefs: new_set(100),
1582 existentials: new_set(100),
1583 statics: new_set(100),
1584 constants: new_set(100),
1585 keywords: new_set(100),
1589 fn append(&mut self, item_name: String, item_type: &ItemType) {
1590 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1591 if let Some(name) = url.pop() {
1592 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1594 let name = url.join("::");
1596 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1597 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1598 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1599 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1600 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1601 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1602 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1603 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1604 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1605 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1606 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1613 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1614 class: &str) -> fmt::Result {
1616 let mut e: Vec<&ItemEntry> = e.iter().collect();
1618 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1622 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1627 impl fmt::Display for AllTypes {
1628 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1631 <span class='out-of-band'>\
1632 <span id='render-detail'>\
1633 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1634 [<span class='inner'>−</span>]\
1638 <span class='in-band'>List of all items</span>\
1640 print_entries(f, &self.structs, "Structs", "structs")?;
1641 print_entries(f, &self.enums, "Enums", "enums")?;
1642 print_entries(f, &self.unions, "Unions", "unions")?;
1643 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1644 print_entries(f, &self.traits, "Traits", "traits")?;
1645 print_entries(f, &self.macros, "Macros", "macros")?;
1646 print_entries(f, &self.functions, "Functions", "functions")?;
1647 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1648 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1649 print_entries(f, &self.statics, "Statics", "statics")?;
1650 print_entries(f, &self.constants, "Constants", "constants")
1655 struct Settings<'a> {
1656 // (id, explanation, default value)
1657 settings: Vec<(&'static str, &'static str, bool)>,
1662 impl<'a> Settings<'a> {
1663 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1666 ("item-declarations", "Auto-hide item declarations.", true),
1667 ("item-attributes", "Auto-hide item attributes.", true),
1668 ("trait-implementations", "Auto-hide trait implementations documentation",
1670 ("method-docs", "Auto-hide item methods' documentation", false),
1671 ("go-to-only-result", "Directly go to item in search if there is only one result",
1680 impl<'a> fmt::Display for Settings<'a> {
1681 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1684 <span class='in-band'>Rustdoc settings</span>\
1686 <div class='settings'>{}</div>\
1687 <script src='{}settings{}.js'></script>",
1688 self.settings.iter()
1689 .map(|(id, text, enabled)| {
1690 format!("<div class='setting-line'>\
1691 <label class='toggle'>\
1692 <input type='checkbox' id='{}' {}>\
1693 <span class='slider'></span>\
1696 </div>", id, if *enabled { " checked" } else { "" }, text)
1698 .collect::<String>(),
1705 fn derive_id(&self, id: String) -> String {
1706 let mut map = self.id_map.borrow_mut();
1710 /// String representation of how to get back to the root path of the 'doc/'
1711 /// folder in terms of a relative URL.
1712 fn root_path(&self) -> String {
1713 "../".repeat(self.current.len())
1716 /// Recurse in the directory structure and change the "root path" to make
1717 /// sure it always points to the top (relatively).
1718 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1719 F: FnOnce(&mut Context) -> T,
1722 panic!("Unexpected empty destination: {:?}", self.current);
1724 let prev = self.dst.clone();
1726 self.current.push(s);
1728 info!("Recursing into {}", self.dst.display());
1732 info!("Recursed; leaving {}", self.dst.display());
1734 // Go back to where we were at
1736 self.current.pop().unwrap();
1741 /// Main method for rendering a crate.
1743 /// This currently isn't parallelized, but it'd be pretty easy to add
1744 /// parallelization to this function.
1745 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1746 let mut item = match krate.module.take() {
1748 None => return Ok(()),
1750 let final_file = self.dst.join(&krate.name)
1752 let settings_file = self.dst.join("settings.html");
1754 let crate_name = krate.name.clone();
1755 item.name = Some(krate.name);
1757 let mut all = AllTypes::new();
1760 // Render the crate documentation
1761 let mut work = vec![(self.clone(), item)];
1763 while let Some((mut cx, item)) = work.pop() {
1764 cx.item(item, &mut all, |cx, item| {
1765 work.push((cx.clone(), item))
1770 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1771 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1772 if !root_path.ends_with('/') {
1773 root_path.push('/');
1775 let mut page = layout::Page {
1776 title: "List of all items in this crate",
1779 description: "List of all items in this crate",
1780 keywords: BASIC_KEYWORDS,
1781 resource_suffix: &self.shared.resource_suffix,
1783 let sidebar = if let Some(ref version) = cache().crate_version {
1784 format!("<p class='location'>Crate {}</p>\
1785 <div class='block version'>\
1788 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1789 crate_name, version)
1793 try_err!(layout::render(&mut w, &self.shared.layout,
1794 &page, &sidebar, &all,
1795 self.shared.css_file_extension.is_some(),
1796 &self.shared.themes),
1799 // Generating settings page.
1800 let settings = Settings::new("./", &self.shared.resource_suffix);
1801 page.title = "Rustdoc settings";
1802 page.description = "Settings of Rustdoc";
1803 page.root_path = "./";
1805 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1806 let mut themes = self.shared.themes.clone();
1807 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1808 themes.push(PathBuf::from("settings.css"));
1809 let mut layout = self.shared.layout.clone();
1810 layout.krate = String::new();
1811 layout.logo = String::new();
1812 layout.favicon = String::new();
1813 try_err!(layout::render(&mut w, &layout,
1814 &page, &sidebar, &settings,
1815 self.shared.css_file_extension.is_some(),
1822 fn render_item(&self,
1823 writer: &mut dyn io::Write,
1827 // A little unfortunate that this is done like this, but it sure
1828 // does make formatting *a lot* nicer.
1829 CURRENT_LOCATION_KEY.with(|slot| {
1830 *slot.borrow_mut() = self.current.clone();
1833 let mut title = if it.is_primitive() {
1834 // No need to include the namespace for primitive types
1837 self.current.join("::")
1840 if !title.is_empty() {
1841 title.push_str("::");
1843 title.push_str(it.name.as_ref().unwrap());
1845 title.push_str(" - Rust");
1846 let tyname = it.type_().css_class();
1847 let desc = if it.is_crate() {
1848 format!("API documentation for the Rust `{}` crate.",
1849 self.shared.layout.krate)
1851 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1852 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1854 let keywords = make_item_keywords(it);
1855 let page = layout::Page {
1857 root_path: &self.root_path(),
1860 keywords: &keywords,
1861 resource_suffix: &self.shared.resource_suffix,
1865 self.id_map.borrow_mut().reset();
1866 self.id_map.borrow_mut().populate(initial_ids());
1869 if !self.render_redirect_pages {
1870 layout::render(writer, &self.shared.layout, &page,
1871 &Sidebar{ cx: self, item: it },
1872 &Item{ cx: self, item: it },
1873 self.shared.css_file_extension.is_some(),
1874 &self.shared.themes)?;
1876 let mut url = self.root_path();
1877 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1878 for name in &names[..names.len() - 1] {
1882 url.push_str(&item_path(ty, names.last().unwrap()));
1883 layout::redirect(writer, &url)?;
1889 /// Non-parallelized version of rendering an item. This will take the input
1890 /// item, render its contents, and then invoke the specified closure with
1891 /// all sub-items which need to be rendered.
1893 /// The rendering driver uses this closure to queue up more work.
1894 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1895 where F: FnMut(&mut Context, clean::Item),
1897 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1898 // if they contain impls for public types. These modules can also
1899 // contain items such as publicly re-exported structures.
1901 // External crates will provide links to these structures, so
1902 // these modules are recursed into, but not rendered normally
1903 // (a flag on the context).
1904 if !self.render_redirect_pages {
1905 self.render_redirect_pages = item.is_stripped();
1909 // modules are special because they add a namespace. We also need to
1910 // recurse into the items of the module as well.
1911 let name = item.name.as_ref().unwrap().to_string();
1912 let mut item = Some(item);
1913 self.recurse(name, |this| {
1914 let item = item.take().unwrap();
1916 let mut buf = Vec::new();
1917 this.render_item(&mut buf, &item, false).unwrap();
1918 // buf will be empty if the module is stripped and there is no redirect for it
1919 if !buf.is_empty() {
1920 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1921 let joint_dst = this.dst.join("index.html");
1922 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1923 try_err!(dst.write_all(&buf), &joint_dst);
1926 let m = match item.inner {
1927 clean::StrippedItem(box clean::ModuleItem(m)) |
1928 clean::ModuleItem(m) => m,
1932 // Render sidebar-items.js used throughout this module.
1933 if !this.render_redirect_pages {
1934 let items = this.build_sidebar_items(&m);
1935 let js_dst = this.dst.join("sidebar-items.js");
1936 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1937 try_err!(write!(&mut js_out, "initSidebarItems({});",
1938 as_json(&items)), &js_dst);
1941 for item in m.items {
1947 } else if item.name.is_some() {
1948 let mut buf = Vec::new();
1949 self.render_item(&mut buf, &item, true).unwrap();
1950 // buf will be empty if the item is stripped and there is no redirect for it
1951 if !buf.is_empty() {
1952 let name = item.name.as_ref().unwrap();
1953 let item_type = item.type_();
1954 let file_name = &item_path(item_type, name);
1955 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1956 let joint_dst = self.dst.join(file_name);
1957 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1958 try_err!(dst.write_all(&buf), &joint_dst);
1960 if !self.render_redirect_pages {
1961 all.append(full_path(self, &item), &item_type);
1963 // Redirect from a sane URL using the namespace to Rustdoc's
1964 // URL for the page.
1965 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1966 let redir_dst = self.dst.join(redir_name);
1967 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1970 let mut redirect_out = BufWriter::new(redirect_out);
1971 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1974 // If the item is a macro, redirect from the old macro URL (with !)
1975 // to the new one (without).
1976 if item_type == ItemType::Macro {
1977 let redir_name = format!("{}.{}!.html", item_type, name);
1978 let redir_dst = self.dst.join(redir_name);
1979 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1980 let mut redirect_out = BufWriter::new(redirect_out);
1981 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1988 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1989 // BTreeMap instead of HashMap to get a sorted output
1990 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1991 for item in &m.items {
1992 if item.is_stripped() { continue }
1994 let short = item.type_().css_class();
1995 let myname = match item.name {
1997 Some(ref s) => s.to_string(),
1999 let short = short.to_string();
2000 map.entry(short).or_default()
2001 .push((myname, Some(plain_summary_line(item.doc_value()))));
2004 if self.shared.sort_modules_alphabetically {
2005 for (_, items) in &mut map {
2014 /// Generate a url appropriate for an `href` attribute back to the source of
2017 /// The url generated, when clicked, will redirect the browser back to the
2018 /// original source code.
2020 /// If `None` is returned, then a source link couldn't be generated. This
2021 /// may happen, for example, with externally inlined items where the source
2022 /// of their crate documentation isn't known.
2023 fn src_href(&self) -> Option<String> {
2024 let mut root = self.cx.root_path();
2026 let cache = cache();
2027 let mut path = String::new();
2029 // We can safely ignore macros from other libraries
2030 let file = match self.item.source.filename {
2031 FileName::Real(ref path) => path,
2035 let (krate, path) = if self.item.def_id.is_local() {
2036 if let Some(path) = self.cx.shared.local_sources.get(file) {
2037 (&self.cx.shared.layout.krate, path)
2042 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
2043 Some(&(ref name, ref src, Local)) => (name, src),
2044 Some(&(ref name, ref src, Remote(ref s))) => {
2045 root = s.to_string();
2048 Some(&(_, _, Unknown)) | None => return None,
2051 clean_srcpath(&src_root, file, false, |component| {
2052 path.push_str(component);
2055 let mut fname = file.file_name().expect("source has no filename")
2057 fname.push(".html");
2058 path.push_str(&fname.to_string_lossy());
2062 let lines = if self.item.source.loline == self.item.source.hiline {
2063 self.item.source.loline.to_string()
2065 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2067 Some(format!("{root}src/{krate}/{path}#{lines}",
2068 root = Escape(&root),
2075 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2076 f: F) -> fmt::Result
2077 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2078 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2083 impl<'a> fmt::Display for Item<'a> {
2084 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2085 debug_assert!(!self.item.is_stripped());
2086 // Write the breadcrumb trail header for the top
2087 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2088 if let Some(version) = self.item.stable_since() {
2089 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2093 "<span id='render-detail'>\
2094 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2095 title=\"collapse all docs\">\
2096 [<span class='inner'>−</span>]\
2102 // When this item is part of a `pub use` in a downstream crate, the
2103 // [src] link in the downstream documentation will actually come back to
2104 // this page, and this link will be auto-clicked. The `id` attribute is
2105 // used to find the link to auto-click.
2106 if self.cx.shared.include_sources && !self.item.is_primitive() {
2107 if let Some(l) = self.src_href() {
2108 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2109 l, "goto source code")?;
2113 write!(fmt, "</span>")?; // out-of-band
2114 write!(fmt, "<span class='in-band'>")?;
2115 match self.item.inner {
2116 clean::ModuleItem(ref m) => if m.is_crate {
2117 write!(fmt, "Crate ")?;
2119 write!(fmt, "Module ")?;
2121 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2122 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2123 clean::StructItem(..) => write!(fmt, "Struct ")?,
2124 clean::UnionItem(..) => write!(fmt, "Union ")?,
2125 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2126 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2127 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2128 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2129 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2130 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2131 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2132 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2133 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2135 // We don't generate pages for any other type.
2139 if !self.item.is_primitive() && !self.item.is_keyword() {
2140 let cur = &self.cx.current;
2141 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2142 for (i, component) in cur.iter().enumerate().take(amt) {
2143 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2144 "../".repeat(cur.len() - i - 1),
2148 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2149 self.item.type_(), self.item.name.as_ref().unwrap())?;
2151 write!(fmt, "</span></h1>")?; // in-band
2153 match self.item.inner {
2154 clean::ModuleItem(ref m) =>
2155 item_module(fmt, self.cx, self.item, &m.items),
2156 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2157 item_function(fmt, self.cx, self.item, f),
2158 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2159 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2160 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2161 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2162 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2163 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2164 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2165 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2166 item_static(fmt, self.cx, self.item, i),
2167 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2168 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2169 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2170 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2172 // We don't generate pages for any other type.
2179 fn item_path(ty: ItemType, name: &str) -> String {
2181 ItemType::Module => format!("{}/index.html", name),
2182 _ => format!("{}.{}.html", ty.css_class(), name),
2186 fn full_path(cx: &Context, item: &clean::Item) -> String {
2187 let mut s = cx.current.join("::");
2189 s.push_str(item.name.as_ref().unwrap());
2193 fn shorter<'a>(s: Option<&'a str>) -> String {
2195 Some(s) => s.lines()
2196 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2198 (*line).chars().any(|chr|{
2199 !chr.is_whitespace()
2201 }).collect::<Vec<_>>().join("\n"),
2202 None => String::new()
2207 fn plain_summary_line(s: Option<&str>) -> String {
2208 let line = shorter(s).replace("\n", " ");
2209 markdown::plain_summary_line(&line[..])
2212 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2213 if let Some(ref name) = item.name {
2214 info!("Documenting {}", name);
2216 document_stability(w, cx, item)?;
2217 document_full(w, item, cx, "")?;
2221 /// Render md_text as markdown.
2222 fn render_markdown(w: &mut fmt::Formatter,
2225 links: Vec<(String, String)>,
2228 let mut ids = cx.id_map.borrow_mut();
2229 write!(w, "<div class='docblock'>{}{}</div>",
2230 prefix, Markdown(md_text, &links, RefCell::new(&mut ids), cx.codes))
2233 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2234 prefix: &str) -> fmt::Result {
2235 if let Some(s) = item.doc_value() {
2236 let markdown = if s.contains('\n') {
2237 format!("{} [Read more]({})",
2238 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2240 plain_summary_line(Some(s)).to_string()
2242 render_markdown(w, cx, &markdown, item.links(), prefix)?;
2243 } else if !prefix.is_empty() {
2244 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2249 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2250 cx: &Context, prefix: &str) -> fmt::Result {
2251 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2252 debug!("Doc block: =====\n{}\n=====", s);
2253 render_markdown(w, cx, &*s, item.links(), prefix)?;
2254 } else if !prefix.is_empty() {
2255 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2260 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2261 let stabilities = short_stability(item, cx, true);
2262 if !stabilities.is_empty() {
2263 write!(w, "<div class='stability'>")?;
2264 for stability in stabilities {
2265 write!(w, "{}", stability)?;
2267 write!(w, "</div>")?;
2272 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2273 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2276 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2277 if item.is_non_exhaustive() {
2278 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2279 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2282 if item.is_struct() {
2283 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2284 Therefore, non-exhaustive structs cannot be constructed in external crates \
2285 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2286 matched against without a wildcard <code>..</code>; and \
2287 struct update syntax will not work.")?;
2288 } else if item.is_enum() {
2289 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2290 Therefore, when matching against variants of non-exhaustive enums, an \
2291 extra wildcard arm must be added to account for any future variants.")?;
2293 write!(w, "This type will require a wildcard arm in any match statements or \
2297 write!(w, "</div>")?;
2303 fn name_key(name: &str) -> (&str, u64, usize) {
2304 // find number at end
2305 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2307 // count leading zeroes
2309 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2311 // sort leading zeroes last
2312 let num_zeroes = after_zeroes - split;
2314 match name[split..].parse() {
2315 Ok(n) => (&name[..split], n, num_zeroes),
2316 Err(_) => (name, 0, num_zeroes),
2320 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2321 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2322 document(w, cx, item)?;
2324 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2326 // the order of item types in the listing
2327 fn reorder(ty: ItemType) -> u8 {
2329 ItemType::ExternCrate => 0,
2330 ItemType::Import => 1,
2331 ItemType::Primitive => 2,
2332 ItemType::Module => 3,
2333 ItemType::Macro => 4,
2334 ItemType::Struct => 5,
2335 ItemType::Enum => 6,
2336 ItemType::Constant => 7,
2337 ItemType::Static => 8,
2338 ItemType::Trait => 9,
2339 ItemType::Function => 10,
2340 ItemType::Typedef => 12,
2341 ItemType::Union => 13,
2346 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2347 let ty1 = i1.type_();
2348 let ty2 = i2.type_();
2350 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2352 let s1 = i1.stability.as_ref().map(|s| s.level);
2353 let s2 = i2.stability.as_ref().map(|s| s.level);
2355 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2356 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2359 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2360 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2361 name_key(lhs).cmp(&name_key(rhs))
2364 if cx.shared.sort_modules_alphabetically {
2365 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2367 // This call is to remove re-export duplicates in cases such as:
2372 // pub trait Double { fn foo(); }
2376 // pub use foo::bar::*;
2380 // `Double` will appear twice in the generated docs.
2382 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2383 // can be identical even if the elements are different (mostly in imports).
2384 // So in case this is an import, we keep everything by adding a "unique id"
2385 // (which is the position in the vector).
2386 indices.dedup_by_key(|i| (items[*i].def_id,
2387 if items[*i].name.as_ref().is_some() {
2388 Some(full_path(cx, &items[*i]).clone())
2393 if items[*i].is_import() {
2399 debug!("{:?}", indices);
2400 let mut curty = None;
2401 for &idx in &indices {
2402 let myitem = &items[idx];
2403 if myitem.is_stripped() {
2407 let myty = Some(myitem.type_());
2408 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2409 // Put `extern crate` and `use` re-exports in the same section.
2411 } else if myty != curty {
2412 if curty.is_some() {
2413 write!(w, "</table>")?;
2416 let (short, name) = item_ty_to_strs(&myty.unwrap());
2417 write!(w, "<h2 id='{id}' class='section-header'>\
2418 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2419 id = cx.derive_id(short.to_owned()), name = name)?;
2422 match myitem.inner {
2423 clean::ExternCrateItem(ref name, ref src) => {
2424 use html::format::HRef;
2428 write!(w, "<tr><td><code>{}extern crate {} as {};",
2429 VisSpace(&myitem.visibility),
2430 HRef::new(myitem.def_id, src),
2434 write!(w, "<tr><td><code>{}extern crate {};",
2435 VisSpace(&myitem.visibility),
2436 HRef::new(myitem.def_id, name))?
2439 write!(w, "</code></td></tr>")?;
2442 clean::ImportItem(ref import) => {
2443 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2444 VisSpace(&myitem.visibility), *import)?;
2448 if myitem.name.is_none() { continue }
2450 let stabilities = short_stability(myitem, cx, false);
2452 let stab_docs = if !stabilities.is_empty() {
2454 .map(|s| format!("[{}]", s))
2455 .collect::<Vec<_>>()
2462 let unsafety_flag = match myitem.inner {
2463 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2464 if func.header.unsafety == hir::Unsafety::Unsafe => {
2465 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2470 let doc_value = myitem.doc_value().unwrap_or("");
2472 <tr class='{stab} module-item'>
2473 <td><a class=\"{class}\" href=\"{href}\"
2474 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2475 <td class='docblock-short'>
2479 name = *myitem.name.as_ref().unwrap(),
2480 stab_docs = stab_docs,
2481 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2482 class = myitem.type_(),
2483 stab = myitem.stability_class().unwrap_or(String::new()),
2484 unsafety_flag = unsafety_flag,
2485 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2486 title_type = myitem.type_(),
2487 title = full_path(cx, myitem))?;
2492 if curty.is_some() {
2493 write!(w, "</table>")?;
2498 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2499 let mut stability = vec![];
2500 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2502 if let Some(stab) = item.stability.as_ref() {
2503 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2504 format!(": {}", stab.deprecated_reason)
2508 if !stab.deprecated_since.is_empty() {
2509 let since = if show_reason {
2510 format!(" since {}", Escape(&stab.deprecated_since))
2514 let mut ids = cx.id_map.borrow_mut();
2515 let html = MarkdownHtml(&deprecated_reason, RefCell::new(&mut ids), error_codes);
2516 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2517 format!("Deprecated{}{}", since, html)
2519 format!("Deprecating in {}{}", Escape(&stab.deprecated_since), html)
2521 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2524 if stab.level == stability::Unstable {
2526 let unstable_extra = match (!stab.feature.is_empty(),
2527 &cx.shared.issue_tracker_base_url,
2529 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2530 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2531 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2532 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2533 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2536 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2539 if stab.unstable_reason.is_empty() {
2540 stability.push(format!("<div class='stab unstable'>\
2541 <span class=microscope>🔬</span> \
2542 This is a nightly-only experimental API. {}\
2546 let mut ids = cx.id_map.borrow_mut();
2547 let text = format!("<summary><span class=microscope>🔬</span> \
2548 This is a nightly-only experimental API. {}\
2552 &stab.unstable_reason,
2553 RefCell::new(&mut ids),
2555 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2559 stability.push("<div class='stab unstable'>Experimental</div>".to_string())
2562 } else if let Some(depr) = item.deprecation.as_ref() {
2563 let note = if show_reason && !depr.note.is_empty() {
2564 format!(": {}", depr.note)
2568 let since = if show_reason && !depr.since.is_empty() {
2569 format!(" since {}", Escape(&depr.since))
2574 let mut ids = cx.id_map.borrow_mut();
2575 let text = if stability::deprecation_in_effect(&depr.since) {
2576 format!("Deprecated{}{}",
2578 MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes))
2580 format!("Deprecating in {}{}",
2581 Escape(&depr.since),
2582 MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes))
2584 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2587 if let Some(ref cfg) = item.attrs.cfg {
2588 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2589 cfg.render_long_html()
2591 cfg.render_short_html()
2598 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2599 c: &clean::Constant) -> fmt::Result {
2600 write!(w, "<pre class='rust const'>")?;
2601 render_attributes(w, it)?;
2602 write!(w, "{vis}const \
2603 {name}: {typ}</pre>",
2604 vis = VisSpace(&it.visibility),
2605 name = it.name.as_ref().unwrap(),
2610 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2611 s: &clean::Static) -> fmt::Result {
2612 write!(w, "<pre class='rust static'>")?;
2613 render_attributes(w, it)?;
2614 write!(w, "{vis}static {mutability}\
2615 {name}: {typ}</pre>",
2616 vis = VisSpace(&it.visibility),
2617 mutability = MutableSpace(s.mutability),
2618 name = it.name.as_ref().unwrap(),
2623 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2624 f: &clean::Function) -> fmt::Result {
2625 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2626 VisSpace(&it.visibility),
2627 ConstnessSpace(f.header.constness),
2628 UnsafetySpace(f.header.unsafety),
2629 AsyncSpace(f.header.asyncness),
2630 AbiSpace(f.header.abi),
2631 it.name.as_ref().unwrap(),
2633 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2634 render_attributes(w, it)?;
2636 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2637 {name}{generics}{decl}{where_clause}</pre>",
2638 vis = VisSpace(&it.visibility),
2639 constness = ConstnessSpace(f.header.constness),
2640 unsafety = UnsafetySpace(f.header.unsafety),
2641 asyncness = AsyncSpace(f.header.asyncness),
2642 abi = AbiSpace(f.header.abi),
2643 name = it.name.as_ref().unwrap(),
2644 generics = f.generics,
2645 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2654 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2655 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2656 // If there's already another implementor that has the same abbridged name, use the
2657 // full path, for example in `std::iter::ExactSizeIterator`
2658 let use_absolute = match implementor.inner_impl().for_ {
2659 clean::ResolvedPath { ref path, is_generic: false, .. } |
2660 clean::BorrowedRef {
2661 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2663 } => implementor_dups[path.last_name()].1,
2666 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2667 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
2671 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2673 containing_item: &clean::Item) -> fmt::Result {
2675 let did = i.trait_did().unwrap();
2676 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2677 render_impl(w, cx, i, assoc_link,
2678 RenderMode::Normal, containing_item.stable_since(), true, None)?;
2683 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
2684 let mut bounds = String::new();
2685 let mut bounds_plain = String::new();
2686 if !t_bounds.is_empty() {
2687 if !bounds.is_empty() {
2689 bounds_plain.push(' ');
2691 bounds.push_str(": ");
2692 bounds_plain.push_str(": ");
2693 for (i, p) in t_bounds.iter().enumerate() {
2695 bounds.push_str(" + ");
2696 bounds_plain.push_str(" + ");
2698 bounds.push_str(&(*p).to_string());
2699 bounds_plain.push_str(&format!("{:#}", *p));
2706 w: &mut fmt::Formatter,
2711 let bounds = bounds(&t.bounds);
2712 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2713 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2714 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2715 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2717 // Output the trait definition
2718 wrap_into_docblock(w, |w| {
2719 write!(w, "<pre class='rust trait'>")?;
2720 render_attributes(w, it)?;
2721 write!(w, "{}{}{}trait {}{}{}",
2722 VisSpace(&it.visibility),
2723 UnsafetySpace(t.unsafety),
2724 if t.is_auto { "auto " } else { "" },
2725 it.name.as_ref().unwrap(),
2729 if !t.generics.where_predicates.is_empty() {
2730 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2735 if t.items.is_empty() {
2736 write!(w, "{{ }}")?;
2738 // FIXME: we should be using a derived_id for the Anchors here
2742 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2745 if !types.is_empty() && !consts.is_empty() {
2750 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2753 if !consts.is_empty() && !required.is_empty() {
2756 for (pos, m) in required.iter().enumerate() {
2758 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2761 if pos < required.len() - 1 {
2762 write!(w, "<div class='item-spacer'></div>")?;
2765 if !required.is_empty() && !provided.is_empty() {
2768 for (pos, m) in provided.iter().enumerate() {
2770 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2772 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2773 write!(w, ",\n {{ ... }}\n")?;
2776 write!(w, " {{ ... }}\n")?;
2779 if pos < provided.len() - 1 {
2780 write!(w, "<div class='item-spacer'></div>")?;
2788 // Trait documentation
2789 document(w, cx, it)?;
2791 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2793 let name = m.name.as_ref().unwrap();
2794 let item_type = m.type_();
2795 let id = cx.derive_id(format!("{}.{}", item_type, name));
2796 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
2797 write!(w, "{extra}<h3 id='{id}' class='method'>\
2798 <span id='{ns_id}' class='invisible'><code>",
2799 extra = render_spotlight_traits(m)?,
2802 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2803 write!(w, "</code>")?;
2804 render_stability_since(w, m, t)?;
2805 write!(w, "</span></h3>")?;
2806 document(w, cx, m)?;
2810 if !types.is_empty() {
2812 <h2 id='associated-types' class='small-section-header'>
2813 Associated Types<a href='#associated-types' class='anchor'></a>
2815 <div class='methods'>
2818 trait_item(w, cx, *t, it)?;
2820 write!(w, "</div>")?;
2823 if !consts.is_empty() {
2825 <h2 id='associated-const' class='small-section-header'>
2826 Associated Constants<a href='#associated-const' class='anchor'></a>
2828 <div class='methods'>
2831 trait_item(w, cx, *t, it)?;
2833 write!(w, "</div>")?;
2836 // Output the documentation for each function individually
2837 if !required.is_empty() {
2839 <h2 id='required-methods' class='small-section-header'>
2840 Required Methods<a href='#required-methods' class='anchor'></a>
2842 <div class='methods'>
2844 for m in &required {
2845 trait_item(w, cx, *m, it)?;
2847 write!(w, "</div>")?;
2849 if !provided.is_empty() {
2851 <h2 id='provided-methods' class='small-section-header'>
2852 Provided Methods<a href='#provided-methods' class='anchor'></a>
2854 <div class='methods'>
2856 for m in &provided {
2857 trait_item(w, cx, *m, it)?;
2859 write!(w, "</div>")?;
2862 // If there are methods directly on this trait object, render them here.
2863 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2865 let cache = cache();
2866 let impl_header = "\
2867 <h2 id='implementors' class='small-section-header'>\
2868 Implementors<a href='#implementors' class='anchor'></a>\
2870 <div class='item-list' id='implementors-list'>\
2873 let synthetic_impl_header = "\
2874 <h2 id='synthetic-implementors' class='small-section-header'>\
2875 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>\
2877 <div class='item-list' id='synthetic-implementors-list'>\
2880 let mut synthetic_types = Vec::new();
2882 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2883 // The DefId is for the first Type found with that name. The bool is
2884 // if any Types with the same name but different DefId have been found.
2885 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2886 for implementor in implementors {
2887 match implementor.inner_impl().for_ {
2888 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2889 clean::BorrowedRef {
2890 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2893 let &mut (prev_did, ref mut has_duplicates) =
2894 implementor_dups.entry(path.last_name()).or_insert((did, false));
2895 if prev_did != did {
2896 *has_duplicates = true;
2903 let (local, foreign) = implementors.iter()
2904 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2905 .map_or(true, |d| cache.paths.contains_key(&d)));
2908 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
2909 .partition(|i| i.inner_impl().synthetic);
2911 if !foreign.is_empty() {
2913 <h2 id='foreign-impls' class='small-section-header'>
2914 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2918 for implementor in foreign {
2919 let assoc_link = AssocItemLink::GotoSource(
2920 implementor.impl_item.def_id,
2921 &implementor.inner_impl().provided_trait_methods
2923 render_impl(w, cx, &implementor, assoc_link,
2924 RenderMode::Normal, implementor.impl_item.stable_since(), false,
2929 write!(w, "{}", impl_header)?;
2930 for implementor in concrete {
2931 render_implementor(cx, implementor, w, &implementor_dups)?;
2933 write!(w, "</div>")?;
2936 write!(w, "{}", synthetic_impl_header)?;
2937 for implementor in synthetic {
2938 synthetic_types.extend(
2939 collect_paths_for_type(implementor.inner_impl().for_.clone())
2941 render_implementor(cx, implementor, w, &implementor_dups)?;
2943 write!(w, "</div>")?;
2946 // even without any implementations to write in, we still want the heading and list, so the
2947 // implementors javascript file pulled in below has somewhere to write the impls into
2948 write!(w, "{}", impl_header)?;
2949 write!(w, "</div>")?;
2952 write!(w, "{}", synthetic_impl_header)?;
2953 write!(w, "</div>")?;
2956 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2957 as_json(&synthetic_types))?;
2959 write!(w, r#"<script type="text/javascript" async
2960 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2962 root_path = vec![".."; cx.current.len()].join("/"),
2963 path = if it.def_id.is_local() {
2964 cx.current.join("/")
2966 let (ref path, _) = cache.external_paths[&it.def_id];
2967 path[..path.len() - 1].join("/")
2969 ty = it.type_().css_class(),
2970 name = *it.name.as_ref().unwrap())?;
2974 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2975 use html::item_type::ItemType::*;
2977 let name = it.name.as_ref().unwrap();
2978 let ty = match it.type_() {
2979 Typedef | AssociatedType => AssociatedType,
2983 let anchor = format!("#{}.{}", ty, name);
2985 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2986 AssocItemLink::Anchor(None) => anchor,
2987 AssocItemLink::GotoSource(did, _) => {
2988 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2993 fn assoc_const(w: &mut fmt::Formatter,
2996 _default: Option<&String>,
2997 link: AssocItemLink) -> fmt::Result {
2998 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2999 VisSpace(&it.visibility),
3000 naive_assoc_href(it, link),
3001 it.name.as_ref().unwrap(),
3006 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3007 bounds: &[clean::GenericBound],
3008 default: Option<&clean::Type>,
3009 link: AssocItemLink) -> fmt::Result {
3010 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3011 naive_assoc_href(it, link),
3012 it.name.as_ref().unwrap())?;
3013 if !bounds.is_empty() {
3014 write!(w, ": {}", GenericBounds(bounds))?
3016 if let Some(default) = default {
3017 write!(w, " = {}", default)?;
3022 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
3023 ver: Option<&'a str>,
3024 containing_ver: Option<&'a str>) -> fmt::Result {
3025 if let Some(v) = ver {
3026 if containing_ver != ver && v.len() > 0 {
3027 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
3034 fn render_stability_since(w: &mut fmt::Formatter,
3036 containing_item: &clean::Item) -> fmt::Result {
3037 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3040 fn render_assoc_item(w: &mut fmt::Formatter,
3042 link: AssocItemLink,
3043 parent: ItemType) -> fmt::Result {
3044 fn method(w: &mut fmt::Formatter,
3046 header: hir::FnHeader,
3047 g: &clean::Generics,
3049 link: AssocItemLink,
3052 let name = meth.name.as_ref().unwrap();
3053 let anchor = format!("#{}.{}", meth.type_(), name);
3054 let href = match link {
3055 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3056 AssocItemLink::Anchor(None) => anchor,
3057 AssocItemLink::GotoSource(did, provided_methods) => {
3058 // We're creating a link from an impl-item to the corresponding
3059 // trait-item and need to map the anchored type accordingly.
3060 let ty = if provided_methods.contains(name) {
3066 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3069 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3070 VisSpace(&meth.visibility),
3071 ConstnessSpace(header.constness),
3072 UnsafetySpace(header.unsafety),
3073 AsyncSpace(header.asyncness),
3074 AbiSpace(header.abi),
3077 let (indent, end_newline) = if parent == ItemType::Trait {
3083 render_attributes(w, meth)?;
3084 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3085 {generics}{decl}{where_clause}",
3086 VisSpace(&meth.visibility),
3087 ConstnessSpace(header.constness),
3088 UnsafetySpace(header.unsafety),
3089 AsyncSpace(header.asyncness),
3090 AbiSpace(header.abi),
3099 where_clause = WhereClause {
3106 clean::StrippedItem(..) => Ok(()),
3107 clean::TyMethodItem(ref m) => {
3108 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3110 clean::MethodItem(ref m) => {
3111 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3113 clean::AssociatedConstItem(ref ty, ref default) => {
3114 assoc_const(w, item, ty, default.as_ref(), link)
3116 clean::AssociatedTypeItem(ref bounds, ref default) => {
3117 assoc_type(w, item, bounds, default.as_ref(), link)
3119 _ => panic!("render_assoc_item called on non-associated-item")
3123 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3124 s: &clean::Struct) -> fmt::Result {
3125 wrap_into_docblock(w, |w| {
3126 write!(w, "<pre class='rust struct'>")?;
3127 render_attributes(w, it)?;
3138 document(w, cx, it)?;
3139 let mut fields = s.fields.iter().filter_map(|f| {
3141 clean::StructFieldItem(ref ty) => Some((f, ty)),
3145 if let doctree::Plain = s.struct_type {
3146 if fields.peek().is_some() {
3147 write!(w, "<h2 id='fields' class='fields small-section-header'>
3148 Fields{}<a href='#fields' class='anchor'></a></h2>",
3149 document_non_exhaustive_header(it))?;
3150 document_non_exhaustive(w, it)?;
3151 for (field, ty) in fields {
3152 let id = cx.derive_id(format!("{}.{}",
3153 ItemType::StructField,
3154 field.name.as_ref().unwrap()));
3155 let ns_id = cx.derive_id(format!("{}.{}",
3156 field.name.as_ref().unwrap(),
3157 ItemType::StructField.name_space()));
3158 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3159 <a href=\"#{id}\" class=\"anchor field\"></a>
3160 <span id=\"{ns_id}\" class='invisible'>
3161 <code>{name}: {ty}</code>
3163 item_type = ItemType::StructField,
3166 name = field.name.as_ref().unwrap(),
3168 if let Some(stability_class) = field.stability_class() {
3169 write!(w, "<span class='stab {stab}'></span>",
3170 stab = stability_class)?;
3172 document(w, cx, field)?;
3176 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3179 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3180 s: &clean::Union) -> fmt::Result {
3181 wrap_into_docblock(w, |w| {
3182 write!(w, "<pre class='rust union'>")?;
3183 render_attributes(w, it)?;
3193 document(w, cx, it)?;
3194 let mut fields = s.fields.iter().filter_map(|f| {
3196 clean::StructFieldItem(ref ty) => Some((f, ty)),
3200 if fields.peek().is_some() {
3201 write!(w, "<h2 id='fields' class='fields small-section-header'>
3202 Fields<a href='#fields' class='anchor'></a></h2>")?;
3203 for (field, ty) in fields {
3204 let name = field.name.as_ref().expect("union field name");
3205 let id = format!("{}.{}", ItemType::StructField, name);
3206 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3207 <a href=\"#{id}\" class=\"anchor field\"></a>\
3208 <span class='invisible'><code>{name}: {ty}</code></span>\
3212 shortty = ItemType::StructField,
3214 if let Some(stability_class) = field.stability_class() {
3215 write!(w, "<span class='stab {stab}'></span>",
3216 stab = stability_class)?;
3218 document(w, cx, field)?;
3221 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3224 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3225 e: &clean::Enum) -> fmt::Result {
3226 wrap_into_docblock(w, |w| {
3227 write!(w, "<pre class='rust enum'>")?;
3228 render_attributes(w, it)?;
3229 write!(w, "{}enum {}{}{}",
3230 VisSpace(&it.visibility),
3231 it.name.as_ref().unwrap(),
3233 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3234 if e.variants.is_empty() && !e.variants_stripped {
3235 write!(w, " {{}}")?;
3237 write!(w, " {{\n")?;
3238 for v in &e.variants {
3240 let name = v.name.as_ref().unwrap();
3242 clean::VariantItem(ref var) => {
3244 clean::VariantKind::CLike => write!(w, "{}", name)?,
3245 clean::VariantKind::Tuple(ref tys) => {
3246 write!(w, "{}(", name)?;
3247 for (i, ty) in tys.iter().enumerate() {
3249 write!(w, ", ")?
3251 write!(w, "{}", *ty)?;
3255 clean::VariantKind::Struct(ref s) => {
3271 if e.variants_stripped {
3272 write!(w, " // some variants omitted\n")?;
3279 document(w, cx, it)?;
3280 if !e.variants.is_empty() {
3281 write!(w, "<h2 id='variants' class='variants small-section-header'>
3282 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3283 document_non_exhaustive_header(it))?;
3284 document_non_exhaustive(w, it)?;
3285 for variant in &e.variants {
3286 let id = cx.derive_id(format!("{}.{}",
3288 variant.name.as_ref().unwrap()));
3289 let ns_id = cx.derive_id(format!("{}.{}",
3290 variant.name.as_ref().unwrap(),
3291 ItemType::Variant.name_space()));
3292 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3293 <a href=\"#{id}\" class=\"anchor field\"></a>\
3294 <span id='{ns_id}' class='invisible'><code>{name}",
3297 name = variant.name.as_ref().unwrap())?;
3298 if let clean::VariantItem(ref var) = variant.inner {
3299 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3301 for (i, ty) in tys.iter().enumerate() {
3303 write!(w, ", ")?;
3305 write!(w, "{}", *ty)?;
3310 write!(w, "</code></span></span>")?;
3311 document(w, cx, variant)?;
3313 use clean::{Variant, VariantKind};
3314 if let clean::VariantItem(Variant {
3315 kind: VariantKind::Struct(ref s)
3316 }) = variant.inner {
3317 let variant_id = cx.derive_id(format!("{}.{}.fields",
3319 variant.name.as_ref().unwrap()));
3320 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3322 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3323 <table>", name = variant.name.as_ref().unwrap())?;
3324 for field in &s.fields {
3325 use clean::StructFieldItem;
3326 if let StructFieldItem(ref ty) = field.inner {
3327 let id = cx.derive_id(format!("variant.{}.field.{}",
3328 variant.name.as_ref().unwrap(),
3329 field.name.as_ref().unwrap()));
3330 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3331 variant.name.as_ref().unwrap(),
3332 ItemType::Variant.name_space(),
3333 field.name.as_ref().unwrap(),
3334 ItemType::StructField.name_space()));
3335 write!(w, "<tr><td \
3337 <span id='{ns_id}' class='invisible'>\
3338 <code>{f}: {t}</code></span></td><td>",
3341 f = field.name.as_ref().unwrap(),
3343 document(w, cx, field)?;
3344 write!(w, "</td></tr>")?;
3347 write!(w, "</table></span>")?;
3349 render_stability_since(w, variant, it)?;
3352 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3356 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3357 let name = attr.name();
3360 Some(name.to_string())
3361 } else if let Some(v) = attr.value_str() {
3362 Some(format!("{} = {:?}", name, v.as_str()))
3363 } else if let Some(values) = attr.meta_item_list() {
3364 let display: Vec<_> = values.iter().filter_map(|attr| {
3365 attr.meta_item().and_then(|mi| render_attribute(mi))
3368 if display.len() > 0 {
3369 Some(format!("{}({})", name, display.join(", ")))
3378 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3385 "unsafe_destructor_blind_to_params",
3389 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3390 let mut attrs = String::new();
3392 for attr in &it.attrs.other_attrs {
3393 let name = attr.name();
3394 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3397 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3398 attrs.push_str(&format!("#[{}]\n", s));
3401 if attrs.len() > 0 {
3402 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3407 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3408 g: Option<&clean::Generics>,
3409 ty: doctree::StructType,
3410 fields: &[clean::Item],
3412 structhead: bool) -> fmt::Result {
3414 VisSpace(&it.visibility),
3415 if structhead {"struct "} else {""},
3416 it.name.as_ref().unwrap())?;
3417 if let Some(g) = g {
3422 if let Some(g) = g {
3423 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3425 let mut has_visible_fields = false;
3427 for field in fields {
3428 if let clean::StructFieldItem(ref ty) = field.inner {
3429 write!(w, "\n{} {}{}: {},",
3431 VisSpace(&field.visibility),
3432 field.name.as_ref().unwrap(),
3434 has_visible_fields = true;
3438 if has_visible_fields {
3439 if it.has_stripped_fields().unwrap() {
3440 write!(w, "\n{} // some fields omitted", tab)?;
3442 write!(w, "\n{}", tab)?;
3443 } else if it.has_stripped_fields().unwrap() {
3444 // If there are no visible fields we can just display
3445 // `{ /* fields omitted */ }` to save space.
3446 write!(w, " /* fields omitted */ ")?;
3452 for (i, field) in fields.iter().enumerate() {
3457 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3460 clean::StructFieldItem(ref ty) => {
3461 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3467 if let Some(g) = g {
3468 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3473 // Needed for PhantomData.
3474 if let Some(g) = g {
3475 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3483 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3484 g: Option<&clean::Generics>,
3485 fields: &[clean::Item],
3487 structhead: bool) -> fmt::Result {
3489 VisSpace(&it.visibility),
3490 if structhead {"union "} else {""},
3491 it.name.as_ref().unwrap())?;
3492 if let Some(g) = g {
3493 write!(w, "{}", g)?;
3494 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3497 write!(w, " {{\n{}", tab)?;
3498 for field in fields {
3499 if let clean::StructFieldItem(ref ty) = field.inner {
3500 write!(w, " {}{}: {},\n{}",
3501 VisSpace(&field.visibility),
3502 field.name.as_ref().unwrap(),
3508 if it.has_stripped_fields().unwrap() {
3509 write!(w, " // some fields omitted\n{}", tab)?;
3515 #[derive(Copy, Clone)]
3516 enum AssocItemLink<'a> {
3517 Anchor(Option<&'a str>),
3518 GotoSource(DefId, &'a FxHashSet<String>),
3521 impl<'a> AssocItemLink<'a> {
3522 fn anchor(&self, id: &'a String) -> Self {
3524 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3525 ref other => *other,
3530 enum AssocItemRender<'a> {
3532 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3535 #[derive(Copy, Clone, PartialEq)]
3538 ForDeref { mut_: bool },
3541 fn render_assoc_items(w: &mut fmt::Formatter,
3543 containing_item: &clean::Item,
3545 what: AssocItemRender) -> fmt::Result {
3547 let v = match c.impls.get(&it) {
3549 None => return Ok(()),
3551 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3552 i.inner_impl().trait_.is_none()
3554 if !non_trait.is_empty() {
3555 let render_mode = match what {
3556 AssocItemRender::All => {
3558 <h2 id='methods' class='small-section-header'>\
3559 Methods<a href='#methods' class='anchor'></a>\
3564 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3566 <h2 id='deref-methods' class='small-section-header'>\
3567 Methods from {}<Target = {}>\
3568 <a href='#deref-methods' class='anchor'></a>\
3571 RenderMode::ForDeref { mut_: deref_mut_ }
3574 for i in &non_trait {
3575 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3576 containing_item.stable_since(), true, None)?;
3579 if let AssocItemRender::DerefFor { .. } = what {
3582 if !traits.is_empty() {
3583 let deref_impl = traits.iter().find(|t| {
3584 t.inner_impl().trait_.def_id() == c.deref_trait_did
3586 if let Some(impl_) = deref_impl {
3587 let has_deref_mut = traits.iter().find(|t| {
3588 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3590 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3593 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3595 .partition(|t| t.inner_impl().synthetic);
3596 let (blanket_impl, concrete) = concrete
3598 .partition(|t| t.inner_impl().blanket_impl.is_some());
3600 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3602 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3603 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3604 render_impls(self.0, fmt, &self.1, self.2)
3608 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3609 if !impls.is_empty() {
3611 <h2 id='implementations' class='small-section-header'>\
3612 Trait Implementations<a href='#implementations' class='anchor'></a>\
3614 <div id='implementations-list'>{}</div>", impls)?;
3617 if !synthetic.is_empty() {
3619 <h2 id='synthetic-implementations' class='small-section-header'>\
3620 Auto Trait Implementations\
3621 <a href='#synthetic-implementations' class='anchor'></a>\
3623 <div id='synthetic-implementations-list'>\
3625 render_impls(cx, w, &synthetic, containing_item)?;
3626 write!(w, "</div>")?;
3629 if !blanket_impl.is_empty() {
3631 <h2 id='blanket-implementations' class='small-section-header'>\
3632 Blanket Implementations\
3633 <a href='#blanket-implementations' class='anchor'></a>\
3635 <div id='blanket-implementations-list'>\
3637 render_impls(cx, w, &blanket_impl, containing_item)?;
3638 write!(w, "</div>")?;
3644 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3645 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3646 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3647 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3649 clean::TypedefItem(ref t, true) => Some(&t.type_),
3652 }).next().expect("Expected associated type binding");
3653 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3654 deref_mut_: deref_mut };
3655 if let Some(did) = target.def_id() {
3656 render_assoc_items(w, cx, container_item, did, what)
3658 if let Some(prim) = target.primitive_type() {
3659 if let Some(&did) = cache().primitive_locations.get(&prim) {
3660 render_assoc_items(w, cx, container_item, did, what)?;
3667 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3668 let self_type_opt = match item.inner {
3669 clean::MethodItem(ref method) => method.decl.self_type(),
3670 clean::TyMethodItem(ref method) => method.decl.self_type(),
3674 if let Some(self_ty) = self_type_opt {
3675 let (by_mut_ref, by_box, by_value) = match self_ty {
3676 SelfTy::SelfBorrowed(_, mutability) |
3677 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3678 (mutability == Mutability::Mutable, false, false)
3680 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3681 (false, Some(did) == cache().owned_box_did, false)
3683 SelfTy::SelfValue => (false, false, true),
3684 _ => (false, false, false),
3687 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3693 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3694 let mut out = String::new();
3697 clean::FunctionItem(clean::Function { ref decl, .. }) |
3698 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3699 clean::MethodItem(clean::Method { ref decl, .. }) |
3700 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3701 out = spotlight_decl(decl)?;
3709 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3710 let mut out = String::new();
3711 let mut trait_ = String::new();
3713 if let Some(did) = decl.output.def_id() {
3715 if let Some(impls) = c.impls.get(&did) {
3717 let impl_ = i.inner_impl();
3718 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3721 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3722 <code class=\"content\">",
3724 trait_.push_str(&impl_.for_.to_string());
3727 //use the "where" class here to make it small
3728 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3729 let t_did = impl_.trait_.def_id().unwrap();
3730 for it in &impl_.items {
3731 if let clean::TypedefItem(ref tydef, _) = it.inner {
3732 out.push_str("<span class=\"where fmt-newline\"> ");
3733 assoc_type(&mut out, it, &[],
3735 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3736 out.push_str(";</span>");
3744 if !out.is_empty() {
3745 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3746 <span class='tooltiptext'>Important traits for {}</span></div>\
3747 <div class=\"content hidden\">",
3749 out.push_str("</code></div></div>");
3755 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3756 render_mode: RenderMode, outer_version: Option<&str>,
3757 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
3758 if render_mode == RenderMode::Normal {
3759 let id = cx.derive_id(match i.inner_impl().trait_ {
3760 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3761 None => "impl".to_string(),
3763 if let Some(use_absolute) = use_absolute {
3764 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3765 <tbody><tr><td><code>", id)?;
3766 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
3768 for it in &i.inner_impl().items {
3769 if let clean::TypedefItem(ref tydef, _) = it.inner {
3770 write!(w, "<span class=\"where fmt-newline\"> ")?;
3771 assoc_type(w, it, &vec![], Some(&tydef.type_),
3772 AssocItemLink::Anchor(None))?;
3773 write!(w, ";</span>")?;
3777 write!(w, "</code>")?;
3779 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3780 <tbody><tr><td><code>{}</code>",
3781 id, i.inner_impl())?;
3783 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3784 write!(w, "</span></td><td><span class='out-of-band'>")?;
3785 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3786 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3787 write!(w, "<div class='ghost'></div>")?;
3788 render_stability_since_raw(w, since, outer_version)?;
3789 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3790 l, "goto source code")?;
3792 render_stability_since_raw(w, since, outer_version)?;
3794 write!(w, "</span></td></tr></tbody></table></h3>")?;
3795 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3796 let mut ids = cx.id_map.borrow_mut();
3797 write!(w, "<div class='docblock'>{}</div>",
3798 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
3802 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3803 link: AssocItemLink, render_mode: RenderMode,
3804 is_default_item: bool, outer_version: Option<&str>,
3805 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3806 let item_type = item.type_();
3807 let name = item.name.as_ref().unwrap();
3809 let render_method_item: bool = match render_mode {
3810 RenderMode::Normal => true,
3811 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3815 clean::MethodItem(clean::Method { ref decl, .. }) |
3816 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3817 // Only render when the method is not static or we allow static methods
3818 if render_method_item {
3819 let id = cx.derive_id(format!("{}.{}", item_type, name));
3820 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3821 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3822 write!(w, "{}", spotlight_decl(decl)?)?;
3823 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3824 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3825 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3826 write!(w, "</code>")?;
3827 if let Some(l) = (Item { cx, item }).src_href() {
3828 write!(w, "</span></td><td><span class='out-of-band'>")?;
3829 write!(w, "<div class='ghost'></div>")?;
3830 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3831 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3832 l, "goto source code")?;
3834 write!(w, "</td><td>")?;
3835 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3837 write!(w, "</td></tr></tbody></table></span></h4>")?;
3840 clean::TypedefItem(ref tydef, _) => {
3841 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3842 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3843 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3844 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3845 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3846 write!(w, "</code></span></h4>\n")?;
3848 clean::AssociatedConstItem(ref ty, ref default) => {
3849 let id = cx.derive_id(format!("{}.{}", item_type, name));
3850 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3851 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3852 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3853 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3854 let src = if let Some(l) = (Item { cx, item }).src_href() {
3855 format!("<a class='srclink' href='{}' title='{}'>[src]</a>",
3856 l, "goto source code")
3860 write!(w, "</code>{}</span></h4>\n", src)?;
3862 clean::AssociatedTypeItem(ref bounds, ref default) => {
3863 let id = cx.derive_id(format!("{}.{}", item_type, name));
3864 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3865 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3866 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3867 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3868 write!(w, "</code></span></h4>\n")?;
3870 clean::StrippedItem(..) => return Ok(()),
3871 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3874 if render_method_item || render_mode == RenderMode::Normal {
3875 if !is_default_item {
3876 if let Some(t) = trait_ {
3877 // The trait item may have been stripped so we might not
3878 // find any documentation or stability for it.
3879 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3880 // We need the stability of the item from the trait
3881 // because impls can't have a stability.
3882 document_stability(w, cx, it)?;
3883 if item.doc_value().is_some() {
3884 document_full(w, item, cx, "")?;
3885 } else if show_def_docs {
3886 // In case the item isn't documented,
3887 // provide short documentation from the trait.
3888 document_short(w, cx, it, link, "")?;
3892 document_stability(w, cx, item)?;
3894 document_full(w, item, cx, "")?;
3898 document_stability(w, cx, item)?;
3900 document_short(w, cx, item, link, "")?;
3907 let traits = &cache().traits;
3908 let trait_ = i.trait_did().map(|did| &traits[&did]);
3910 write!(w, "<div class='impl-items'>")?;
3911 for trait_item in &i.inner_impl().items {
3912 doc_impl_item(w, cx, trait_item, link, render_mode,
3913 false, outer_version, trait_, show_def_docs)?;
3916 fn render_default_items(w: &mut fmt::Formatter,
3920 render_mode: RenderMode,
3921 outer_version: Option<&str>,
3922 show_def_docs: bool) -> fmt::Result {
3923 for trait_item in &t.items {
3924 let n = trait_item.name.clone();
3925 if i.items.iter().find(|m| m.name == n).is_some() {
3928 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3929 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3931 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3932 outer_version, None, show_def_docs)?;
3937 // If we've implemented a trait, then also emit documentation for all
3938 // default items which weren't overridden in the implementation block.
3939 if let Some(t) = trait_ {
3940 render_default_items(w, cx, t, &i.inner_impl(),
3941 render_mode, outer_version, show_def_docs)?;
3943 write!(w, "</div>")?;
3948 fn item_existential(
3949 w: &mut fmt::Formatter,
3952 t: &clean::Existential,
3954 write!(w, "<pre class='rust existential'>")?;
3955 render_attributes(w, it)?;
3956 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
3957 it.name.as_ref().unwrap(),
3959 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3960 bounds = bounds(&t.bounds))?;
3962 document(w, cx, it)?;
3964 // Render any items associated directly to this alias, as otherwise they
3965 // won't be visible anywhere in the docs. It would be nice to also show
3966 // associated items from the aliased type (see discussion in #32077), but
3967 // we need #14072 to make sense of the generics.
3968 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3971 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3972 t: &clean::Typedef) -> fmt::Result {
3973 write!(w, "<pre class='rust typedef'>")?;
3974 render_attributes(w, it)?;
3975 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3976 it.name.as_ref().unwrap(),
3978 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3981 document(w, cx, it)?;
3983 // Render any items associated directly to this alias, as otherwise they
3984 // won't be visible anywhere in the docs. It would be nice to also show
3985 // associated items from the aliased type (see discussion in #32077), but
3986 // we need #14072 to make sense of the generics.
3987 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3990 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3991 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3992 render_attributes(w, it)?;
3995 " {}type {};\n}}</pre>",
3996 VisSpace(&it.visibility),
3997 it.name.as_ref().unwrap(),
4000 document(w, cx, it)?;
4002 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4005 impl<'a> fmt::Display for Sidebar<'a> {
4006 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4009 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4011 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4012 || it.is_enum() || it.is_mod() || it.is_typedef() {
4013 write!(fmt, "<p class='location'>{}{}</p>",
4015 clean::StructItem(..) => "Struct ",
4016 clean::TraitItem(..) => "Trait ",
4017 clean::PrimitiveItem(..) => "Primitive Type ",
4018 clean::UnionItem(..) => "Union ",
4019 clean::EnumItem(..) => "Enum ",
4020 clean::TypedefItem(..) => "Type Definition ",
4021 clean::ForeignTypeItem => "Foreign Type ",
4022 clean::ModuleItem(..) => if it.is_crate() {
4029 it.name.as_ref().unwrap())?;
4033 if let Some(ref version) = cache().crate_version {
4035 "<div class='block version'>\
4038 <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4040 it.name.as_ref().unwrap())?;
4044 write!(fmt, "<div class=\"sidebar-elems\">")?;
4046 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4047 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4048 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4049 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4050 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4051 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4052 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4053 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4057 // The sidebar is designed to display sibling functions, modules and
4058 // other miscellaneous information. since there are lots of sibling
4059 // items (and that causes quadratic growth in large modules),
4060 // we refactor common parts into a shared JavaScript file per module.
4061 // still, we don't move everything into JS because we want to preserve
4062 // as much HTML as possible in order to allow non-JS-enabled browsers
4063 // to navigate the documentation (though slightly inefficiently).
4065 write!(fmt, "<p class='location'>")?;
4066 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4068 write!(fmt, "::<wbr>")?;
4070 write!(fmt, "<a href='{}index.html'>{}</a>",
4071 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4074 write!(fmt, "</p>")?;
4076 // Sidebar refers to the enclosing module, not this module.
4077 let relpath = if it.is_mod() { "../" } else { "" };
4079 "<script>window.sidebarCurrent = {{\
4084 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4085 ty = it.type_().css_class(),
4088 // There is no sidebar-items.js beyond the crate root path
4089 // FIXME maybe dynamic crate loading can be merged here
4091 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4094 // Closes sidebar-elems div.
4095 write!(fmt, "</div>")?;
4101 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
4102 i.items.iter().filter_map(|item| {
4104 // Maybe check with clean::Visibility::Public as well?
4105 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4106 if !for_deref || should_render_item(item, false) {
4107 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4114 }).collect::<Vec<_>>()
4117 // The point is to url encode any potential character from a type with genericity.
4118 fn small_url_encode(s: &str) -> String {
4119 s.replace("<", "%3C")
4120 .replace(">", "%3E")
4121 .replace(" ", "%20")
4122 .replace("?", "%3F")
4123 .replace("'", "%27")
4124 .replace("&", "%26")
4125 .replace(",", "%2C")
4126 .replace(":", "%3A")
4127 .replace(";", "%3B")
4128 .replace("[", "%5B")
4129 .replace("]", "%5D")
4130 .replace("\"", "%22")
4133 fn sidebar_assoc_items(it: &clean::Item) -> String {
4134 let mut out = String::new();
4136 if let Some(v) = c.impls.get(&it.def_id) {
4138 .filter(|i| i.inner_impl().trait_.is_none())
4139 .flat_map(|i| get_methods(i.inner_impl(), false))
4140 .collect::<String>();
4141 if !ret.is_empty() {
4142 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4143 </a><div class=\"sidebar-links\">{}</div>", ret));
4146 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4147 if let Some(impl_) = v.iter()
4148 .filter(|i| i.inner_impl().trait_.is_some())
4149 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4150 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4152 clean::TypedefItem(ref t, true) => Some(&t.type_),
4156 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4157 c.primitive_locations.get(&prim).cloned()
4158 })).and_then(|did| c.impls.get(&did));
4159 if let Some(impls) = inner_impl {
4160 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4161 out.push_str(&format!("Methods from {}<Target={}>",
4162 Escape(&format!("{:#}",
4163 impl_.inner_impl().trait_.as_ref().unwrap())),
4164 Escape(&format!("{:#}", target))));
4165 out.push_str("</a>");
4166 let ret = impls.iter()
4167 .filter(|i| i.inner_impl().trait_.is_none())
4168 .flat_map(|i| get_methods(i.inner_impl(), true))
4169 .collect::<String>();
4170 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4174 let format_impls = |impls: Vec<&Impl>| {
4175 let mut links = FxHashSet::default();
4178 let is_negative_impl = is_negative_impl(i.inner_impl());
4179 if let Some(ref i) = i.inner_impl().trait_ {
4180 let i_display = format!("{:#}", i);
4181 let out = Escape(&i_display);
4182 let encoded = small_url_encode(&format!("{:#}", i));
4183 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4185 if is_negative_impl { "!" } else { "" },
4187 if links.insert(generated.clone()) {
4196 .collect::<String>()
4199 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4201 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4202 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4204 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4206 let concrete_format = format_impls(concrete);
4207 let synthetic_format = format_impls(synthetic);
4208 let blanket_format = format_impls(blanket_impl);
4210 if !concrete_format.is_empty() {
4211 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4212 Trait Implementations</a>");
4213 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4216 if !synthetic_format.is_empty() {
4217 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4218 Auto Trait Implementations</a>");
4219 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4222 if !blanket_format.is_empty() {
4223 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4224 Blanket Implementations</a>");
4225 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4233 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4234 s: &clean::Struct) -> fmt::Result {
4235 let mut sidebar = String::new();
4236 let fields = get_struct_fields_name(&s.fields);
4238 if !fields.is_empty() {
4239 if let doctree::Plain = s.struct_type {
4240 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4241 <div class=\"sidebar-links\">{}</div>", fields));
4245 sidebar.push_str(&sidebar_assoc_items(it));
4247 if !sidebar.is_empty() {
4248 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4253 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4255 clean::ItemEnum::ImplItem(ref i) => {
4256 if let Some(ref trait_) = i.trait_ {
4257 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4266 fn is_negative_impl(i: &clean::Impl) -> bool {
4267 i.polarity == Some(clean::ImplPolarity::Negative)
4270 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4271 t: &clean::Trait) -> fmt::Result {
4272 let mut sidebar = String::new();
4278 Some(ref name) if m.is_associated_type() => {
4279 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4285 .collect::<String>();
4286 let consts = t.items
4290 Some(ref name) if m.is_associated_const() => {
4291 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4297 .collect::<String>();
4298 let required = t.items
4302 Some(ref name) if m.is_ty_method() => {
4303 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4309 .collect::<String>();
4310 let provided = t.items
4314 Some(ref name) if m.is_method() => {
4315 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4320 .collect::<String>();
4322 if !types.is_empty() {
4323 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4324 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4327 if !consts.is_empty() {
4328 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4329 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4332 if !required.is_empty() {
4333 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4334 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4337 if !provided.is_empty() {
4338 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4339 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4345 if let Some(implementors) = c.implementors.get(&it.def_id) {
4346 let res = implementors.iter()
4347 .filter(|i| i.inner_impl().for_.def_id()
4348 .map_or(false, |d| !c.paths.contains_key(&d)))
4350 match extract_for_impl_name(&i.impl_item) {
4351 Some((ref name, ref url)) => {
4352 Some(format!("<a href=\"#impl-{}\">{}</a>",
4353 small_url_encode(url),
4359 .collect::<String>();
4360 if !res.is_empty() {
4361 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4362 Implementations on Foreign Types</a><div \
4363 class=\"sidebar-links\">{}</div>",
4368 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4370 sidebar.push_str("<a class=\"sidebar-title\" \
4371 href=\"#synthetic-implementors\">Auto Implementors</a>");
4374 sidebar.push_str(&sidebar_assoc_items(it));
4376 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4379 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4380 _p: &clean::PrimitiveType) -> fmt::Result {
4381 let sidebar = sidebar_assoc_items(it);
4383 if !sidebar.is_empty() {
4384 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4389 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4390 _t: &clean::Typedef) -> fmt::Result {
4391 let sidebar = sidebar_assoc_items(it);
4393 if !sidebar.is_empty() {
4394 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4399 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4401 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4406 .filter_map(|f| match f.name {
4407 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4408 {name}</a>", name=name)),
4414 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4415 u: &clean::Union) -> fmt::Result {
4416 let mut sidebar = String::new();
4417 let fields = get_struct_fields_name(&u.fields);
4419 if !fields.is_empty() {
4420 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4421 <div class=\"sidebar-links\">{}</div>", fields));
4424 sidebar.push_str(&sidebar_assoc_items(it));
4426 if !sidebar.is_empty() {
4427 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4432 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4433 e: &clean::Enum) -> fmt::Result {
4434 let mut sidebar = String::new();
4436 let variants = e.variants.iter()
4437 .filter_map(|v| match v.name {
4438 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4439 </a>", name = name)),
4442 .collect::<String>();
4443 if !variants.is_empty() {
4444 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4445 <div class=\"sidebar-links\">{}</div>", variants));
4448 sidebar.push_str(&sidebar_assoc_items(it));
4450 if !sidebar.is_empty() {
4451 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4456 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4458 ItemType::ExternCrate |
4459 ItemType::Import => ("reexports", "Re-exports"),
4460 ItemType::Module => ("modules", "Modules"),
4461 ItemType::Struct => ("structs", "Structs"),
4462 ItemType::Union => ("unions", "Unions"),
4463 ItemType::Enum => ("enums", "Enums"),
4464 ItemType::Function => ("functions", "Functions"),
4465 ItemType::Typedef => ("types", "Type Definitions"),
4466 ItemType::Static => ("statics", "Statics"),
4467 ItemType::Constant => ("constants", "Constants"),
4468 ItemType::Trait => ("traits", "Traits"),
4469 ItemType::Impl => ("impls", "Implementations"),
4470 ItemType::TyMethod => ("tymethods", "Type Methods"),
4471 ItemType::Method => ("methods", "Methods"),
4472 ItemType::StructField => ("fields", "Struct Fields"),
4473 ItemType::Variant => ("variants", "Variants"),
4474 ItemType::Macro => ("macros", "Macros"),
4475 ItemType::Primitive => ("primitives", "Primitive Types"),
4476 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4477 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4478 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4479 ItemType::Keyword => ("keywords", "Keywords"),
4480 ItemType::Existential => ("existentials", "Existentials"),
4484 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4485 items: &[clean::Item]) -> fmt::Result {
4486 let mut sidebar = String::new();
4488 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4489 it.type_() == ItemType::Import) {
4490 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4492 name = "Re-exports"));
4495 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4496 // to print its headings
4497 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4498 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4499 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4500 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4501 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4502 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4503 let (short, name) = item_ty_to_strs(&myty);
4504 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4510 if !sidebar.is_empty() {
4511 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4516 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4517 let sidebar = sidebar_assoc_items(it);
4518 if !sidebar.is_empty() {
4519 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4524 impl<'a> fmt::Display for Source<'a> {
4525 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4526 let Source(s) = *self;
4527 let lines = s.lines().count();
4529 let mut tmp = lines;
4534 write!(fmt, "<pre class=\"line-numbers\">")?;
4535 for i in 1..lines + 1 {
4536 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4538 write!(fmt, "</pre>")?;
4540 highlight::render_with_highlighting(s, None, None, None))?;
4545 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4546 t: &clean::Macro) -> fmt::Result {
4547 wrap_into_docblock(w, |w| {
4548 w.write_str(&highlight::render_with_highlighting(&t.source,
4556 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4558 _p: &clean::PrimitiveType) -> fmt::Result {
4559 document(w, cx, it)?;
4560 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4563 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4565 _p: &str) -> fmt::Result {
4569 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4571 fn make_item_keywords(it: &clean::Item) -> String {
4572 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4575 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4576 let decl = match item.inner {
4577 clean::FunctionItem(ref f) => &f.decl,
4578 clean::MethodItem(ref m) => &m.decl,
4579 clean::TyMethodItem(ref m) => &m.decl,
4583 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4584 let output = match decl.output {
4585 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4589 Some(IndexItemFunctionType { inputs: inputs, output: output })
4592 fn get_index_type(clean_type: &clean::Type) -> Type {
4594 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4595 generics: get_generics(clean_type),
4600 /// Returns a list of all paths used in the type.
4601 /// This is used to help deduplicate imported impls
4602 /// for reexported types. If any of the contained
4603 /// types are re-exported, we don't use the corresponding
4604 /// entry from the js file, as inlining will have already
4605 /// picked up the impl
4606 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4607 let mut out = Vec::new();
4608 let mut visited = FxHashSet();
4609 let mut work = VecDeque::new();
4610 let cache = cache();
4612 work.push_back(first_ty);
4614 while let Some(ty) = work.pop_front() {
4615 if !visited.insert(ty.clone()) {
4620 clean::Type::ResolvedPath { did, .. } => {
4621 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4622 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4626 out.push(path.join("::"));
4632 clean::Type::Tuple(tys) => {
4633 work.extend(tys.into_iter());
4635 clean::Type::Slice(ty) => {
4636 work.push_back(*ty);
4638 clean::Type::Array(ty, _) => {
4639 work.push_back(*ty);
4641 clean::Type::Unique(ty) => {
4642 work.push_back(*ty);
4644 clean::Type::RawPointer(_, ty) => {
4645 work.push_back(*ty);
4647 clean::Type::BorrowedRef { type_, .. } => {
4648 work.push_back(*type_);
4650 clean::Type::QPath { self_type, trait_, .. } => {
4651 work.push_back(*self_type);
4652 work.push_back(*trait_);
4660 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4662 clean::ResolvedPath { ref path, .. } => {
4663 let segments = &path.segments;
4664 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4665 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4666 clean_type, accept_generic
4668 Some(path_segment.name.clone())
4670 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4671 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4672 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4673 // FIXME: add all from clean::Type.
4678 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4679 clean_type.generics()
4681 let r = types.iter()
4682 .filter_map(|t| get_index_type_name(t, false))
4683 .map(|s| s.to_ascii_lowercase())
4684 .collect::<Vec<_>>();
4693 pub fn cache() -> Arc<Cache> {
4694 CACHE_KEY.with(|c| c.borrow().clone())
4699 fn test_name_key() {
4700 assert_eq!(name_key("0"), ("", 0, 1));
4701 assert_eq!(name_key("123"), ("", 123, 0));
4702 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4703 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4704 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4705 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4706 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4707 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4712 fn test_name_sorting() {
4713 let names = ["Apple",
4715 "Fruit", "Fruit0", "Fruit00",
4716 "Fruit1", "Fruit01",
4717 "Fruit2", "Fruit02",
4721 let mut sorted = names.to_owned();
4722 sorted.sort_by_key(|&s| name_key(s));
4723 assert_eq!(names, sorted);