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.
35 pub use self::ExternalLocation::*;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::{BTreeMap, HashSet, VecDeque};
41 use std::default::Default;
43 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
44 use std::fs::{self, File, OpenOptions};
45 use std::io::prelude::*;
46 use std::io::{self, BufWriter, BufReader};
47 use std::iter::repeat;
49 use std::path::{PathBuf, Path, Component};
53 use externalfiles::ExternalHtml;
55 use serialize::json::{ToJson, Json, as_json};
56 use syntax::{abi, ast};
57 use syntax::codemap::FileName;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
68 use html::escape::Escape;
69 use html::format::{ConstnessSpace};
70 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
71 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
72 use html::format::fmt_impl_for_trait_page;
73 use html::item_type::ItemType;
74 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
75 use html::{highlight, layout};
77 /// A pair of name and its optional document.
78 pub type NameDoc = (String, Option<String>);
80 /// Major driving force in all rustdoc rendering. This contains information
81 /// about where in the tree-like hierarchy rendering is occurring and controls
82 /// how the current page is being rendered.
84 /// It is intended that this context is a lightweight object which can be fairly
85 /// easily cloned because it is cloned per work-job (about once per item in the
89 /// Current hierarchy of components leading down to what's currently being
91 pub current: Vec<String>,
92 /// The current destination folder of where HTML artifacts should be placed.
93 /// This changes as the context descends into the module hierarchy.
95 /// A flag, which when `true`, will render pages which redirect to the
96 /// real location of an item. This is used to allow external links to
97 /// publicly reused items to redirect to the right location.
98 pub render_redirect_pages: bool,
99 pub shared: Arc<SharedContext>,
102 pub struct SharedContext {
103 /// The path to the crate root source minus the file name.
104 /// Used for simplifying paths to the highlighted source code files.
105 pub src_root: PathBuf,
106 /// This describes the layout of each page, and is not modified after
107 /// creation of the context (contains info like the favicon and added html).
108 pub layout: layout::Layout,
109 /// This flag indicates whether [src] links should be generated or not. If
110 /// the source files are present in the html rendering, then this will be
112 pub include_sources: bool,
113 /// The local file sources we've emitted and their respective url-paths.
114 pub local_sources: FxHashMap<PathBuf, String>,
115 /// All the passes that were run on this crate.
116 pub passes: FxHashSet<String>,
117 /// The base-URL of the issue tracker for when an item has been tagged with
119 pub issue_tracker_base_url: Option<String>,
120 /// The given user css file which allow to customize the generated
121 /// documentation theme.
122 pub css_file_extension: Option<PathBuf>,
123 /// The directories that have already been created in this doc run. Used to reduce the number
124 /// of spurious `create_dir_all` calls.
125 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
126 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
127 /// should be ordered alphabetically or in order of appearance (in the source code).
128 pub sort_modules_alphabetically: bool,
129 /// Additional themes to be added to the generated docs.
130 pub themes: Vec<PathBuf>,
134 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
135 let mut dirs = self.created_dirs.borrow_mut();
136 if !dirs.contains(dst) {
137 fs::create_dir_all(dst)?;
138 dirs.insert(dst.to_path_buf());
146 /// Returns whether the `collapse-docs` pass was run on this crate.
147 pub fn was_collapsed(&self) -> bool {
148 self.passes.contains("collapse-docs")
151 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
152 /// `collapsed_doc_value` of the given item.
153 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
154 if self.was_collapsed() {
155 item.collapsed_doc_value().map(|s| s.into())
157 item.doc_value().map(|s| s.into())
162 /// Indicates where an external crate can be found.
163 pub enum ExternalLocation {
164 /// Remote URL root of the external crate
166 /// This external crate can be found in the local doc/ folder
168 /// The external crate could not be found.
172 /// Metadata about implementations for a type or trait.
175 pub impl_item: clean::Item,
179 fn inner_impl(&self) -> &clean::Impl {
180 match self.impl_item.inner {
181 clean::ImplItem(ref impl_) => impl_,
182 _ => panic!("non-impl item found in impl")
186 fn trait_did(&self) -> Option<DefId> {
187 self.inner_impl().trait_.def_id()
197 impl error::Error for Error {
198 fn description(&self) -> &str {
199 self.error.description()
203 impl Display for Error {
204 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
205 write!(f, "\"{}\": {}", self.file.display(), self.error)
210 pub fn new(e: io::Error, file: &Path) -> Error {
212 file: file.to_path_buf(),
218 macro_rules! try_none {
219 ($e:expr, $file:expr) => ({
223 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
229 macro_rules! try_err {
230 ($e:expr, $file:expr) => ({
233 Err(e) => return Err(Error::new(e, $file)),
238 /// This cache is used to store information about the `clean::Crate` being
239 /// rendered in order to provide more useful documentation. This contains
240 /// information like all implementors of a trait, all traits a type implements,
241 /// documentation for all known traits, etc.
243 /// This structure purposefully does not implement `Clone` because it's intended
244 /// to be a fairly large and expensive structure to clone. Instead this adheres
245 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
246 /// rendering threads.
249 /// Mapping of typaram ids to the name of the type parameter. This is used
250 /// when pretty-printing a type (so pretty printing doesn't have to
251 /// painfully maintain a context like this)
252 pub typarams: FxHashMap<DefId, String>,
254 /// Maps a type id to all known implementations for that type. This is only
255 /// recognized for intra-crate `ResolvedPath` types, and is used to print
256 /// out extra documentation on the page of an enum/struct.
258 /// The values of the map are a list of implementations and documentation
259 /// found on that implementation.
260 pub impls: FxHashMap<DefId, Vec<Impl>>,
262 /// Maintains a mapping of local crate node ids to the fully qualified name
263 /// and "short type description" of that node. This is used when generating
264 /// URLs when a type is being linked to. External paths are not located in
265 /// this map because the `External` type itself has all the information
267 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
269 /// Similar to `paths`, but only holds external paths. This is only used for
270 /// generating explicit hyperlinks to other crates.
271 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
273 /// Maps local def ids of exported types to fully qualified paths.
274 /// Unlike 'paths', this mapping ignores any renames that occur
275 /// due to 'use' statements.
277 /// This map is used when writing out the special 'implementors'
278 /// javascript file. By using the exact path that the type
279 /// is declared with, we ensure that each path will be identical
280 /// to the path used if the corresponding type is inlined. By
281 /// doing this, we can detect duplicate impls on a trait page, and only display
282 /// the impl for the inlined type.
283 pub exact_paths: FxHashMap<DefId, Vec<String>>,
285 /// This map contains information about all known traits of this crate.
286 /// Implementations of a crate should inherit the documentation of the
287 /// parent trait if no extra documentation is specified, and default methods
288 /// should show up in documentation about trait implementations.
289 pub traits: FxHashMap<DefId, clean::Trait>,
291 /// When rendering traits, it's often useful to be able to list all
292 /// implementors of the trait, and this mapping is exactly, that: a mapping
293 /// of trait ids to the list of known implementors of the trait
294 pub implementors: FxHashMap<DefId, Vec<Impl>>,
296 /// Cache of where external crate documentation can be found.
297 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
299 /// Cache of where documentation for primitives can be found.
300 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
302 // Note that external items for which `doc(hidden)` applies to are shown as
303 // non-reachable while local items aren't. This is because we're reusing
304 // the access levels from crateanalysis.
305 pub access_levels: Arc<AccessLevels<DefId>>,
307 /// The version of the crate being documented, if given fron the `--crate-version` flag.
308 pub crate_version: Option<String>,
310 // Private fields only used when initially crawling a crate to build a cache
313 parent_stack: Vec<DefId>,
314 parent_is_trait_impl: bool,
315 search_index: Vec<IndexItem>,
317 deref_trait_did: Option<DefId>,
318 deref_mut_trait_did: Option<DefId>,
319 owned_box_did: Option<DefId>,
320 masked_crates: FxHashSet<CrateNum>,
322 // In rare case where a structure is defined in one module but implemented
323 // in another, if the implementing module is parsed before defining module,
324 // then the fully qualified name of the structure isn't presented in `paths`
325 // yet when its implementation methods are being indexed. Caches such methods
326 // and their parent id here and indexes them at the end of crate parsing.
327 orphan_impl_items: Vec<(DefId, clean::Item)>,
330 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
331 /// Later on moved into `CACHE_KEY`.
333 pub struct RenderInfo {
334 pub inlined: FxHashSet<DefId>,
335 pub external_paths: ::core::ExternalPaths,
336 pub external_typarams: FxHashMap<DefId, String>,
337 pub exact_paths: FxHashMap<DefId, Vec<String>>,
338 pub deref_trait_did: Option<DefId>,
339 pub deref_mut_trait_did: Option<DefId>,
340 pub owned_box_did: Option<DefId>,
343 /// Helper struct to render all source code to HTML pages
344 struct SourceCollector<'a> {
345 scx: &'a mut SharedContext,
347 /// Root destination to place all HTML output into
351 /// Wrapper struct to render the source code of a file. This will do things like
352 /// adding line numbers to the left-hand side.
353 struct Source<'a>(&'a str);
355 // Helper structs for rendering items/sidebars and carrying along contextual
358 #[derive(Copy, Clone)]
361 item: &'a clean::Item,
364 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
366 /// Struct representing one entry in the JS search index. These are all emitted
367 /// by hand to a large JS file at the end of cache-creation.
373 parent: Option<DefId>,
374 parent_idx: Option<usize>,
375 search_type: Option<IndexItemFunctionType>,
378 impl ToJson for IndexItem {
379 fn to_json(&self) -> Json {
380 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
382 let mut data = Vec::with_capacity(6);
383 data.push((self.ty as usize).to_json());
384 data.push(self.name.to_json());
385 data.push(self.path.to_json());
386 data.push(self.desc.to_json());
387 data.push(self.parent_idx.to_json());
388 data.push(self.search_type.to_json());
394 /// A type used for the search index.
396 name: Option<String>,
397 generics: Option<Vec<String>>,
400 impl ToJson for Type {
401 fn to_json(&self) -> Json {
404 let mut data = BTreeMap::new();
405 data.insert("name".to_owned(), name.to_json());
406 if let Some(ref generics) = self.generics {
407 data.insert("generics".to_owned(), generics.to_json());
416 /// Full type of functions/methods in the search index.
417 struct IndexItemFunctionType {
422 impl ToJson for IndexItemFunctionType {
423 fn to_json(&self) -> Json {
424 // If we couldn't figure out a type, just write `null`.
425 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
428 let mut data = BTreeMap::new();
429 data.insert("inputs".to_owned(), self.inputs.to_json());
430 data.insert("output".to_owned(), self.output.to_json());
436 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
437 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
438 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
440 fn init_ids() -> FxHashMap<String, usize> {
452 "synthetic-implementors",
454 "synthetic-implementors-list",
458 ].into_iter().map(|id| (String::from(*id), 1)).collect()
461 /// This method resets the local table of used ID attributes. This is typically
462 /// used at the beginning of rendering an entire HTML page to reset from the
463 /// previous state (if any).
464 pub fn reset_ids(embedded: bool) {
465 USED_ID_MAP.with(|s| {
466 *s.borrow_mut() = if embedded {
474 pub fn derive_id(candidate: String) -> String {
475 USED_ID_MAP.with(|map| {
476 let id = match map.borrow_mut().get_mut(&candidate) {
479 let id = format!("{}-{}", candidate, *a);
485 map.borrow_mut().insert(id.clone(), 1);
490 /// Generates the documentation for `crate` into the directory `dst`
491 pub fn run(mut krate: clean::Crate,
492 external_html: &ExternalHtml,
493 playground_url: Option<String>,
495 passes: FxHashSet<String>,
496 css_file_extension: Option<PathBuf>,
497 renderinfo: RenderInfo,
498 sort_modules_alphabetically: bool,
499 themes: Vec<PathBuf>) -> Result<(), Error> {
500 let src_root = match krate.src {
501 FileName::Real(ref p) => match p.parent() {
502 Some(p) => p.to_path_buf(),
503 None => PathBuf::new(),
507 let mut scx = SharedContext {
510 include_sources: true,
511 local_sources: FxHashMap(),
512 issue_tracker_base_url: None,
513 layout: layout::Layout {
514 logo: "".to_string(),
515 favicon: "".to_string(),
516 external_html: external_html.clone(),
517 krate: krate.name.clone(),
519 css_file_extension: css_file_extension.clone(),
520 created_dirs: RefCell::new(FxHashSet()),
521 sort_modules_alphabetically,
525 // If user passed in `--playground-url` arg, we fill in crate name here
526 if let Some(url) = playground_url {
527 markdown::PLAYGROUND.with(|slot| {
528 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
532 // Crawl the crate attributes looking for attributes which control how we're
533 // going to emit HTML
534 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
535 for attr in attrs.lists("doc") {
536 let name = attr.name().map(|s| s.as_str());
537 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
538 (Some("html_favicon_url"), Some(s)) => {
539 scx.layout.favicon = s.to_string();
541 (Some("html_logo_url"), Some(s)) => {
542 scx.layout.logo = s.to_string();
544 (Some("html_playground_url"), Some(s)) => {
545 markdown::PLAYGROUND.with(|slot| {
546 let name = krate.name.clone();
547 *slot.borrow_mut() = Some((Some(name), s.to_string()));
550 (Some("issue_tracker_base_url"), Some(s)) => {
551 scx.issue_tracker_base_url = Some(s.to_string());
553 (Some("html_no_source"), None) if attr.is_word() => {
554 scx.include_sources = false;
560 try_err!(fs::create_dir_all(&dst), &dst);
561 krate = render_sources(&dst, &mut scx, krate)?;
565 render_redirect_pages: false,
566 shared: Arc::new(scx),
569 // Crawl the crate to build various caches used for the output
580 let external_paths = external_paths.into_iter()
581 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
584 let mut cache = Cache {
589 implementors: FxHashMap(),
591 parent_stack: Vec::new(),
592 search_index: Vec::new(),
593 parent_is_trait_impl: false,
594 extern_locations: FxHashMap(),
595 primitive_locations: FxHashMap(),
597 access_levels: krate.access_levels.clone(),
598 crate_version: krate.version.take(),
599 orphan_impl_items: Vec::new(),
600 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
604 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
605 typarams: external_typarams,
608 // Cache where all our extern crates are located
609 for &(n, ref e) in &krate.externs {
610 let src_root = match e.src {
611 FileName::Real(ref p) => match p.parent() {
612 Some(p) => p.to_path_buf(),
613 None => PathBuf::new(),
617 cache.extern_locations.insert(n, (e.name.clone(), src_root,
618 extern_location(e, &cx.dst)));
620 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
621 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
624 // Cache where all known primitives have their documentation located.
626 // Favor linking to as local extern as possible, so iterate all crates in
627 // reverse topological order.
628 for &(_, ref e) in krate.externs.iter().rev() {
629 for &(def_id, prim, _) in &e.primitives {
630 cache.primitive_locations.insert(prim, def_id);
633 for &(def_id, prim, _) in &krate.primitives {
634 cache.primitive_locations.insert(prim, def_id);
637 cache.stack.push(krate.name.clone());
638 krate = cache.fold_crate(krate);
640 // Build our search index
641 let index = build_index(&krate, &mut cache);
643 // Freeze the cache now that the index has been built. Put an Arc into TLS
644 // for future parallelization opportunities
645 let cache = Arc::new(cache);
646 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
647 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
649 write_shared(&cx, &krate, &*cache, index)?;
651 // And finally render the whole crate's documentation
655 /// Build the search index from the collected metadata
656 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
657 let mut nodeid_to_pathid = FxHashMap();
658 let mut crate_items = Vec::with_capacity(cache.search_index.len());
659 let mut crate_paths = Vec::<Json>::new();
661 let Cache { ref mut search_index,
662 ref orphan_impl_items,
663 ref mut paths, .. } = *cache;
665 // Attach all orphan items to the type's definition if the type
666 // has since been learned.
667 for &(did, ref item) in orphan_impl_items {
668 if let Some(&(ref fqp, _)) = paths.get(&did) {
669 search_index.push(IndexItem {
671 name: item.name.clone().unwrap(),
672 path: fqp[..fqp.len() - 1].join("::"),
673 desc: plain_summary_line(item.doc_value()),
676 search_type: get_index_search_type(&item),
681 // Reduce `NodeId` in paths into smaller sequential numbers,
682 // and prune the paths that do not appear in the index.
683 let mut lastpath = String::new();
684 let mut lastpathid = 0usize;
686 for item in search_index {
687 item.parent_idx = item.parent.map(|nodeid| {
688 if nodeid_to_pathid.contains_key(&nodeid) {
689 *nodeid_to_pathid.get(&nodeid).unwrap()
691 let pathid = lastpathid;
692 nodeid_to_pathid.insert(nodeid, pathid);
695 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
696 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
701 // Omit the parent path if it is same to that of the prior item.
702 if lastpath == item.path {
705 lastpath = item.path.clone();
707 crate_items.push(item.to_json());
710 let crate_doc = krate.module.as_ref().map(|module| {
711 plain_summary_line(module.doc_value())
712 }).unwrap_or(String::new());
714 let mut crate_data = BTreeMap::new();
715 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
716 crate_data.insert("items".to_owned(), Json::Array(crate_items));
717 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
719 // Collect the index into a string
720 format!("searchIndex[{}] = {};",
721 as_json(&krate.name),
722 Json::Object(crate_data))
725 fn write_shared(cx: &Context,
726 krate: &clean::Crate,
728 search_index: String) -> 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(cx.dst.join("rustdoc.css"),
738 include_bytes!("static/rustdoc.css"))?;
740 // To avoid "main.css" to be overwritten, we'll first run over the received themes and only
741 // then we'll run over the "official" styles.
742 let mut themes: HashSet<String> = HashSet::new();
744 for entry in &cx.shared.themes {
745 let mut content = Vec::with_capacity(100000);
747 let mut f = try_err!(File::open(&entry), &entry);
748 try_err!(f.read_to_end(&mut content), &entry);
749 write(cx.dst.join(try_none!(entry.file_name(), &entry)), content.as_slice())?;
750 themes.insert(try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry).to_owned());
753 write(cx.dst.join("brush.svg"),
754 include_bytes!("static/brush.svg"))?;
755 write(cx.dst.join("main.css"),
756 include_bytes!("static/themes/main.css"))?;
757 themes.insert("main".to_owned());
758 write(cx.dst.join("dark.css"),
759 include_bytes!("static/themes/dark.css"))?;
760 themes.insert("dark".to_owned());
762 let mut themes: Vec<&String> = themes.iter().collect();
764 // To avoid theme switch latencies as much as possible, we put everything theme related
765 // at the beginning of the html files into another js file.
766 write(cx.dst.join("theme.js"), format!(
767 r#"var themes = document.getElementById("theme-choices");
768 var themePicker = document.getElementById("theme-picker");
769 themePicker.onclick = function() {{
770 if (themes.style.display === "block") {{
771 themes.style.display = "none";
772 themePicker.style.borderBottomRightRadius = "3px";
773 themePicker.style.borderBottomLeftRadius = "3px";
775 themes.style.display = "block";
776 themePicker.style.borderBottomRightRadius = "0";
777 themePicker.style.borderBottomLeftRadius = "0";
780 [{}].forEach(function(item) {{
781 var but = document.createElement('button');
782 but.innerHTML = item;
783 but.onclick = function(el) {{
784 switchTheme(currentTheme, mainTheme, item);
786 themes.appendChild(but);
789 .map(|s| format!("\"{}\"", s))
790 .collect::<Vec<String>>()
791 .join(",")).as_bytes())?;
793 write(cx.dst.join("main.js"), include_bytes!("static/main.js"))?;
794 write(cx.dst.join("storage.js"), include_bytes!("static/storage.js"))?;
796 if let Some(ref css) = cx.shared.css_file_extension {
797 let out = cx.dst.join("theme.css");
798 try_err!(fs::copy(css, out), css);
800 write(cx.dst.join("normalize.css"),
801 include_bytes!("static/normalize.css"))?;
802 write(cx.dst.join("FiraSans-Regular.woff"),
803 include_bytes!("static/FiraSans-Regular.woff"))?;
804 write(cx.dst.join("FiraSans-Medium.woff"),
805 include_bytes!("static/FiraSans-Medium.woff"))?;
806 write(cx.dst.join("FiraSans-LICENSE.txt"),
807 include_bytes!("static/FiraSans-LICENSE.txt"))?;
808 write(cx.dst.join("Heuristica-Italic.woff"),
809 include_bytes!("static/Heuristica-Italic.woff"))?;
810 write(cx.dst.join("Heuristica-LICENSE.txt"),
811 include_bytes!("static/Heuristica-LICENSE.txt"))?;
812 write(cx.dst.join("SourceSerifPro-Regular.woff"),
813 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
814 write(cx.dst.join("SourceSerifPro-Bold.woff"),
815 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
816 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
817 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
818 write(cx.dst.join("SourceCodePro-Regular.woff"),
819 include_bytes!("static/SourceCodePro-Regular.woff"))?;
820 write(cx.dst.join("SourceCodePro-Semibold.woff"),
821 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
822 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
823 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
824 write(cx.dst.join("LICENSE-MIT.txt"),
825 include_bytes!("static/LICENSE-MIT.txt"))?;
826 write(cx.dst.join("LICENSE-APACHE.txt"),
827 include_bytes!("static/LICENSE-APACHE.txt"))?;
828 write(cx.dst.join("COPYRIGHT.txt"),
829 include_bytes!("static/COPYRIGHT.txt"))?;
831 fn collect(path: &Path, krate: &str,
832 key: &str) -> io::Result<Vec<String>> {
833 let mut ret = Vec::new();
835 for line in BufReader::new(File::open(path)?).lines() {
837 if !line.starts_with(key) {
840 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
843 ret.push(line.to_string());
849 // Update the search index
850 let dst = cx.dst.join("search-index.js");
851 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
852 all_indexes.push(search_index);
853 // Sort the indexes by crate so the file will be generated identically even
854 // with rustdoc running in parallel.
856 let mut w = try_err!(File::create(&dst), &dst);
857 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
858 for index in &all_indexes {
859 try_err!(writeln!(&mut w, "{}", *index), &dst);
861 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
863 // Update the list of all implementors for traits
864 let dst = cx.dst.join("implementors");
865 for (&did, imps) in &cache.implementors {
866 // Private modules can leak through to this phase of rustdoc, which
867 // could contain implementations for otherwise private types. In some
868 // rare cases we could find an implementation for an item which wasn't
869 // indexed, so we just skip this step in that case.
871 // FIXME: this is a vague explanation for why this can't be a `get`, in
872 // theory it should be...
873 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
875 None => match cache.external_paths.get(&did) {
881 let mut have_impls = false;
882 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
884 // If the trait and implementation are in the same crate, then
885 // there's no need to emit information about it (there's inlining
886 // going on). If they're in different crates then the crate defining
887 // the trait will be interested in our implementation.
888 if imp.impl_item.def_id.krate == did.krate { continue }
889 // If the implementation is from another crate then that crate
891 if !imp.impl_item.def_id.is_local() { continue }
893 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
894 as_json(&imp.inner_impl().to_string()),
895 imp.inner_impl().synthetic,
896 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
898 implementors.push_str("];");
900 // Only create a js file if we have impls to add to it. If the trait is
901 // documented locally though we always create the file to avoid dead
903 if !have_impls && !cache.paths.contains_key(&did) {
907 let mut mydst = dst.clone();
908 for part in &remote_path[..remote_path.len() - 1] {
911 try_err!(fs::create_dir_all(&mydst), &mydst);
912 mydst.push(&format!("{}.{}.js",
913 remote_item_type.css_class(),
914 remote_path[remote_path.len() - 1]));
916 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
917 all_implementors.push(implementors);
918 // Sort the implementors by crate so the file will be generated
919 // identically even with rustdoc running in parallel.
920 all_implementors.sort();
922 let mut f = try_err!(File::create(&mydst), &mydst);
923 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
924 for implementor in &all_implementors {
925 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
927 try_err!(writeln!(&mut f, "{}", r"
928 if (window.register_implementors) {
929 window.register_implementors(implementors);
931 window.pending_implementors = implementors;
934 try_err!(writeln!(&mut f, r"}})()"), &mydst);
939 fn render_sources(dst: &Path, scx: &mut SharedContext,
940 krate: clean::Crate) -> Result<clean::Crate, Error> {
941 info!("emitting source files");
942 let dst = dst.join("src").join(&krate.name);
943 try_err!(fs::create_dir_all(&dst), &dst);
944 let mut folder = SourceCollector {
948 Ok(folder.fold_crate(krate))
951 /// Writes the entire contents of a string to a destination, not attempting to
952 /// catch any errors.
953 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
954 Ok(try_err!(fs::write(&dst, contents), &dst))
957 /// Takes a path to a source file and cleans the path to it. This canonicalizes
958 /// things like ".." to components which preserve the "top down" hierarchy of a
959 /// static HTML tree. Each component in the cleaned path will be passed as an
960 /// argument to `f`. The very last component of the path (ie the file name) will
961 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
962 // FIXME (#9639): The closure should deal with &[u8] instead of &str
963 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
964 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
967 // make it relative, if possible
968 let p = p.strip_prefix(src_root).unwrap_or(p);
970 let mut iter = p.components().peekable();
972 while let Some(c) = iter.next() {
973 if !keep_filename && iter.peek().is_none() {
978 Component::ParentDir => f("up"),
979 Component::Normal(c) => f(c.to_str().unwrap()),
985 /// Attempts to find where an external crate is located, given that we're
986 /// rendering in to the specified source destination.
987 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
988 // See if there's documentation generated into the local directory
989 let local_location = dst.join(&e.name);
990 if local_location.is_dir() {
994 // Failing that, see if there's an attribute specifying where to find this
997 .filter(|a| a.check_name("html_root_url"))
998 .filter_map(|a| a.value_str())
1000 let mut url = url.to_string();
1001 if !url.ends_with("/") {
1005 }).next().unwrap_or(Unknown) // Well, at least we tried.
1008 impl<'a> DocFolder for SourceCollector<'a> {
1009 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1010 // If we're including source files, and we haven't seen this file yet,
1011 // then we need to render it out to the filesystem.
1012 if self.scx.include_sources
1013 // skip all invalid or macro spans
1014 && item.source.filename.is_real()
1015 // skip non-local items
1016 && item.def_id.is_local() {
1018 // If it turns out that we couldn't read this file, then we probably
1019 // can't read any of the files (generating html output from json or
1020 // something like that), so just don't include sources for the
1021 // entire crate. The other option is maintaining this mapping on a
1022 // per-file basis, but that's probably not worth it...
1024 .include_sources = match self.emit_source(&item.source.filename) {
1027 println!("warning: source code was requested to be rendered, \
1028 but processing `{}` had an error: {}",
1029 item.source.filename, e);
1030 println!(" skipping rendering of source code");
1035 self.fold_item_recur(item)
1039 impl<'a> SourceCollector<'a> {
1040 /// Renders the given filename into its corresponding HTML source file.
1041 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1042 let p = match *filename {
1043 FileName::Real(ref file) => file,
1046 if self.scx.local_sources.contains_key(&**p) {
1047 // We've already emitted this source
1051 let contents = fs::read_string(&p)?;
1053 // Remove the utf-8 BOM if any
1054 let contents = if contents.starts_with("\u{feff}") {
1060 // Create the intermediate directories
1061 let mut cur = self.dst.clone();
1062 let mut root_path = String::from("../../");
1063 let mut href = String::new();
1064 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1065 cur.push(component);
1066 fs::create_dir_all(&cur).unwrap();
1067 root_path.push_str("../");
1068 href.push_str(component);
1071 let mut fname = p.file_name().expect("source has no filename")
1073 fname.push(".html");
1075 href.push_str(&fname.to_string_lossy());
1077 let mut w = BufWriter::new(File::create(&cur)?);
1078 let title = format!("{} -- source", cur.file_name().unwrap()
1079 .to_string_lossy());
1080 let desc = format!("Source to the Rust file `{}`.", filename);
1081 let page = layout::Page {
1083 css_class: "source",
1084 root_path: &root_path,
1086 keywords: BASIC_KEYWORDS,
1088 layout::render(&mut w, &self.scx.layout,
1089 &page, &(""), &Source(contents),
1090 self.scx.css_file_extension.is_some(),
1093 self.scx.local_sources.insert(p.clone(), href);
1098 impl DocFolder for Cache {
1099 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1100 // If this is a stripped module,
1101 // we don't want it or its children in the search index.
1102 let orig_stripped_mod = match item.inner {
1103 clean::StrippedItem(box clean::ModuleItem(..)) => {
1104 mem::replace(&mut self.stripped_mod, true)
1106 _ => self.stripped_mod,
1109 // If the impl is from a masked crate or references something from a
1110 // masked crate then remove it completely.
1111 if let clean::ImplItem(ref i) = item.inner {
1112 if self.masked_crates.contains(&item.def_id.krate) ||
1113 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1114 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1119 // Register any generics to their corresponding string. This is used
1120 // when pretty-printing types.
1121 if let Some(generics) = item.inner.generics() {
1122 self.generics(generics);
1125 // Propagate a trait method's documentation to all implementors of the
1127 if let clean::TraitItem(ref t) = item.inner {
1128 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1131 // Collect all the implementors of traits.
1132 if let clean::ImplItem(ref i) = item.inner {
1133 if let Some(did) = i.trait_.def_id() {
1134 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1135 impl_item: item.clone(),
1140 // Index this method for searching later on.
1141 if let Some(ref s) = item.name {
1142 let (parent, is_inherent_impl_item) = match item.inner {
1143 clean::StrippedItem(..) => ((None, None), false),
1144 clean::AssociatedConstItem(..) |
1145 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1146 // skip associated items in trait impls
1147 ((None, None), false)
1149 clean::AssociatedTypeItem(..) |
1150 clean::TyMethodItem(..) |
1151 clean::StructFieldItem(..) |
1152 clean::VariantItem(..) => {
1153 ((Some(*self.parent_stack.last().unwrap()),
1154 Some(&self.stack[..self.stack.len() - 1])),
1157 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1158 if self.parent_stack.is_empty() {
1159 ((None, None), false)
1161 let last = self.parent_stack.last().unwrap();
1163 let path = match self.paths.get(&did) {
1164 // The current stack not necessarily has correlation
1165 // for where the type was defined. On the other
1166 // hand, `paths` always has the right
1167 // information if present.
1168 Some(&(ref fqp, ItemType::Trait)) |
1169 Some(&(ref fqp, ItemType::Struct)) |
1170 Some(&(ref fqp, ItemType::Union)) |
1171 Some(&(ref fqp, ItemType::Enum)) =>
1172 Some(&fqp[..fqp.len() - 1]),
1173 Some(..) => Some(&*self.stack),
1176 ((Some(*last), path), true)
1179 _ => ((None, Some(&*self.stack)), false)
1183 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1184 debug_assert!(!item.is_stripped());
1186 // A crate has a module at its root, containing all items,
1187 // which should not be indexed. The crate-item itself is
1188 // inserted later on when serializing the search-index.
1189 if item.def_id.index != CRATE_DEF_INDEX {
1190 self.search_index.push(IndexItem {
1192 name: s.to_string(),
1193 path: path.join("::").to_string(),
1194 desc: plain_summary_line(item.doc_value()),
1197 search_type: get_index_search_type(&item),
1201 (Some(parent), None) if is_inherent_impl_item => {
1202 // We have a parent, but we don't know where they're
1203 // defined yet. Wait for later to index this item.
1204 self.orphan_impl_items.push((parent, item.clone()));
1210 // Keep track of the fully qualified path for this item.
1211 let pushed = match item.name {
1212 Some(ref n) if !n.is_empty() => {
1213 self.stack.push(n.to_string());
1220 clean::StructItem(..) | clean::EnumItem(..) |
1221 clean::TypedefItem(..) | clean::TraitItem(..) |
1222 clean::FunctionItem(..) | clean::ModuleItem(..) |
1223 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1224 clean::ConstantItem(..) | clean::StaticItem(..) |
1225 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1226 if !self.stripped_mod => {
1227 // Re-exported items mean that the same id can show up twice
1228 // in the rustdoc ast that we're looking at. We know,
1229 // however, that a re-exported item doesn't show up in the
1230 // `public_items` map, so we can skip inserting into the
1231 // paths map if there was already an entry present and we're
1232 // not a public item.
1234 !self.paths.contains_key(&item.def_id) ||
1235 self.access_levels.is_public(item.def_id)
1237 self.paths.insert(item.def_id,
1238 (self.stack.clone(), item.type_()));
1241 // Link variants to their parent enum because pages aren't emitted
1242 // for each variant.
1243 clean::VariantItem(..) if !self.stripped_mod => {
1244 let mut stack = self.stack.clone();
1246 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1249 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1250 self.paths.insert(item.def_id, (self.stack.clone(),
1257 // Maintain the parent stack
1258 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1259 let parent_pushed = match item.inner {
1260 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1261 clean::StructItem(..) | clean::UnionItem(..) => {
1262 self.parent_stack.push(item.def_id);
1263 self.parent_is_trait_impl = false;
1266 clean::ImplItem(ref i) => {
1267 self.parent_is_trait_impl = i.trait_.is_some();
1269 clean::ResolvedPath{ did, .. } => {
1270 self.parent_stack.push(did);
1274 let prim_did = t.primitive_type().and_then(|t| {
1275 self.primitive_locations.get(&t).cloned()
1279 self.parent_stack.push(did);
1290 // Once we've recursively found all the generics, hoard off all the
1291 // implementations elsewhere.
1292 let ret = self.fold_item_recur(item).and_then(|item| {
1293 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1294 // Figure out the id of this impl. This may map to a
1295 // primitive rather than always to a struct/enum.
1296 // Note: matching twice to restrict the lifetime of the `i` borrow.
1297 let mut dids = FxHashSet();
1298 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1300 clean::ResolvedPath { did, .. } |
1301 clean::BorrowedRef {
1302 type_: box clean::ResolvedPath { did, .. }, ..
1307 let did = t.primitive_type().and_then(|t| {
1308 self.primitive_locations.get(&t).cloned()
1311 if let Some(did) = did {
1317 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1318 for bound in generics {
1319 if let Some(did) = bound.def_id() {
1328 self.impls.entry(did).or_insert(vec![]).push(Impl {
1329 impl_item: item.clone(),
1338 if pushed { self.stack.pop().unwrap(); }
1339 if parent_pushed { self.parent_stack.pop().unwrap(); }
1340 self.stripped_mod = orig_stripped_mod;
1341 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1347 fn generics(&mut self, generics: &clean::Generics) {
1348 for param in &generics.params {
1349 if let clean::GenericParam::Type(ref typ) = *param {
1350 self.typarams.insert(typ.did, typ.name.clone());
1357 /// String representation of how to get back to the root path of the 'doc/'
1358 /// folder in terms of a relative URL.
1359 fn root_path(&self) -> String {
1360 repeat("../").take(self.current.len()).collect::<String>()
1363 /// Recurse in the directory structure and change the "root path" to make
1364 /// sure it always points to the top (relatively).
1365 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1366 F: FnOnce(&mut Context) -> T,
1369 panic!("Unexpected empty destination: {:?}", self.current);
1371 let prev = self.dst.clone();
1373 self.current.push(s);
1375 info!("Recursing into {}", self.dst.display());
1379 info!("Recursed; leaving {}", self.dst.display());
1381 // Go back to where we were at
1383 self.current.pop().unwrap();
1388 /// Main method for rendering a crate.
1390 /// This currently isn't parallelized, but it'd be pretty easy to add
1391 /// parallelization to this function.
1392 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1393 let mut item = match krate.module.take() {
1395 None => return Ok(()),
1397 item.name = Some(krate.name);
1399 // Render the crate documentation
1400 let mut work = vec![(self, item)];
1402 while let Some((mut cx, item)) = work.pop() {
1403 cx.item(item, |cx, item| {
1404 work.push((cx.clone(), item))
1410 fn render_item(&self,
1411 writer: &mut io::Write,
1415 // A little unfortunate that this is done like this, but it sure
1416 // does make formatting *a lot* nicer.
1417 CURRENT_LOCATION_KEY.with(|slot| {
1418 *slot.borrow_mut() = self.current.clone();
1421 let mut title = if it.is_primitive() {
1422 // No need to include the namespace for primitive types
1425 self.current.join("::")
1428 if !title.is_empty() {
1429 title.push_str("::");
1431 title.push_str(it.name.as_ref().unwrap());
1433 title.push_str(" - Rust");
1434 let tyname = it.type_().css_class();
1435 let desc = if it.is_crate() {
1436 format!("API documentation for the Rust `{}` crate.",
1437 self.shared.layout.krate)
1439 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1440 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1442 let keywords = make_item_keywords(it);
1443 let page = layout::Page {
1445 root_path: &self.root_path(),
1448 keywords: &keywords,
1453 if !self.render_redirect_pages {
1454 layout::render(writer, &self.shared.layout, &page,
1455 &Sidebar{ cx: self, item: it },
1456 &Item{ cx: self, item: it },
1457 self.shared.css_file_extension.is_some(),
1458 &self.shared.themes)?;
1460 let mut url = self.root_path();
1461 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1462 for name in &names[..names.len() - 1] {
1466 url.push_str(&item_path(ty, names.last().unwrap()));
1467 layout::redirect(writer, &url)?;
1473 /// Non-parallelized version of rendering an item. This will take the input
1474 /// item, render its contents, and then invoke the specified closure with
1475 /// all sub-items which need to be rendered.
1477 /// The rendering driver uses this closure to queue up more work.
1478 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1479 F: FnMut(&mut Context, clean::Item),
1481 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1482 // if they contain impls for public types. These modules can also
1483 // contain items such as publicly re-exported structures.
1485 // External crates will provide links to these structures, so
1486 // these modules are recursed into, but not rendered normally
1487 // (a flag on the context).
1488 if !self.render_redirect_pages {
1489 self.render_redirect_pages = item.is_stripped();
1493 // modules are special because they add a namespace. We also need to
1494 // recurse into the items of the module as well.
1495 let name = item.name.as_ref().unwrap().to_string();
1496 let mut item = Some(item);
1497 self.recurse(name, |this| {
1498 let item = item.take().unwrap();
1500 let mut buf = Vec::new();
1501 this.render_item(&mut buf, &item, false).unwrap();
1502 // buf will be empty if the module is stripped and there is no redirect for it
1503 if !buf.is_empty() {
1504 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1505 let joint_dst = this.dst.join("index.html");
1506 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1507 try_err!(dst.write_all(&buf), &joint_dst);
1510 let m = match item.inner {
1511 clean::StrippedItem(box clean::ModuleItem(m)) |
1512 clean::ModuleItem(m) => m,
1516 // Render sidebar-items.js used throughout this module.
1517 if !this.render_redirect_pages {
1518 let items = this.build_sidebar_items(&m);
1519 let js_dst = this.dst.join("sidebar-items.js");
1520 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1521 try_err!(write!(&mut js_out, "initSidebarItems({});",
1522 as_json(&items)), &js_dst);
1525 for item in m.items {
1531 } else if item.name.is_some() {
1532 let mut buf = Vec::new();
1533 self.render_item(&mut buf, &item, true).unwrap();
1534 // buf will be empty if the item is stripped and there is no redirect for it
1535 if !buf.is_empty() {
1536 let name = item.name.as_ref().unwrap();
1537 let item_type = item.type_();
1538 let file_name = &item_path(item_type, name);
1539 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1540 let joint_dst = self.dst.join(file_name);
1541 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1542 try_err!(dst.write_all(&buf), &joint_dst);
1544 // Redirect from a sane URL using the namespace to Rustdoc's
1545 // URL for the page.
1546 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1547 let redir_dst = self.dst.join(redir_name);
1548 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1551 let mut redirect_out = BufWriter::new(redirect_out);
1552 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1555 // If the item is a macro, redirect from the old macro URL (with !)
1556 // to the new one (without).
1557 // FIXME(#35705) remove this redirect.
1558 if item_type == ItemType::Macro {
1559 let redir_name = format!("{}.{}!.html", item_type, name);
1560 let redir_dst = self.dst.join(redir_name);
1561 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1562 let mut redirect_out = BufWriter::new(redirect_out);
1563 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1570 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1571 // BTreeMap instead of HashMap to get a sorted output
1572 let mut map = BTreeMap::new();
1573 for item in &m.items {
1574 if item.is_stripped() { continue }
1576 let short = item.type_().css_class();
1577 let myname = match item.name {
1579 Some(ref s) => s.to_string(),
1581 let short = short.to_string();
1582 map.entry(short).or_insert(vec![])
1583 .push((myname, Some(plain_summary_line(item.doc_value()))));
1586 if self.shared.sort_modules_alphabetically {
1587 for (_, items) in &mut map {
1596 /// Generate a url appropriate for an `href` attribute back to the source of
1599 /// The url generated, when clicked, will redirect the browser back to the
1600 /// original source code.
1602 /// If `None` is returned, then a source link couldn't be generated. This
1603 /// may happen, for example, with externally inlined items where the source
1604 /// of their crate documentation isn't known.
1605 fn src_href(&self) -> Option<String> {
1606 let mut root = self.cx.root_path();
1608 let cache = cache();
1609 let mut path = String::new();
1611 // We can safely ignore macros from other libraries
1612 let file = match self.item.source.filename {
1613 FileName::Real(ref path) => path,
1617 let (krate, path) = if self.item.def_id.is_local() {
1618 if let Some(path) = self.cx.shared.local_sources.get(file) {
1619 (&self.cx.shared.layout.krate, path)
1624 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1625 Some(&(ref name, ref src, Local)) => (name, src),
1626 Some(&(ref name, ref src, Remote(ref s))) => {
1627 root = s.to_string();
1630 Some(&(_, _, Unknown)) | None => return None,
1633 clean_srcpath(&src_root, file, false, |component| {
1634 path.push_str(component);
1637 let mut fname = file.file_name().expect("source has no filename")
1639 fname.push(".html");
1640 path.push_str(&fname.to_string_lossy());
1644 let lines = if self.item.source.loline == self.item.source.hiline {
1645 format!("{}", self.item.source.loline)
1647 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1649 Some(format!("{root}src/{krate}/{path}#{lines}",
1650 root = Escape(&root),
1657 impl<'a> fmt::Display for Item<'a> {
1658 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1659 debug_assert!(!self.item.is_stripped());
1660 // Write the breadcrumb trail header for the top
1661 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1662 match self.item.inner {
1663 clean::ModuleItem(ref m) => if m.is_crate {
1664 write!(fmt, "Crate ")?;
1666 write!(fmt, "Module ")?;
1668 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1669 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1670 clean::StructItem(..) => write!(fmt, "Struct ")?,
1671 clean::UnionItem(..) => write!(fmt, "Union ")?,
1672 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1673 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1674 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1675 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1676 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1677 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1678 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1680 // We don't generate pages for any other type.
1684 if !self.item.is_primitive() {
1685 let cur = &self.cx.current;
1686 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1687 for (i, component) in cur.iter().enumerate().take(amt) {
1688 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1689 repeat("../").take(cur.len() - i - 1)
1690 .collect::<String>(),
1694 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1695 self.item.type_(), self.item.name.as_ref().unwrap())?;
1697 write!(fmt, "</span>")?; // in-band
1698 write!(fmt, "<span class='out-of-band'>")?;
1699 if let Some(version) = self.item.stable_since() {
1700 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1704 r##"<span id='render-detail'>
1705 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1706 [<span class='inner'>−</span>]
1712 // When this item is part of a `pub use` in a downstream crate, the
1713 // [src] link in the downstream documentation will actually come back to
1714 // this page, and this link will be auto-clicked. The `id` attribute is
1715 // used to find the link to auto-click.
1716 if self.cx.shared.include_sources && !self.item.is_primitive() {
1717 if let Some(l) = self.src_href() {
1718 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1719 l, "goto source code")?;
1723 write!(fmt, "</span>")?; // out-of-band
1725 write!(fmt, "</h1>\n")?;
1727 match self.item.inner {
1728 clean::ModuleItem(ref m) => {
1729 item_module(fmt, self.cx, self.item, &m.items)
1731 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1732 item_function(fmt, self.cx, self.item, f),
1733 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1734 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1735 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1736 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1737 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1738 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1739 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1740 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1741 item_static(fmt, self.cx, self.item, i),
1742 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1743 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1745 // We don't generate pages for any other type.
1752 fn item_path(ty: ItemType, name: &str) -> String {
1754 ItemType::Module => format!("{}/index.html", name),
1755 _ => format!("{}.{}.html", ty.css_class(), name),
1759 fn full_path(cx: &Context, item: &clean::Item) -> String {
1760 let mut s = cx.current.join("::");
1762 s.push_str(item.name.as_ref().unwrap());
1766 fn shorter<'a>(s: Option<&'a str>) -> String {
1768 Some(s) => s.lines()
1769 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1771 (*line).chars().any(|chr|{
1772 !chr.is_whitespace()
1774 }).collect::<Vec<_>>().join("\n"),
1775 None => "".to_string()
1780 fn plain_summary_line(s: Option<&str>) -> String {
1781 let line = shorter(s).replace("\n", " ");
1782 markdown::plain_summary_line(&line[..])
1785 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1786 if let Some(ref name) = item.name {
1787 info!("Documenting {}", name);
1789 document_stability(w, cx, item)?;
1790 let prefix = render_assoc_const_value(item);
1791 document_full(w, item, cx, &prefix)?;
1795 /// Render md_text as markdown.
1796 fn render_markdown(w: &mut fmt::Formatter,
1798 links: Vec<(String, String)>,
1801 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1804 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1805 prefix: &str) -> fmt::Result {
1806 if let Some(s) = item.doc_value() {
1807 let markdown = if s.contains('\n') {
1808 format!("{} [Read more]({})",
1809 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1811 format!("{}", &plain_summary_line(Some(s)))
1813 render_markdown(w, &markdown, item.links(), prefix)?;
1814 } else if !prefix.is_empty() {
1815 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1820 fn render_assoc_const_value(item: &clean::Item) -> String {
1822 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1823 highlight::render_with_highlighting(
1824 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1835 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1836 cx: &Context, prefix: &str) -> fmt::Result {
1837 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1838 debug!("Doc block: =====\n{}\n=====", s);
1839 render_markdown(w, &*s, item.links(), prefix)?;
1840 } else if !prefix.is_empty() {
1841 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1846 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1847 let stabilities = short_stability(item, cx, true);
1848 if !stabilities.is_empty() {
1849 write!(w, "<div class='stability'>")?;
1850 for stability in stabilities {
1851 write!(w, "{}", stability)?;
1853 write!(w, "</div>")?;
1858 fn name_key(name: &str) -> (&str, u64, usize) {
1859 // find number at end
1860 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1862 // count leading zeroes
1864 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1866 // sort leading zeroes last
1867 let num_zeroes = after_zeroes - split;
1869 match name[split..].parse() {
1870 Ok(n) => (&name[..split], n, num_zeroes),
1871 Err(_) => (name, 0, num_zeroes),
1875 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1876 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1877 document(w, cx, item)?;
1879 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1881 // the order of item types in the listing
1882 fn reorder(ty: ItemType) -> u8 {
1884 ItemType::ExternCrate => 0,
1885 ItemType::Import => 1,
1886 ItemType::Primitive => 2,
1887 ItemType::Module => 3,
1888 ItemType::Macro => 4,
1889 ItemType::Struct => 5,
1890 ItemType::Enum => 6,
1891 ItemType::Constant => 7,
1892 ItemType::Static => 8,
1893 ItemType::Trait => 9,
1894 ItemType::Function => 10,
1895 ItemType::Typedef => 12,
1896 ItemType::Union => 13,
1901 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1902 let ty1 = i1.type_();
1903 let ty2 = i2.type_();
1905 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1907 let s1 = i1.stability.as_ref().map(|s| s.level);
1908 let s2 = i2.stability.as_ref().map(|s| s.level);
1910 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1911 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1914 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1915 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1916 name_key(lhs).cmp(&name_key(rhs))
1919 if cx.shared.sort_modules_alphabetically {
1920 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1922 // This call is to remove re-export duplicates in cases such as:
1927 // pub trait Double { fn foo(); }
1931 // pub use foo::bar::*;
1935 // `Double` will appear twice in the generated docs.
1937 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1938 // can be identical even if the elements are different (mostly in imports).
1939 // So in case this is an import, we keep everything by adding a "unique id"
1940 // (which is the position in the vector).
1941 indices.dedup_by_key(|i| (items[*i].def_id,
1942 if items[*i].name.as_ref().is_some() {
1943 Some(full_path(cx, &items[*i]).clone())
1948 if items[*i].is_import() {
1954 debug!("{:?}", indices);
1955 let mut curty = None;
1956 for &idx in &indices {
1957 let myitem = &items[idx];
1958 if myitem.is_stripped() {
1962 let myty = Some(myitem.type_());
1963 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1964 // Put `extern crate` and `use` re-exports in the same section.
1966 } else if myty != curty {
1967 if curty.is_some() {
1968 write!(w, "</table>")?;
1971 let (short, name) = match myty.unwrap() {
1972 ItemType::ExternCrate |
1973 ItemType::Import => ("reexports", "Re-exports"),
1974 ItemType::Module => ("modules", "Modules"),
1975 ItemType::Struct => ("structs", "Structs"),
1976 ItemType::Union => ("unions", "Unions"),
1977 ItemType::Enum => ("enums", "Enums"),
1978 ItemType::Function => ("functions", "Functions"),
1979 ItemType::Typedef => ("types", "Type Definitions"),
1980 ItemType::Static => ("statics", "Statics"),
1981 ItemType::Constant => ("constants", "Constants"),
1982 ItemType::Trait => ("traits", "Traits"),
1983 ItemType::Impl => ("impls", "Implementations"),
1984 ItemType::TyMethod => ("tymethods", "Type Methods"),
1985 ItemType::Method => ("methods", "Methods"),
1986 ItemType::StructField => ("fields", "Struct Fields"),
1987 ItemType::Variant => ("variants", "Variants"),
1988 ItemType::Macro => ("macros", "Macros"),
1989 ItemType::Primitive => ("primitives", "Primitive Types"),
1990 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1991 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1992 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
1994 write!(w, "<h2 id='{id}' class='section-header'>\
1995 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1996 id = derive_id(short.to_owned()), name = name)?;
1999 match myitem.inner {
2000 clean::ExternCrateItem(ref name, ref src) => {
2001 use html::format::HRef;
2005 write!(w, "<tr><td><code>{}extern crate {} as {};",
2006 VisSpace(&myitem.visibility),
2007 HRef::new(myitem.def_id, src),
2011 write!(w, "<tr><td><code>{}extern crate {};",
2012 VisSpace(&myitem.visibility),
2013 HRef::new(myitem.def_id, name))?
2016 write!(w, "</code></td></tr>")?;
2019 clean::ImportItem(ref import) => {
2020 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2021 VisSpace(&myitem.visibility), *import)?;
2025 if myitem.name.is_none() { continue }
2027 let stabilities = short_stability(myitem, cx, false);
2029 let stab_docs = if !stabilities.is_empty() {
2031 .map(|s| format!("[{}]", s))
2032 .collect::<Vec<_>>()
2039 let unsafety_flag = match myitem.inner {
2040 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2041 if func.unsafety == hir::Unsafety::Unsafe => {
2042 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2047 let doc_value = myitem.doc_value().unwrap_or("");
2049 <tr class='{stab} module-item'>
2050 <td><a class=\"{class}\" href=\"{href}\"
2051 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2052 <td class='docblock-short'>
2056 name = *myitem.name.as_ref().unwrap(),
2057 stab_docs = stab_docs,
2058 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2059 class = myitem.type_(),
2060 stab = myitem.stability_class().unwrap_or("".to_string()),
2061 unsafety_flag = unsafety_flag,
2062 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2063 title_type = myitem.type_(),
2064 title = full_path(cx, myitem))?;
2069 if curty.is_some() {
2070 write!(w, "</table>")?;
2075 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2076 let mut stability = vec![];
2078 if let Some(stab) = item.stability.as_ref() {
2079 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2080 format!(": {}", stab.deprecated_reason)
2084 if !stab.deprecated_since.is_empty() {
2085 let since = if show_reason {
2086 format!(" since {}", Escape(&stab.deprecated_since))
2090 let text = format!("Deprecated{}{}",
2092 MarkdownHtml(&deprecated_reason));
2093 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2096 if stab.level == stability::Unstable {
2098 let unstable_extra = match (!stab.feature.is_empty(),
2099 &cx.shared.issue_tracker_base_url,
2101 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2102 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2103 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2104 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2105 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2108 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2111 if stab.unstable_reason.is_empty() {
2112 stability.push(format!("<div class='stab unstable'>\
2113 <span class=microscope>🔬</span> \
2114 This is a nightly-only experimental API. {}\
2118 let text = format!("<summary><span class=microscope>🔬</span> \
2119 This is a nightly-only experimental API. {}\
2122 MarkdownHtml(&stab.unstable_reason));
2123 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2127 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2130 } else if let Some(depr) = item.deprecation.as_ref() {
2131 let note = if show_reason && !depr.note.is_empty() {
2132 format!(": {}", depr.note)
2136 let since = if show_reason && !depr.since.is_empty() {
2137 format!(" since {}", Escape(&depr.since))
2142 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e));
2143 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2146 if let Some(ref cfg) = item.attrs.cfg {
2147 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2148 cfg.render_long_html()
2150 cfg.render_short_html()
2157 struct Initializer<'a>(&'a str);
2159 impl<'a> fmt::Display for Initializer<'a> {
2160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2161 let Initializer(s) = *self;
2162 if s.is_empty() { return Ok(()); }
2163 write!(f, "<code> = </code>")?;
2164 write!(f, "<code>{}</code>", Escape(s))
2168 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2169 c: &clean::Constant) -> fmt::Result {
2170 write!(w, "<pre class='rust const'>")?;
2171 render_attributes(w, it)?;
2172 write!(w, "{vis}const \
2173 {name}: {typ}{init}</pre>",
2174 vis = VisSpace(&it.visibility),
2175 name = it.name.as_ref().unwrap(),
2177 init = Initializer(&c.expr))?;
2181 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2182 s: &clean::Static) -> fmt::Result {
2183 write!(w, "<pre class='rust static'>")?;
2184 render_attributes(w, it)?;
2185 write!(w, "{vis}static {mutability}\
2186 {name}: {typ}{init}</pre>",
2187 vis = VisSpace(&it.visibility),
2188 mutability = MutableSpace(s.mutability),
2189 name = it.name.as_ref().unwrap(),
2191 init = Initializer(&s.expr))?;
2195 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2196 f: &clean::Function) -> fmt::Result {
2197 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2198 VisSpace(&it.visibility),
2199 ConstnessSpace(f.constness),
2200 UnsafetySpace(f.unsafety),
2202 it.name.as_ref().unwrap(),
2204 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2205 render_attributes(w, it)?;
2207 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2208 vis = VisSpace(&it.visibility),
2209 constness = ConstnessSpace(f.constness),
2210 unsafety = UnsafetySpace(f.unsafety),
2211 abi = AbiSpace(f.abi),
2212 name = it.name.as_ref().unwrap(),
2213 generics = f.generics,
2214 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2223 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2224 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2226 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2227 write!(w, "<div class='out-of-band'>")?;
2228 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2229 l, "goto source code")?;
2230 write!(w, "</div>")?;
2232 write!(w, "<code>")?;
2233 // If there's already another implementor that has the same abbridged name, use the
2234 // full path, for example in `std::iter::ExactSizeIterator`
2235 let use_absolute = match implementor.inner_impl().for_ {
2236 clean::ResolvedPath { ref path, is_generic: false, .. } |
2237 clean::BorrowedRef {
2238 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2240 } => implementor_dups[path.last_name()].1,
2243 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2244 for it in &implementor.inner_impl().items {
2245 if let clean::TypedefItem(ref tydef, _) = it.inner {
2246 write!(w, "<span class=\"where fmt-newline\"> ")?;
2247 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2248 write!(w, ";</span>")?;
2251 writeln!(w, "</code></li>")?;
2255 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2256 traits: Vec<&&Impl>,
2257 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2259 let did = i.trait_did().unwrap();
2260 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2261 render_impl(w, cx, i, assoc_link,
2262 RenderMode::Normal, containing_item.stable_since(), true)?;
2267 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2268 t: &clean::Trait) -> fmt::Result {
2269 let mut bounds = String::new();
2270 let mut bounds_plain = String::new();
2271 if !t.bounds.is_empty() {
2272 if !bounds.is_empty() {
2274 bounds_plain.push(' ');
2276 bounds.push_str(": ");
2277 bounds_plain.push_str(": ");
2278 for (i, p) in t.bounds.iter().enumerate() {
2280 bounds.push_str(" + ");
2281 bounds_plain.push_str(" + ");
2283 bounds.push_str(&format!("{}", *p));
2284 bounds_plain.push_str(&format!("{:#}", *p));
2288 // Output the trait definition
2289 write!(w, "<pre class='rust trait'>")?;
2290 render_attributes(w, it)?;
2291 write!(w, "{}{}{}trait {}{}{}",
2292 VisSpace(&it.visibility),
2293 UnsafetySpace(t.unsafety),
2294 if t.is_auto { "auto " } else { "" },
2295 it.name.as_ref().unwrap(),
2299 if !t.generics.where_predicates.is_empty() {
2300 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2305 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2306 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2307 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2308 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2310 if t.items.is_empty() {
2311 write!(w, "{{ }}")?;
2313 // FIXME: we should be using a derived_id for the Anchors here
2317 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2320 if !types.is_empty() && !consts.is_empty() {
2325 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2328 if !consts.is_empty() && !required.is_empty() {
2331 for (pos, m) in required.iter().enumerate() {
2333 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2336 if pos < required.len() - 1 {
2337 write!(w, "<div class='item-spacer'></div>")?;
2340 if !required.is_empty() && !provided.is_empty() {
2343 for (pos, m) in provided.iter().enumerate() {
2345 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2347 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2348 write!(w, ",\n {{ ... }}\n")?;
2351 write!(w, " {{ ... }}\n")?;
2354 if pos < provided.len() - 1 {
2355 write!(w, "<div class='item-spacer'></div>")?;
2360 write!(w, "</pre>")?;
2362 // Trait documentation
2363 document(w, cx, it)?;
2365 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2367 let name = m.name.as_ref().unwrap();
2368 let item_type = m.type_();
2369 let id = derive_id(format!("{}.{}", item_type, name));
2370 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2371 write!(w, "{extra}<h3 id='{id}' class='method'>\
2372 <span id='{ns_id}' class='invisible'><code>",
2373 extra = render_spotlight_traits(m)?,
2376 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2377 write!(w, "</code>")?;
2378 render_stability_since(w, m, t)?;
2379 write!(w, "</span></h3>")?;
2380 document(w, cx, m)?;
2384 if !types.is_empty() {
2386 <h2 id='associated-types' class='small-section-header'>
2387 Associated Types<a href='#associated-types' class='anchor'></a>
2389 <div class='methods'>
2392 trait_item(w, cx, *t, it)?;
2394 write!(w, "</div>")?;
2397 if !consts.is_empty() {
2399 <h2 id='associated-const' class='small-section-header'>
2400 Associated Constants<a href='#associated-const' class='anchor'></a>
2402 <div class='methods'>
2405 trait_item(w, cx, *t, it)?;
2407 write!(w, "</div>")?;
2410 // Output the documentation for each function individually
2411 if !required.is_empty() {
2413 <h2 id='required-methods' class='small-section-header'>
2414 Required Methods<a href='#required-methods' class='anchor'></a>
2416 <div class='methods'>
2418 for m in &required {
2419 trait_item(w, cx, *m, it)?;
2421 write!(w, "</div>")?;
2423 if !provided.is_empty() {
2425 <h2 id='provided-methods' class='small-section-header'>
2426 Provided Methods<a href='#provided-methods' class='anchor'></a>
2428 <div class='methods'>
2430 for m in &provided {
2431 trait_item(w, cx, *m, it)?;
2433 write!(w, "</div>")?;
2436 // If there are methods directly on this trait object, render them here.
2437 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2439 let cache = cache();
2441 <h2 id='implementors' class='small-section-header'>
2442 Implementors<a href='#implementors' class='anchor'></a>
2444 <ul class='item-list' id='implementors-list'>
2447 let synthetic_impl_header = "
2448 <h2 id='synthetic-implementors' class='small-section-header'>
2449 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2451 <ul class='item-list' id='synthetic-implementors-list'>
2454 let mut synthetic_types = Vec::new();
2456 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2457 // The DefId is for the first Type found with that name. The bool is
2458 // if any Types with the same name but different DefId have been found.
2459 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2460 for implementor in implementors {
2461 match implementor.inner_impl().for_ {
2462 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2463 clean::BorrowedRef {
2464 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2467 let &mut (prev_did, ref mut has_duplicates) =
2468 implementor_dups.entry(path.last_name()).or_insert((did, false));
2469 if prev_did != did {
2470 *has_duplicates = true;
2477 let (local, foreign) = implementors.iter()
2478 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2479 .map_or(true, |d| cache.paths.contains_key(&d)));
2482 let (synthetic, concrete) = local.iter()
2483 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2486 if !foreign.is_empty() {
2488 <h2 id='foreign-impls' class='small-section-header'>
2489 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2493 for implementor in foreign {
2494 let assoc_link = AssocItemLink::GotoSource(
2495 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2497 render_impl(w, cx, &implementor, assoc_link,
2498 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2502 write!(w, "{}", impl_header)?;
2503 for implementor in concrete {
2504 render_implementor(cx, implementor, w, &implementor_dups)?;
2506 write!(w, "</ul>")?;
2509 write!(w, "{}", synthetic_impl_header)?;
2510 for implementor in synthetic {
2511 synthetic_types.extend(
2512 collect_paths_for_type(implementor.inner_impl().for_.clone())
2514 render_implementor(cx, implementor, w, &implementor_dups)?;
2516 write!(w, "</ul>")?;
2519 // even without any implementations to write in, we still want the heading and list, so the
2520 // implementors javascript file pulled in below has somewhere to write the impls into
2521 write!(w, "{}", impl_header)?;
2522 write!(w, "</ul>")?;
2525 write!(w, "{}", synthetic_impl_header)?;
2526 write!(w, "</ul>")?;
2529 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2530 as_json(&synthetic_types))?;
2532 write!(w, r#"<script type="text/javascript" async
2533 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2535 root_path = vec![".."; cx.current.len()].join("/"),
2536 path = if it.def_id.is_local() {
2537 cx.current.join("/")
2539 let (ref path, _) = cache.external_paths[&it.def_id];
2540 path[..path.len() - 1].join("/")
2542 ty = it.type_().css_class(),
2543 name = *it.name.as_ref().unwrap())?;
2547 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2548 use html::item_type::ItemType::*;
2550 let name = it.name.as_ref().unwrap();
2551 let ty = match it.type_() {
2552 Typedef | AssociatedType => AssociatedType,
2556 let anchor = format!("#{}.{}", ty, name);
2558 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2559 AssocItemLink::Anchor(None) => anchor,
2560 AssocItemLink::GotoSource(did, _) => {
2561 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2566 fn assoc_const(w: &mut fmt::Formatter,
2569 _default: Option<&String>,
2570 link: AssocItemLink) -> fmt::Result {
2571 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2572 VisSpace(&it.visibility),
2573 naive_assoc_href(it, link),
2574 it.name.as_ref().unwrap(),
2579 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2580 bounds: &Vec<clean::TyParamBound>,
2581 default: Option<&clean::Type>,
2582 link: AssocItemLink) -> fmt::Result {
2583 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2584 naive_assoc_href(it, link),
2585 it.name.as_ref().unwrap())?;
2586 if !bounds.is_empty() {
2587 write!(w, ": {}", TyParamBounds(bounds))?
2589 if let Some(default) = default {
2590 write!(w, " = {}", default)?;
2595 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2596 ver: Option<&'a str>,
2597 containing_ver: Option<&'a str>) -> fmt::Result {
2598 if let Some(v) = ver {
2599 if containing_ver != ver && v.len() > 0 {
2600 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2607 fn render_stability_since(w: &mut fmt::Formatter,
2609 containing_item: &clean::Item) -> fmt::Result {
2610 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2613 fn render_assoc_item(w: &mut fmt::Formatter,
2615 link: AssocItemLink,
2616 parent: ItemType) -> fmt::Result {
2617 fn method(w: &mut fmt::Formatter,
2619 unsafety: hir::Unsafety,
2620 constness: hir::Constness,
2622 g: &clean::Generics,
2624 link: AssocItemLink,
2627 let name = meth.name.as_ref().unwrap();
2628 let anchor = format!("#{}.{}", meth.type_(), name);
2629 let href = match link {
2630 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2631 AssocItemLink::Anchor(None) => anchor,
2632 AssocItemLink::GotoSource(did, provided_methods) => {
2633 // We're creating a link from an impl-item to the corresponding
2634 // trait-item and need to map the anchored type accordingly.
2635 let ty = if provided_methods.contains(name) {
2641 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2644 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2645 VisSpace(&meth.visibility),
2646 ConstnessSpace(constness),
2647 UnsafetySpace(unsafety),
2651 let (indent, end_newline) = if parent == ItemType::Trait {
2657 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2658 {generics}{decl}{where_clause}",
2659 VisSpace(&meth.visibility),
2660 ConstnessSpace(constness),
2661 UnsafetySpace(unsafety),
2671 where_clause = WhereClause {
2678 clean::StrippedItem(..) => Ok(()),
2679 clean::TyMethodItem(ref m) => {
2680 method(w, item, m.unsafety, hir::Constness::NotConst,
2681 m.abi, &m.generics, &m.decl, link, parent)
2683 clean::MethodItem(ref m) => {
2684 method(w, item, m.unsafety, m.constness,
2685 m.abi, &m.generics, &m.decl, link, parent)
2687 clean::AssociatedConstItem(ref ty, ref default) => {
2688 assoc_const(w, item, ty, default.as_ref(), link)
2690 clean::AssociatedTypeItem(ref bounds, ref default) => {
2691 assoc_type(w, item, bounds, default.as_ref(), link)
2693 _ => panic!("render_assoc_item called on non-associated-item")
2697 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2698 s: &clean::Struct) -> fmt::Result {
2699 write!(w, "<pre class='rust struct'>")?;
2700 render_attributes(w, it)?;
2708 write!(w, "</pre>")?;
2710 document(w, cx, it)?;
2711 let mut fields = s.fields.iter().filter_map(|f| {
2713 clean::StructFieldItem(ref ty) => Some((f, ty)),
2717 if let doctree::Plain = s.struct_type {
2718 if fields.peek().is_some() {
2719 write!(w, "<h2 id='fields' class='fields small-section-header'>
2720 Fields<a href='#fields' class='anchor'></a></h2>")?;
2721 for (field, ty) in fields {
2722 let id = derive_id(format!("{}.{}",
2723 ItemType::StructField,
2724 field.name.as_ref().unwrap()));
2725 let ns_id = derive_id(format!("{}.{}",
2726 field.name.as_ref().unwrap(),
2727 ItemType::StructField.name_space()));
2728 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2729 <a href=\"#{id}\" class=\"anchor field\"></a>
2730 <span id=\"{ns_id}\" class='invisible'>
2731 <code>{name}: {ty}</code>
2733 item_type = ItemType::StructField,
2736 name = field.name.as_ref().unwrap(),
2738 if let Some(stability_class) = field.stability_class() {
2739 write!(w, "<span class='stab {stab}'></span>",
2740 stab = stability_class)?;
2742 document(w, cx, field)?;
2746 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2749 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2750 s: &clean::Union) -> fmt::Result {
2751 write!(w, "<pre class='rust union'>")?;
2752 render_attributes(w, it)?;
2759 write!(w, "</pre>")?;
2761 document(w, cx, it)?;
2762 let mut fields = s.fields.iter().filter_map(|f| {
2764 clean::StructFieldItem(ref ty) => Some((f, ty)),
2768 if fields.peek().is_some() {
2769 write!(w, "<h2 id='fields' class='fields small-section-header'>
2770 Fields<a href='#fields' class='anchor'></a></h2>")?;
2771 for (field, ty) in fields {
2772 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2774 shortty = ItemType::StructField,
2775 name = field.name.as_ref().unwrap(),
2777 if let Some(stability_class) = field.stability_class() {
2778 write!(w, "<span class='stab {stab}'></span>",
2779 stab = stability_class)?;
2781 document(w, cx, field)?;
2784 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2787 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2788 e: &clean::Enum) -> fmt::Result {
2789 write!(w, "<pre class='rust enum'>")?;
2790 render_attributes(w, it)?;
2791 write!(w, "{}enum {}{}{}",
2792 VisSpace(&it.visibility),
2793 it.name.as_ref().unwrap(),
2795 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2796 if e.variants.is_empty() && !e.variants_stripped {
2797 write!(w, " {{}}")?;
2799 write!(w, " {{\n")?;
2800 for v in &e.variants {
2802 let name = v.name.as_ref().unwrap();
2804 clean::VariantItem(ref var) => {
2806 clean::VariantKind::CLike => write!(w, "{}", name)?,
2807 clean::VariantKind::Tuple(ref tys) => {
2808 write!(w, "{}(", name)?;
2809 for (i, ty) in tys.iter().enumerate() {
2811 write!(w, ", ")?
2813 write!(w, "{}", *ty)?;
2817 clean::VariantKind::Struct(ref s) => {
2833 if e.variants_stripped {
2834 write!(w, " // some variants omitted\n")?;
2838 write!(w, "</pre>")?;
2840 document(w, cx, it)?;
2841 if !e.variants.is_empty() {
2842 write!(w, "<h2 id='variants' class='variants small-section-header'>
2843 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2844 for variant in &e.variants {
2845 let id = derive_id(format!("{}.{}",
2847 variant.name.as_ref().unwrap()));
2848 let ns_id = derive_id(format!("{}.{}",
2849 variant.name.as_ref().unwrap(),
2850 ItemType::Variant.name_space()));
2851 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2852 <a href=\"#{id}\" class=\"anchor field\"></a>\
2853 <span id='{ns_id}' class='invisible'><code>{name}",
2856 name = variant.name.as_ref().unwrap())?;
2857 if let clean::VariantItem(ref var) = variant.inner {
2858 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2860 for (i, ty) in tys.iter().enumerate() {
2862 write!(w, ", ")?;
2864 write!(w, "{}", *ty)?;
2869 write!(w, "</code></span></span>")?;
2870 document(w, cx, variant)?;
2872 use clean::{Variant, VariantKind};
2873 if let clean::VariantItem(Variant {
2874 kind: VariantKind::Struct(ref s)
2875 }) = variant.inner {
2876 let variant_id = derive_id(format!("{}.{}.fields",
2878 variant.name.as_ref().unwrap()));
2879 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2881 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2882 <table>", name = variant.name.as_ref().unwrap())?;
2883 for field in &s.fields {
2884 use clean::StructFieldItem;
2885 if let StructFieldItem(ref ty) = field.inner {
2886 let id = derive_id(format!("variant.{}.field.{}",
2887 variant.name.as_ref().unwrap(),
2888 field.name.as_ref().unwrap()));
2889 let ns_id = derive_id(format!("{}.{}.{}.{}",
2890 variant.name.as_ref().unwrap(),
2891 ItemType::Variant.name_space(),
2892 field.name.as_ref().unwrap(),
2893 ItemType::StructField.name_space()));
2894 write!(w, "<tr><td \
2896 <span id='{ns_id}' class='invisible'>\
2897 <code>{f}: {t}</code></span></td><td>",
2900 f = field.name.as_ref().unwrap(),
2902 document(w, cx, field)?;
2903 write!(w, "</td></tr>")?;
2906 write!(w, "</table></span>")?;
2908 render_stability_since(w, variant, it)?;
2911 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2915 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2916 let name = attr.name();
2919 Some(format!("{}", name))
2920 } else if let Some(v) = attr.value_str() {
2921 Some(format!("{} = {:?}", name, v.as_str()))
2922 } else if let Some(values) = attr.meta_item_list() {
2923 let display: Vec<_> = values.iter().filter_map(|attr| {
2924 attr.meta_item().and_then(|mi| render_attribute(mi))
2927 if display.len() > 0 {
2928 Some(format!("{}({})", name, display.join(", ")))
2937 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2944 "unsafe_destructor_blind_to_params"
2947 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2948 let mut attrs = String::new();
2950 for attr in &it.attrs.other_attrs {
2951 let name = attr.name().unwrap();
2952 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2955 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2956 attrs.push_str(&format!("#[{}]\n", s));
2959 if attrs.len() > 0 {
2960 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2965 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2966 g: Option<&clean::Generics>,
2967 ty: doctree::StructType,
2968 fields: &[clean::Item],
2970 structhead: bool) -> fmt::Result {
2972 VisSpace(&it.visibility),
2973 if structhead {"struct "} else {""},
2974 it.name.as_ref().unwrap())?;
2975 if let Some(g) = g {
2980 if let Some(g) = g {
2981 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2983 let mut has_visible_fields = false;
2985 for field in fields {
2986 if let clean::StructFieldItem(ref ty) = field.inner {
2987 write!(w, "\n{} {}{}: {},",
2989 VisSpace(&field.visibility),
2990 field.name.as_ref().unwrap(),
2992 has_visible_fields = true;
2996 if has_visible_fields {
2997 if it.has_stripped_fields().unwrap() {
2998 write!(w, "\n{} // some fields omitted", tab)?;
3000 write!(w, "\n{}", tab)?;
3001 } else if it.has_stripped_fields().unwrap() {
3002 // If there are no visible fields we can just display
3003 // `{ /* fields omitted */ }` to save space.
3004 write!(w, " /* fields omitted */ ")?;
3010 for (i, field) in fields.iter().enumerate() {
3015 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3018 clean::StructFieldItem(ref ty) => {
3019 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3025 if let Some(g) = g {
3026 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3031 // Needed for PhantomData.
3032 if let Some(g) = g {
3033 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3041 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3042 g: Option<&clean::Generics>,
3043 fields: &[clean::Item],
3045 structhead: bool) -> fmt::Result {
3047 VisSpace(&it.visibility),
3048 if structhead {"union "} else {""},
3049 it.name.as_ref().unwrap())?;
3050 if let Some(g) = g {
3051 write!(w, "{}", g)?;
3052 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3055 write!(w, " {{\n{}", tab)?;
3056 for field in fields {
3057 if let clean::StructFieldItem(ref ty) = field.inner {
3058 write!(w, " {}{}: {},\n{}",
3059 VisSpace(&field.visibility),
3060 field.name.as_ref().unwrap(),
3066 if it.has_stripped_fields().unwrap() {
3067 write!(w, " // some fields omitted\n{}", tab)?;
3073 #[derive(Copy, Clone)]
3074 enum AssocItemLink<'a> {
3075 Anchor(Option<&'a str>),
3076 GotoSource(DefId, &'a FxHashSet<String>),
3079 impl<'a> AssocItemLink<'a> {
3080 fn anchor(&self, id: &'a String) -> Self {
3082 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3083 ref other => *other,
3088 enum AssocItemRender<'a> {
3090 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3093 #[derive(Copy, Clone, PartialEq)]
3096 ForDeref { mut_: bool },
3099 fn render_assoc_items(w: &mut fmt::Formatter,
3101 containing_item: &clean::Item,
3103 what: AssocItemRender) -> fmt::Result {
3105 let v = match c.impls.get(&it) {
3107 None => return Ok(()),
3109 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3110 i.inner_impl().trait_.is_none()
3112 if !non_trait.is_empty() {
3113 let render_mode = match what {
3114 AssocItemRender::All => {
3116 <h2 id='methods' class='small-section-header'>
3117 Methods<a href='#methods' class='anchor'></a>
3122 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3124 <h2 id='deref-methods' class='small-section-header'>
3125 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3128 RenderMode::ForDeref { mut_: deref_mut_ }
3131 for i in &non_trait {
3132 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3133 containing_item.stable_since(), true)?;
3136 if let AssocItemRender::DerefFor { .. } = what {
3139 if !traits.is_empty() {
3140 let deref_impl = traits.iter().find(|t| {
3141 t.inner_impl().trait_.def_id() == c.deref_trait_did
3143 if let Some(impl_) = deref_impl {
3144 let has_deref_mut = traits.iter().find(|t| {
3145 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3147 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3150 let (synthetic, concrete) = traits
3152 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3155 <h2 id='implementations' class='small-section-header'>
3156 Trait Implementations<a href='#implementations' class='anchor'></a>
3158 <div id='implementations-list'>
3160 render_impls(cx, w, concrete, containing_item)?;
3161 write!(w, "</div>")?;
3164 <h2 id='synthetic-implementations' class='small-section-header'>
3165 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3167 <div id='synthetic-implementations-list'>
3169 render_impls(cx, w, synthetic, containing_item)?;
3170 write!(w, "</div>")?;
3175 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3176 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3177 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3178 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3180 clean::TypedefItem(ref t, true) => Some(&t.type_),
3183 }).next().expect("Expected associated type binding");
3184 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3185 deref_mut_: deref_mut };
3186 if let Some(did) = target.def_id() {
3187 render_assoc_items(w, cx, container_item, did, what)
3189 if let Some(prim) = target.primitive_type() {
3190 if let Some(&did) = cache().primitive_locations.get(&prim) {
3191 render_assoc_items(w, cx, container_item, did, what)?;
3198 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3199 let self_type_opt = match item.inner {
3200 clean::MethodItem(ref method) => method.decl.self_type(),
3201 clean::TyMethodItem(ref method) => method.decl.self_type(),
3205 if let Some(self_ty) = self_type_opt {
3206 let (by_mut_ref, by_box, by_value) = match self_ty {
3207 SelfTy::SelfBorrowed(_, mutability) |
3208 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3209 (mutability == Mutability::Mutable, false, false)
3211 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3212 (false, Some(did) == cache().owned_box_did, false)
3214 SelfTy::SelfValue => (false, false, true),
3215 _ => (false, false, false),
3218 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3224 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3225 let mut out = String::new();
3228 clean::FunctionItem(clean::Function { ref decl, .. }) |
3229 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3230 clean::MethodItem(clean::Method { ref decl, .. }) |
3231 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3232 out = spotlight_decl(decl)?;
3240 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3241 let mut out = String::new();
3242 let mut trait_ = String::new();
3244 if let Some(did) = decl.output.def_id() {
3246 if let Some(impls) = c.impls.get(&did) {
3248 let impl_ = i.inner_impl();
3249 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3252 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3253 <code class=\"content\">",
3255 trait_.push_str(&format!("{}", impl_.for_));
3258 //use the "where" class here to make it small
3259 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3260 let t_did = impl_.trait_.def_id().unwrap();
3261 for it in &impl_.items {
3262 if let clean::TypedefItem(ref tydef, _) = it.inner {
3263 out.push_str("<span class=\"where fmt-newline\"> ");
3264 assoc_type(&mut out, it, &vec![],
3266 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3267 out.push_str(";</span>");
3275 if !out.is_empty() {
3276 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3277 <span class='tooltiptext'>Important traits for {}</span></div>\
3278 <div class=\"content hidden\">",
3280 out.push_str("</code></div></div>");
3286 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3287 render_mode: RenderMode, outer_version: Option<&str>,
3288 show_def_docs: bool) -> fmt::Result {
3289 if render_mode == RenderMode::Normal {
3290 let id = derive_id(match i.inner_impl().trait_ {
3291 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3292 None => "impl".to_string(),
3294 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3295 id, i.inner_impl())?;
3296 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3297 write!(w, "</span><span class='out-of-band'>")?;
3298 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3299 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3300 write!(w, "<div class='ghost'></div>")?;
3301 render_stability_since_raw(w, since, outer_version)?;
3302 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3303 l, "goto source code")?;
3305 render_stability_since_raw(w, since, outer_version)?;
3307 write!(w, "</span>")?;
3308 write!(w, "</h3>\n")?;
3309 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3310 write!(w, "<div class='docblock'>{}</div>",
3311 Markdown(&*dox, &i.impl_item.links()))?;
3315 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3316 link: AssocItemLink, render_mode: RenderMode,
3317 is_default_item: bool, outer_version: Option<&str>,
3318 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3319 let item_type = item.type_();
3320 let name = item.name.as_ref().unwrap();
3322 let render_method_item: bool = match render_mode {
3323 RenderMode::Normal => true,
3324 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3328 clean::MethodItem(clean::Method { ref decl, .. }) |
3329 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3330 // Only render when the method is not static or we allow static methods
3331 if render_method_item {
3332 let id = derive_id(format!("{}.{}", item_type, name));
3333 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3334 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3335 write!(w, "{}", spotlight_decl(decl)?)?;
3336 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3337 write!(w, "<code>")?;
3338 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3339 write!(w, "</code>")?;
3340 if let Some(l) = (Item { cx, item }).src_href() {
3341 write!(w, "</span><span class='out-of-band'>")?;
3342 write!(w, "<div class='ghost'></div>")?;
3343 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3344 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3345 l, "goto source code")?;
3347 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3349 write!(w, "</span></h4>\n")?;
3352 clean::TypedefItem(ref tydef, _) => {
3353 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3354 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3355 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3356 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3357 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3358 write!(w, "</code></span></h4>\n")?;
3360 clean::AssociatedConstItem(ref ty, ref default) => {
3361 let id = derive_id(format!("{}.{}", item_type, name));
3362 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3363 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3364 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3365 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3366 write!(w, "</code></span></h4>\n")?;
3368 clean::AssociatedTypeItem(ref bounds, ref default) => {
3369 let id = derive_id(format!("{}.{}", item_type, name));
3370 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3371 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3372 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3373 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3374 write!(w, "</code></span></h4>\n")?;
3376 clean::StrippedItem(..) => return Ok(()),
3377 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3380 if render_method_item || render_mode == RenderMode::Normal {
3381 let prefix = render_assoc_const_value(item);
3383 if !is_default_item {
3384 if let Some(t) = trait_ {
3385 // The trait item may have been stripped so we might not
3386 // find any documentation or stability for it.
3387 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3388 // We need the stability of the item from the trait
3389 // because impls can't have a stability.
3390 document_stability(w, cx, it)?;
3391 if item.doc_value().is_some() {
3392 document_full(w, item, cx, &prefix)?;
3393 } else if show_def_docs {
3394 // In case the item isn't documented,
3395 // provide short documentation from the trait.
3396 document_short(w, it, link, &prefix)?;
3400 document_stability(w, cx, item)?;
3402 document_full(w, item, cx, &prefix)?;
3406 document_stability(w, cx, item)?;
3408 document_short(w, item, link, &prefix)?;
3415 let traits = &cache().traits;
3416 let trait_ = i.trait_did().map(|did| &traits[&did]);
3419 write!(w, "<span class='docblock autohide'>")?;
3422 write!(w, "<div class='impl-items'>")?;
3423 for trait_item in &i.inner_impl().items {
3424 doc_impl_item(w, cx, trait_item, link, render_mode,
3425 false, outer_version, trait_, show_def_docs)?;
3428 fn render_default_items(w: &mut fmt::Formatter,
3432 render_mode: RenderMode,
3433 outer_version: Option<&str>,
3434 show_def_docs: bool) -> fmt::Result {
3435 for trait_item in &t.items {
3436 let n = trait_item.name.clone();
3437 if i.items.iter().find(|m| m.name == n).is_some() {
3440 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3441 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3443 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3444 outer_version, None, show_def_docs)?;
3449 // If we've implemented a trait, then also emit documentation for all
3450 // default items which weren't overridden in the implementation block.
3451 if let Some(t) = trait_ {
3452 render_default_items(w, cx, t, &i.inner_impl(),
3453 render_mode, outer_version, show_def_docs)?;
3455 write!(w, "</div>")?;
3458 write!(w, "</span>")?;
3464 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3465 t: &clean::Typedef) -> fmt::Result {
3466 write!(w, "<pre class='rust typedef'>")?;
3467 render_attributes(w, it)?;
3468 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3469 it.name.as_ref().unwrap(),
3471 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3474 document(w, cx, it)?;
3476 // Render any items associated directly to this alias, as otherwise they
3477 // won't be visible anywhere in the docs. It would be nice to also show
3478 // associated items from the aliased type (see discussion in #32077), but
3479 // we need #14072 to make sense of the generics.
3480 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3483 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3484 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3485 render_attributes(w, it)?;
3488 " {}type {};\n}}</pre>",
3489 VisSpace(&it.visibility),
3490 it.name.as_ref().unwrap(),
3493 document(w, cx, it)?;
3495 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3498 impl<'a> fmt::Display for Sidebar<'a> {
3499 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3502 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3503 let mut should_close = false;
3505 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3506 || it.is_enum() || it.is_mod() || it.is_typedef()
3508 write!(fmt, "<p class='location'>")?;
3510 clean::StructItem(..) => write!(fmt, "Struct ")?,
3511 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3512 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3513 clean::UnionItem(..) => write!(fmt, "Union ")?,
3514 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3515 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3516 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3517 clean::ModuleItem(..) => if it.is_crate() {
3518 write!(fmt, "Crate ")?;
3520 write!(fmt, "Module ")?;
3524 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3525 write!(fmt, "</p>")?;
3528 if let Some(ref version) = cache().crate_version {
3530 "<div class='block version'>\
3537 write!(fmt, "<div class=\"sidebar-elems\">")?;
3538 should_close = true;
3540 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3541 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3542 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3543 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3544 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3545 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3546 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3547 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3552 // The sidebar is designed to display sibling functions, modules and
3553 // other miscellaneous information. since there are lots of sibling
3554 // items (and that causes quadratic growth in large modules),
3555 // we refactor common parts into a shared JavaScript file per module.
3556 // still, we don't move everything into JS because we want to preserve
3557 // as much HTML as possible in order to allow non-JS-enabled browsers
3558 // to navigate the documentation (though slightly inefficiently).
3560 write!(fmt, "<p class='location'>")?;
3561 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3563 write!(fmt, "::<wbr>")?;
3565 write!(fmt, "<a href='{}index.html'>{}</a>",
3566 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3569 write!(fmt, "</p>")?;
3571 // Sidebar refers to the enclosing module, not this module.
3572 let relpath = if it.is_mod() { "../" } else { "" };
3574 "<script>window.sidebarCurrent = {{\
3579 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3580 ty = it.type_().css_class(),
3583 // There is no sidebar-items.js beyond the crate root path
3584 // FIXME maybe dynamic crate loading can be merged here
3586 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3590 // Closes sidebar-elems div.
3591 write!(fmt, "</div>")?;
3598 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3599 i.items.iter().filter_map(|item| {
3601 // Maybe check with clean::Visibility::Public as well?
3602 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3603 if !for_deref || should_render_item(item, false) {
3604 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3611 }).collect::<Vec<_>>()
3614 // The point is to url encode any potential character from a type with genericity.
3615 fn small_url_encode(s: &str) -> String {
3616 s.replace("<", "%3C")
3617 .replace(">", "%3E")
3618 .replace(" ", "%20")
3619 .replace("?", "%3F")
3620 .replace("'", "%27")
3621 .replace("&", "%26")
3622 .replace(",", "%2C")
3623 .replace(":", "%3A")
3624 .replace(";", "%3B")
3625 .replace("[", "%5B")
3626 .replace("]", "%5D")
3627 .replace("\"", "%22")
3630 fn sidebar_assoc_items(it: &clean::Item) -> String {
3631 let mut out = String::new();
3633 if let Some(v) = c.impls.get(&it.def_id) {
3635 .filter(|i| i.inner_impl().trait_.is_none())
3636 .flat_map(|i| get_methods(i.inner_impl(), false))
3637 .collect::<String>();
3638 if !ret.is_empty() {
3639 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3640 </a><div class=\"sidebar-links\">{}</div>", ret));
3643 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3644 if let Some(impl_) = v.iter()
3645 .filter(|i| i.inner_impl().trait_.is_some())
3646 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3647 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3649 clean::TypedefItem(ref t, true) => Some(&t.type_),
3653 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3654 c.primitive_locations.get(&prim).cloned()
3655 })).and_then(|did| c.impls.get(&did));
3656 if let Some(impls) = inner_impl {
3657 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3658 out.push_str(&format!("Methods from {}<Target={}>",
3659 Escape(&format!("{:#}",
3660 impl_.inner_impl().trait_.as_ref().unwrap())),
3661 Escape(&format!("{:#}", target))));
3662 out.push_str("</a>");
3663 let ret = impls.iter()
3664 .filter(|i| i.inner_impl().trait_.is_none())
3665 .flat_map(|i| get_methods(i.inner_impl(), true))
3666 .collect::<String>();
3667 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3671 let format_impls = |impls: Vec<&Impl>| {
3672 let mut links = HashSet::new();
3675 let is_negative_impl = is_negative_impl(i.inner_impl());
3676 if let Some(ref i) = i.inner_impl().trait_ {
3677 let i_display = format!("{:#}", i);
3678 let out = Escape(&i_display);
3679 let encoded = small_url_encode(&format!("{:#}", i));
3680 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3682 if is_negative_impl { "!" } else { "" },
3684 if links.insert(generated.clone()) {
3693 .collect::<String>()
3696 let (synthetic, concrete) = v
3698 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3700 let concrete_format = format_impls(concrete);
3701 let synthetic_format = format_impls(synthetic);
3703 if !concrete_format.is_empty() {
3704 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3705 Trait Implementations</a>");
3706 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3709 if !synthetic_format.is_empty() {
3710 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3711 Auto Trait Implementations</a>");
3712 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3720 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3721 s: &clean::Struct) -> fmt::Result {
3722 let mut sidebar = String::new();
3723 let fields = get_struct_fields_name(&s.fields);
3725 if !fields.is_empty() {
3726 if let doctree::Plain = s.struct_type {
3727 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3728 <div class=\"sidebar-links\">{}</div>", fields));
3732 sidebar.push_str(&sidebar_assoc_items(it));
3734 if !sidebar.is_empty() {
3735 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3740 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3742 clean::ItemEnum::ImplItem(ref i) => {
3743 if let Some(ref trait_) = i.trait_ {
3744 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3753 fn is_negative_impl(i: &clean::Impl) -> bool {
3754 i.polarity == Some(clean::ImplPolarity::Negative)
3757 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3758 t: &clean::Trait) -> fmt::Result {
3759 let mut sidebar = String::new();
3765 Some(ref name) if m.is_associated_type() => {
3766 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3772 .collect::<String>();
3773 let consts = t.items
3777 Some(ref name) if m.is_associated_const() => {
3778 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3784 .collect::<String>();
3785 let required = t.items
3789 Some(ref name) if m.is_ty_method() => {
3790 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3796 .collect::<String>();
3797 let provided = t.items
3801 Some(ref name) if m.is_method() => {
3802 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3807 .collect::<String>();
3809 if !types.is_empty() {
3810 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3811 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3814 if !consts.is_empty() {
3815 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3816 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3819 if !required.is_empty() {
3820 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3821 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3824 if !provided.is_empty() {
3825 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3826 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3832 if let Some(implementors) = c.implementors.get(&it.def_id) {
3833 let res = implementors.iter()
3834 .filter(|i| i.inner_impl().for_.def_id()
3835 .map_or(false, |d| !c.paths.contains_key(&d)))
3837 match extract_for_impl_name(&i.impl_item) {
3838 Some((ref name, ref url)) => {
3839 Some(format!("<a href=\"#impl-{}\">{}</a>",
3840 small_url_encode(url),
3846 .collect::<String>();
3847 if !res.is_empty() {
3848 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3849 Implementations on Foreign Types</a><div \
3850 class=\"sidebar-links\">{}</div>",
3855 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3857 sidebar.push_str("<a class=\"sidebar-title\" \
3858 href=\"#synthetic-implementors\">Auto Implementors</a>");
3861 sidebar.push_str(&sidebar_assoc_items(it));
3863 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3866 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3867 _p: &clean::PrimitiveType) -> fmt::Result {
3868 let sidebar = sidebar_assoc_items(it);
3870 if !sidebar.is_empty() {
3871 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3876 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3877 _t: &clean::Typedef) -> fmt::Result {
3878 let sidebar = sidebar_assoc_items(it);
3880 if !sidebar.is_empty() {
3881 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3886 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3888 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3893 .filter_map(|f| match f.name {
3894 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3895 {name}</a>", name=name)),
3901 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3902 u: &clean::Union) -> fmt::Result {
3903 let mut sidebar = String::new();
3904 let fields = get_struct_fields_name(&u.fields);
3906 if !fields.is_empty() {
3907 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3908 <div class=\"sidebar-links\">{}</div>", fields));
3911 sidebar.push_str(&sidebar_assoc_items(it));
3913 if !sidebar.is_empty() {
3914 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3919 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3920 e: &clean::Enum) -> fmt::Result {
3921 let mut sidebar = String::new();
3923 let variants = e.variants.iter()
3924 .filter_map(|v| match v.name {
3925 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3926 </a>", name = name)),
3929 .collect::<String>();
3930 if !variants.is_empty() {
3931 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3932 <div class=\"sidebar-links\">{}</div>", variants));
3935 sidebar.push_str(&sidebar_assoc_items(it));
3937 if !sidebar.is_empty() {
3938 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3943 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3944 items: &[clean::Item]) -> fmt::Result {
3945 let mut sidebar = String::new();
3947 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3948 it.type_() == ItemType::Import) {
3949 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3951 name = "Re-exports"));
3954 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3955 // to print its headings
3956 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3957 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3958 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3959 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3960 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3961 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3962 let (short, name) = match myty {
3963 ItemType::ExternCrate |
3964 ItemType::Import => ("reexports", "Re-exports"),
3965 ItemType::Module => ("modules", "Modules"),
3966 ItemType::Struct => ("structs", "Structs"),
3967 ItemType::Union => ("unions", "Unions"),
3968 ItemType::Enum => ("enums", "Enums"),
3969 ItemType::Function => ("functions", "Functions"),
3970 ItemType::Typedef => ("types", "Type Definitions"),
3971 ItemType::Static => ("statics", "Statics"),
3972 ItemType::Constant => ("constants", "Constants"),
3973 ItemType::Trait => ("traits", "Traits"),
3974 ItemType::Impl => ("impls", "Implementations"),
3975 ItemType::TyMethod => ("tymethods", "Type Methods"),
3976 ItemType::Method => ("methods", "Methods"),
3977 ItemType::StructField => ("fields", "Struct Fields"),
3978 ItemType::Variant => ("variants", "Variants"),
3979 ItemType::Macro => ("macros", "Macros"),
3980 ItemType::Primitive => ("primitives", "Primitive Types"),
3981 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3982 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3983 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
3985 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3991 if !sidebar.is_empty() {
3992 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3997 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3998 let sidebar = sidebar_assoc_items(it);
3999 if !sidebar.is_empty() {
4000 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4005 impl<'a> fmt::Display for Source<'a> {
4006 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4007 let Source(s) = *self;
4008 let lines = s.lines().count();
4010 let mut tmp = lines;
4015 write!(fmt, "<pre class=\"line-numbers\">")?;
4016 for i in 1..lines + 1 {
4017 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4019 write!(fmt, "</pre>")?;
4021 highlight::render_with_highlighting(s, None, None, None, None))?;
4026 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4027 t: &clean::Macro) -> fmt::Result {
4028 w.write_str(&highlight::render_with_highlighting(&t.source,
4036 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4038 _p: &clean::PrimitiveType) -> fmt::Result {
4039 document(w, cx, it)?;
4040 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4043 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4045 fn make_item_keywords(it: &clean::Item) -> String {
4046 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4049 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4050 let decl = match item.inner {
4051 clean::FunctionItem(ref f) => &f.decl,
4052 clean::MethodItem(ref m) => &m.decl,
4053 clean::TyMethodItem(ref m) => &m.decl,
4057 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4058 let output = match decl.output {
4059 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4063 Some(IndexItemFunctionType { inputs: inputs, output: output })
4066 fn get_index_type(clean_type: &clean::Type) -> Type {
4068 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4069 generics: get_generics(clean_type),
4074 /// Returns a list of all paths used in the type.
4075 /// This is used to help deduplicate imported impls
4076 /// for reexported types. If any of the contained
4077 /// types are re-exported, we don't use the corresponding
4078 /// entry from the js file, as inlining will have already
4079 /// picked up the impl
4080 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4081 let mut out = Vec::new();
4082 let mut visited = FxHashSet();
4083 let mut work = VecDeque::new();
4084 let cache = cache();
4086 work.push_back(first_ty);
4088 while let Some(ty) = work.pop_front() {
4089 if !visited.insert(ty.clone()) {
4094 clean::Type::ResolvedPath { did, .. } => {
4095 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4096 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4100 out.push(path.join("::"));
4106 clean::Type::Tuple(tys) => {
4107 work.extend(tys.into_iter());
4109 clean::Type::Slice(ty) => {
4110 work.push_back(*ty);
4112 clean::Type::Array(ty, _) => {
4113 work.push_back(*ty);
4115 clean::Type::Unique(ty) => {
4116 work.push_back(*ty);
4118 clean::Type::RawPointer(_, ty) => {
4119 work.push_back(*ty);
4121 clean::Type::BorrowedRef { type_, .. } => {
4122 work.push_back(*type_);
4124 clean::Type::QPath { self_type, trait_, .. } => {
4125 work.push_back(*self_type);
4126 work.push_back(*trait_);
4134 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4136 clean::ResolvedPath { ref path, .. } => {
4137 let segments = &path.segments;
4138 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4139 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4140 clean_type, accept_generic
4142 Some(path_segment.name.clone())
4144 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4145 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4146 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4147 // FIXME: add all from clean::Type.
4152 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4153 clean_type.generics()
4155 let r = types.iter()
4156 .filter_map(|t| get_index_type_name(t, false))
4157 .map(|s| s.to_ascii_lowercase())
4158 .collect::<Vec<_>>();
4167 pub fn cache() -> Arc<Cache> {
4168 CACHE_KEY.with(|c| c.borrow().clone())
4173 fn test_unique_id() {
4174 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4175 "method.into_iter", "foo", "main", "search", "methods",
4176 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4177 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4178 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4179 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4182 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4183 assert_eq!(&actual[..], expected);
4192 fn test_name_key() {
4193 assert_eq!(name_key("0"), ("", 0, 1));
4194 assert_eq!(name_key("123"), ("", 123, 0));
4195 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4196 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4197 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4198 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4199 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4200 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4205 fn test_name_sorting() {
4206 let names = ["Apple",
4208 "Fruit", "Fruit0", "Fruit00",
4209 "Fruit1", "Fruit01",
4210 "Fruit2", "Fruit02",
4214 let mut sorted = names.to_owned();
4215 sorted.sort_by_key(|&s| name_key(s));
4216 assert_eq!(names, sorted);