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.
173 /// Metadata about implementations for a type or trait.
176 pub impl_item: clean::Item,
180 fn inner_impl(&self) -> &clean::Impl {
181 match self.impl_item.inner {
182 clean::ImplItem(ref impl_) => impl_,
183 _ => panic!("non-impl item found in impl")
187 fn trait_did(&self) -> Option<DefId> {
188 self.inner_impl().trait_.def_id()
198 impl error::Error for Error {
199 fn description(&self) -> &str {
200 self.error.description()
204 impl Display for Error {
205 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
206 write!(f, "\"{}\": {}", self.file.display(), self.error)
211 pub fn new(e: io::Error, file: &Path) -> Error {
213 file: file.to_path_buf(),
219 macro_rules! try_none {
220 ($e:expr, $file:expr) => ({
224 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
230 macro_rules! try_err {
231 ($e:expr, $file:expr) => ({
234 Err(e) => return Err(Error::new(e, $file)),
239 /// This cache is used to store information about the `clean::Crate` being
240 /// rendered in order to provide more useful documentation. This contains
241 /// information like all implementors of a trait, all traits a type implements,
242 /// documentation for all known traits, etc.
244 /// This structure purposefully does not implement `Clone` because it's intended
245 /// to be a fairly large and expensive structure to clone. Instead this adheres
246 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
247 /// rendering threads.
250 /// Mapping of typaram ids to the name of the type parameter. This is used
251 /// when pretty-printing a type (so pretty printing doesn't have to
252 /// painfully maintain a context like this)
253 pub typarams: FxHashMap<DefId, String>,
255 /// Maps a type id to all known implementations for that type. This is only
256 /// recognized for intra-crate `ResolvedPath` types, and is used to print
257 /// out extra documentation on the page of an enum/struct.
259 /// The values of the map are a list of implementations and documentation
260 /// found on that implementation.
261 pub impls: FxHashMap<DefId, Vec<Impl>>,
263 /// Maintains a mapping of local crate node ids to the fully qualified name
264 /// and "short type description" of that node. This is used when generating
265 /// URLs when a type is being linked to. External paths are not located in
266 /// this map because the `External` type itself has all the information
268 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
270 /// Similar to `paths`, but only holds external paths. This is only used for
271 /// generating explicit hyperlinks to other crates.
272 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
274 /// Maps local def ids of exported types to fully qualified paths.
275 /// Unlike 'paths', this mapping ignores any renames that occur
276 /// due to 'use' statements.
278 /// This map is used when writing out the special 'implementors'
279 /// javascript file. By using the exact path that the type
280 /// is declared with, we ensure that each path will be identical
281 /// to the path used if the corresponding type is inlined. By
282 /// doing this, we can detect duplicate impls on a trait page, and only display
283 /// the impl for the inlined type.
284 pub exact_paths: FxHashMap<DefId, Vec<String>>,
286 /// This map contains information about all known traits of this crate.
287 /// Implementations of a crate should inherit the documentation of the
288 /// parent trait if no extra documentation is specified, and default methods
289 /// should show up in documentation about trait implementations.
290 pub traits: FxHashMap<DefId, clean::Trait>,
292 /// When rendering traits, it's often useful to be able to list all
293 /// implementors of the trait, and this mapping is exactly, that: a mapping
294 /// of trait ids to the list of known implementors of the trait
295 pub implementors: FxHashMap<DefId, Vec<Impl>>,
297 /// Cache of where external crate documentation can be found.
298 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
300 /// Cache of where documentation for primitives can be found.
301 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
303 // Note that external items for which `doc(hidden)` applies to are shown as
304 // non-reachable while local items aren't. This is because we're reusing
305 // the access levels from crateanalysis.
306 pub access_levels: Arc<AccessLevels<DefId>>,
308 /// The version of the crate being documented, if given fron the `--crate-version` flag.
309 pub crate_version: Option<String>,
311 // Private fields only used when initially crawling a crate to build a cache
314 parent_stack: Vec<DefId>,
315 parent_is_trait_impl: bool,
316 search_index: Vec<IndexItem>,
318 deref_trait_did: Option<DefId>,
319 deref_mut_trait_did: Option<DefId>,
320 owned_box_did: Option<DefId>,
321 masked_crates: FxHashSet<CrateNum>,
323 // In rare case where a structure is defined in one module but implemented
324 // in another, if the implementing module is parsed before defining module,
325 // then the fully qualified name of the structure isn't presented in `paths`
326 // yet when its implementation methods are being indexed. Caches such methods
327 // and their parent id here and indexes them at the end of crate parsing.
328 orphan_impl_items: Vec<(DefId, clean::Item)>,
331 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
332 /// Later on moved into `CACHE_KEY`.
334 pub struct RenderInfo {
335 pub inlined: FxHashSet<DefId>,
336 pub external_paths: ::core::ExternalPaths,
337 pub external_typarams: FxHashMap<DefId, String>,
338 pub exact_paths: FxHashMap<DefId, Vec<String>>,
339 pub deref_trait_did: Option<DefId>,
340 pub deref_mut_trait_did: Option<DefId>,
341 pub owned_box_did: Option<DefId>,
344 /// Helper struct to render all source code to HTML pages
345 struct SourceCollector<'a> {
346 scx: &'a mut SharedContext,
348 /// Root destination to place all HTML output into
352 /// Wrapper struct to render the source code of a file. This will do things like
353 /// adding line numbers to the left-hand side.
354 struct Source<'a>(&'a str);
356 // Helper structs for rendering items/sidebars and carrying along contextual
359 #[derive(Copy, Clone)]
362 item: &'a clean::Item,
365 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
367 /// Struct representing one entry in the JS search index. These are all emitted
368 /// by hand to a large JS file at the end of cache-creation.
374 parent: Option<DefId>,
375 parent_idx: Option<usize>,
376 search_type: Option<IndexItemFunctionType>,
379 impl ToJson for IndexItem {
380 fn to_json(&self) -> Json {
381 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
383 let mut data = Vec::with_capacity(6);
384 data.push((self.ty as usize).to_json());
385 data.push(self.name.to_json());
386 data.push(self.path.to_json());
387 data.push(self.desc.to_json());
388 data.push(self.parent_idx.to_json());
389 data.push(self.search_type.to_json());
395 /// A type used for the search index.
397 name: Option<String>,
398 generics: Option<Vec<String>>,
401 impl ToJson for Type {
402 fn to_json(&self) -> Json {
405 let mut data = BTreeMap::new();
406 data.insert("name".to_owned(), name.to_json());
407 if let Some(ref generics) = self.generics {
408 data.insert("generics".to_owned(), generics.to_json());
417 /// Full type of functions/methods in the search index.
418 struct IndexItemFunctionType {
423 impl ToJson for IndexItemFunctionType {
424 fn to_json(&self) -> Json {
425 // If we couldn't figure out a type, just write `null`.
426 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
429 let mut data = BTreeMap::new();
430 data.insert("inputs".to_owned(), self.inputs.to_json());
431 data.insert("output".to_owned(), self.output.to_json());
437 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
438 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
439 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
441 fn init_ids() -> FxHashMap<String, usize> {
453 "synthetic-implementors",
455 "synthetic-implementors-list",
459 ].into_iter().map(|id| (String::from(*id), 1)).collect()
462 /// This method resets the local table of used ID attributes. This is typically
463 /// used at the beginning of rendering an entire HTML page to reset from the
464 /// previous state (if any).
465 pub fn reset_ids(embedded: bool) {
466 USED_ID_MAP.with(|s| {
467 *s.borrow_mut() = if embedded {
475 pub fn derive_id(candidate: String) -> String {
476 USED_ID_MAP.with(|map| {
477 let id = match map.borrow_mut().get_mut(&candidate) {
480 let id = format!("{}-{}", candidate, *a);
486 map.borrow_mut().insert(id.clone(), 1);
491 /// Generates the documentation for `crate` into the directory `dst`
492 pub fn run(mut krate: clean::Crate,
493 external_html: &ExternalHtml,
494 playground_url: Option<String>,
496 passes: FxHashSet<String>,
497 css_file_extension: Option<PathBuf>,
498 renderinfo: RenderInfo,
499 sort_modules_alphabetically: bool,
500 themes: Vec<PathBuf>) -> Result<(), Error> {
501 let src_root = match krate.src {
502 FileName::Real(ref p) => match p.parent() {
503 Some(p) => p.to_path_buf(),
504 None => PathBuf::new(),
508 let mut scx = SharedContext {
511 include_sources: true,
512 local_sources: FxHashMap(),
513 issue_tracker_base_url: None,
514 layout: layout::Layout {
515 logo: "".to_string(),
516 favicon: "".to_string(),
517 external_html: external_html.clone(),
518 krate: krate.name.clone(),
520 css_file_extension: css_file_extension.clone(),
521 created_dirs: RefCell::new(FxHashSet()),
522 sort_modules_alphabetically,
527 // If user passed in `--playground-url` arg, we fill in crate name here
528 if let Some(url) = playground_url {
529 markdown::PLAYGROUND.with(|slot| {
530 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
534 // Crawl the crate attributes looking for attributes which control how we're
535 // going to emit HTML
536 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
537 for attr in attrs.lists("doc") {
538 let name = attr.name().map(|s| s.as_str());
539 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
540 (Some("html_favicon_url"), Some(s)) => {
541 scx.layout.favicon = s.to_string();
543 (Some("html_logo_url"), Some(s)) => {
544 scx.layout.logo = s.to_string();
546 (Some("html_playground_url"), Some(s)) => {
547 markdown::PLAYGROUND.with(|slot| {
548 let name = krate.name.clone();
549 *slot.borrow_mut() = Some((Some(name), s.to_string()));
552 (Some("issue_tracker_base_url"), Some(s)) => {
553 scx.issue_tracker_base_url = Some(s.to_string());
555 (Some("html_no_source"), None) if attr.is_word() => {
556 scx.include_sources = false;
562 try_err!(fs::create_dir_all(&dst), &dst);
563 krate = render_sources(&dst, &mut scx, krate)?;
567 render_redirect_pages: false,
568 shared: Arc::new(scx),
571 // Crawl the crate to build various caches used for the output
582 let external_paths = external_paths.into_iter()
583 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
586 let mut cache = Cache {
591 implementors: FxHashMap(),
593 parent_stack: Vec::new(),
594 search_index: Vec::new(),
595 parent_is_trait_impl: false,
596 extern_locations: FxHashMap(),
597 primitive_locations: FxHashMap(),
599 access_levels: krate.access_levels.clone(),
600 crate_version: krate.version.take(),
601 orphan_impl_items: Vec::new(),
602 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
606 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
607 typarams: external_typarams,
610 // Cache where all our extern crates are located
611 for &(n, ref e) in &krate.externs {
612 let src_root = match e.src {
613 FileName::Real(ref p) => match p.parent() {
614 Some(p) => p.to_path_buf(),
615 None => PathBuf::new(),
619 cache.extern_locations.insert(n, (e.name.clone(), src_root,
620 extern_location(e, &cx.dst)));
622 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
623 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
626 // Cache where all known primitives have their documentation located.
628 // Favor linking to as local extern as possible, so iterate all crates in
629 // reverse topological order.
630 for &(_, ref e) in krate.externs.iter().rev() {
631 for &(def_id, prim, _) in &e.primitives {
632 cache.primitive_locations.insert(prim, def_id);
635 for &(def_id, prim, _) in &krate.primitives {
636 cache.primitive_locations.insert(prim, def_id);
639 cache.stack.push(krate.name.clone());
640 krate = cache.fold_crate(krate);
642 // Build our search index
643 let index = build_index(&krate, &mut cache);
645 // Freeze the cache now that the index has been built. Put an Arc into TLS
646 // for future parallelization opportunities
647 let cache = Arc::new(cache);
648 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
649 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
651 write_shared(&cx, &krate, &*cache, index)?;
653 // And finally render the whole crate's documentation
657 /// Build the search index from the collected metadata
658 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
659 let mut nodeid_to_pathid = FxHashMap();
660 let mut crate_items = Vec::with_capacity(cache.search_index.len());
661 let mut crate_paths = Vec::<Json>::new();
663 let Cache { ref mut search_index,
664 ref orphan_impl_items,
665 ref mut paths, .. } = *cache;
667 // Attach all orphan items to the type's definition if the type
668 // has since been learned.
669 for &(did, ref item) in orphan_impl_items {
670 if let Some(&(ref fqp, _)) = paths.get(&did) {
671 search_index.push(IndexItem {
673 name: item.name.clone().unwrap(),
674 path: fqp[..fqp.len() - 1].join("::"),
675 desc: plain_summary_line(item.doc_value()),
678 search_type: get_index_search_type(&item),
683 // Reduce `NodeId` in paths into smaller sequential numbers,
684 // and prune the paths that do not appear in the index.
685 let mut lastpath = String::new();
686 let mut lastpathid = 0usize;
688 for item in search_index {
689 item.parent_idx = item.parent.map(|nodeid| {
690 if nodeid_to_pathid.contains_key(&nodeid) {
691 *nodeid_to_pathid.get(&nodeid).unwrap()
693 let pathid = lastpathid;
694 nodeid_to_pathid.insert(nodeid, pathid);
697 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
698 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
703 // Omit the parent path if it is same to that of the prior item.
704 if lastpath == item.path {
707 lastpath = item.path.clone();
709 crate_items.push(item.to_json());
712 let crate_doc = krate.module.as_ref().map(|module| {
713 plain_summary_line(module.doc_value())
714 }).unwrap_or(String::new());
716 let mut crate_data = BTreeMap::new();
717 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
718 crate_data.insert("items".to_owned(), Json::Array(crate_items));
719 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
721 // Collect the index into a string
722 format!("searchIndex[{}] = {};",
723 as_json(&krate.name),
724 Json::Object(crate_data))
727 fn write_shared(cx: &Context,
728 krate: &clean::Crate,
730 search_index: String) -> Result<(), Error> {
731 // Write out the shared files. Note that these are shared among all rustdoc
732 // docs placed in the output directory, so this needs to be a synchronized
733 // operation with respect to all other rustdocs running around.
734 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
736 // Add all the static files. These may already exist, but we just
737 // overwrite them anyway to make sure that they're fresh and up-to-date.
739 write(cx.dst.join("rustdoc.css"),
740 include_bytes!("static/rustdoc.css"))?;
742 // To avoid "main.css" to be overwritten, we'll first run over the received themes and only
743 // then we'll run over the "official" styles.
744 let mut themes: HashSet<String> = HashSet::new();
746 for entry in &cx.shared.themes {
747 let mut content = Vec::with_capacity(100000);
749 let mut f = try_err!(File::open(&entry), &entry);
750 try_err!(f.read_to_end(&mut content), &entry);
751 write(cx.dst.join(try_none!(entry.file_name(), &entry)), content.as_slice())?;
752 themes.insert(try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry).to_owned());
755 write(cx.dst.join("brush.svg"),
756 include_bytes!("static/brush.svg"))?;
757 write(cx.dst.join("main.css"),
758 include_bytes!("static/themes/main.css"))?;
759 themes.insert("main".to_owned());
760 write(cx.dst.join("dark.css"),
761 include_bytes!("static/themes/dark.css"))?;
762 themes.insert("dark".to_owned());
764 let mut themes: Vec<&String> = themes.iter().collect();
766 // To avoid theme switch latencies as much as possible, we put everything theme related
767 // at the beginning of the html files into another js file.
768 write(cx.dst.join("theme.js"), format!(
769 r#"var themes = document.getElementById("theme-choices");
770 var themePicker = document.getElementById("theme-picker");
771 themePicker.onclick = function() {{
772 if (themes.style.display === "block") {{
773 themes.style.display = "none";
774 themePicker.style.borderBottomRightRadius = "3px";
775 themePicker.style.borderBottomLeftRadius = "3px";
777 themes.style.display = "block";
778 themePicker.style.borderBottomRightRadius = "0";
779 themePicker.style.borderBottomLeftRadius = "0";
782 [{}].forEach(function(item) {{
783 var but = document.createElement('button');
784 but.innerHTML = item;
785 but.onclick = function(el) {{
786 switchTheme(currentTheme, mainTheme, item);
788 themes.appendChild(but);
791 .map(|s| format!("\"{}\"", s))
792 .collect::<Vec<String>>()
793 .join(",")).as_bytes())?;
795 write(cx.dst.join("main.js"), include_bytes!("static/main.js"))?;
796 write(cx.dst.join("storage.js"), include_bytes!("static/storage.js"))?;
798 if let Some(ref css) = cx.shared.css_file_extension {
799 let out = cx.dst.join("theme.css");
800 try_err!(fs::copy(css, out), css);
802 write(cx.dst.join("normalize.css"),
803 include_bytes!("static/normalize.css"))?;
804 write(cx.dst.join("FiraSans-Regular.woff"),
805 include_bytes!("static/FiraSans-Regular.woff"))?;
806 write(cx.dst.join("FiraSans-Medium.woff"),
807 include_bytes!("static/FiraSans-Medium.woff"))?;
808 write(cx.dst.join("FiraSans-LICENSE.txt"),
809 include_bytes!("static/FiraSans-LICENSE.txt"))?;
810 write(cx.dst.join("Heuristica-Italic.woff"),
811 include_bytes!("static/Heuristica-Italic.woff"))?;
812 write(cx.dst.join("Heuristica-LICENSE.txt"),
813 include_bytes!("static/Heuristica-LICENSE.txt"))?;
814 write(cx.dst.join("SourceSerifPro-Regular.woff"),
815 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
816 write(cx.dst.join("SourceSerifPro-Bold.woff"),
817 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
818 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
819 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
820 write(cx.dst.join("SourceCodePro-Regular.woff"),
821 include_bytes!("static/SourceCodePro-Regular.woff"))?;
822 write(cx.dst.join("SourceCodePro-Semibold.woff"),
823 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
824 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
825 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
826 write(cx.dst.join("LICENSE-MIT.txt"),
827 include_bytes!("static/LICENSE-MIT.txt"))?;
828 write(cx.dst.join("LICENSE-APACHE.txt"),
829 include_bytes!("static/LICENSE-APACHE.txt"))?;
830 write(cx.dst.join("COPYRIGHT.txt"),
831 include_bytes!("static/COPYRIGHT.txt"))?;
833 fn collect(path: &Path, krate: &str,
834 key: &str) -> io::Result<Vec<String>> {
835 let mut ret = Vec::new();
837 for line in BufReader::new(File::open(path)?).lines() {
839 if !line.starts_with(key) {
842 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
845 ret.push(line.to_string());
851 // Update the search index
852 let dst = cx.dst.join("search-index.js");
853 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
854 all_indexes.push(search_index);
855 // Sort the indexes by crate so the file will be generated identically even
856 // with rustdoc running in parallel.
858 let mut w = try_err!(File::create(&dst), &dst);
859 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
860 for index in &all_indexes {
861 try_err!(writeln!(&mut w, "{}", *index), &dst);
863 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
865 // Update the list of all implementors for traits
866 let dst = cx.dst.join("implementors");
867 for (&did, imps) in &cache.implementors {
868 // Private modules can leak through to this phase of rustdoc, which
869 // could contain implementations for otherwise private types. In some
870 // rare cases we could find an implementation for an item which wasn't
871 // indexed, so we just skip this step in that case.
873 // FIXME: this is a vague explanation for why this can't be a `get`, in
874 // theory it should be...
875 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
877 None => match cache.external_paths.get(&did) {
883 let mut have_impls = false;
884 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
886 // If the trait and implementation are in the same crate, then
887 // there's no need to emit information about it (there's inlining
888 // going on). If they're in different crates then the crate defining
889 // the trait will be interested in our implementation.
890 if imp.impl_item.def_id.krate == did.krate { continue }
891 // If the implementation is from another crate then that crate
893 if !imp.impl_item.def_id.is_local() { continue }
895 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
896 as_json(&imp.inner_impl().to_string()),
897 imp.inner_impl().synthetic,
898 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
900 implementors.push_str("];");
902 // Only create a js file if we have impls to add to it. If the trait is
903 // documented locally though we always create the file to avoid dead
905 if !have_impls && !cache.paths.contains_key(&did) {
909 let mut mydst = dst.clone();
910 for part in &remote_path[..remote_path.len() - 1] {
913 try_err!(fs::create_dir_all(&mydst), &mydst);
914 mydst.push(&format!("{}.{}.js",
915 remote_item_type.css_class(),
916 remote_path[remote_path.len() - 1]));
918 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
919 all_implementors.push(implementors);
920 // Sort the implementors by crate so the file will be generated
921 // identically even with rustdoc running in parallel.
922 all_implementors.sort();
924 let mut f = try_err!(File::create(&mydst), &mydst);
925 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
926 for implementor in &all_implementors {
927 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
929 try_err!(writeln!(&mut f, "{}", r"
930 if (window.register_implementors) {
931 window.register_implementors(implementors);
933 window.pending_implementors = implementors;
936 try_err!(writeln!(&mut f, r"}})()"), &mydst);
941 fn render_sources(dst: &Path, scx: &mut SharedContext,
942 krate: clean::Crate) -> Result<clean::Crate, Error> {
943 info!("emitting source files");
944 let dst = dst.join("src").join(&krate.name);
945 try_err!(fs::create_dir_all(&dst), &dst);
946 let mut folder = SourceCollector {
950 Ok(folder.fold_crate(krate))
953 /// Writes the entire contents of a string to a destination, not attempting to
954 /// catch any errors.
955 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
956 Ok(try_err!(fs::write(&dst, contents), &dst))
959 /// Takes a path to a source file and cleans the path to it. This canonicalizes
960 /// things like ".." to components which preserve the "top down" hierarchy of a
961 /// static HTML tree. Each component in the cleaned path will be passed as an
962 /// argument to `f`. The very last component of the path (ie the file name) will
963 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
964 // FIXME (#9639): The closure should deal with &[u8] instead of &str
965 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
966 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
969 // make it relative, if possible
970 let p = p.strip_prefix(src_root).unwrap_or(p);
972 let mut iter = p.components().peekable();
974 while let Some(c) = iter.next() {
975 if !keep_filename && iter.peek().is_none() {
980 Component::ParentDir => f("up"),
981 Component::Normal(c) => f(c.to_str().unwrap()),
987 /// Attempts to find where an external crate is located, given that we're
988 /// rendering in to the specified source destination.
989 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
990 // See if there's documentation generated into the local directory
991 let local_location = dst.join(&e.name);
992 if local_location.is_dir() {
996 // Failing that, see if there's an attribute specifying where to find this
999 .filter(|a| a.check_name("html_root_url"))
1000 .filter_map(|a| a.value_str())
1002 let mut url = url.to_string();
1003 if !url.ends_with("/") {
1007 }).next().unwrap_or(Unknown) // Well, at least we tried.
1010 impl<'a> DocFolder for SourceCollector<'a> {
1011 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1012 // If we're including source files, and we haven't seen this file yet,
1013 // then we need to render it out to the filesystem.
1014 if self.scx.include_sources
1015 // skip all invalid or macro spans
1016 && item.source.filename.is_real()
1017 // skip non-local items
1018 && item.def_id.is_local() {
1020 // If it turns out that we couldn't read this file, then we probably
1021 // can't read any of the files (generating html output from json or
1022 // something like that), so just don't include sources for the
1023 // entire crate. The other option is maintaining this mapping on a
1024 // per-file basis, but that's probably not worth it...
1026 .include_sources = match self.emit_source(&item.source.filename) {
1029 println!("warning: source code was requested to be rendered, \
1030 but processing `{}` had an error: {}",
1031 item.source.filename, e);
1032 println!(" skipping rendering of source code");
1037 self.fold_item_recur(item)
1041 impl<'a> SourceCollector<'a> {
1042 /// Renders the given filename into its corresponding HTML source file.
1043 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1044 let p = match *filename {
1045 FileName::Real(ref file) => file,
1048 if self.scx.local_sources.contains_key(&**p) {
1049 // We've already emitted this source
1053 let contents = fs::read_string(&p)?;
1055 // Remove the utf-8 BOM if any
1056 let contents = if contents.starts_with("\u{feff}") {
1062 // Create the intermediate directories
1063 let mut cur = self.dst.clone();
1064 let mut root_path = String::from("../../");
1065 let mut href = String::new();
1066 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1067 cur.push(component);
1068 fs::create_dir_all(&cur).unwrap();
1069 root_path.push_str("../");
1070 href.push_str(component);
1073 let mut fname = p.file_name().expect("source has no filename")
1075 fname.push(".html");
1077 href.push_str(&fname.to_string_lossy());
1079 let mut w = BufWriter::new(File::create(&cur)?);
1080 let title = format!("{} -- source", cur.file_name().unwrap()
1081 .to_string_lossy());
1082 let desc = format!("Source to the Rust file `{}`.", filename);
1083 let page = layout::Page {
1085 css_class: "source",
1086 root_path: &root_path,
1088 keywords: BASIC_KEYWORDS,
1090 layout::render(&mut w, &self.scx.layout,
1091 &page, &(""), &Source(contents),
1092 self.scx.css_file_extension.is_some(),
1095 self.scx.local_sources.insert(p.clone(), href);
1100 impl DocFolder for Cache {
1101 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1102 // If this is a stripped module,
1103 // we don't want it or its children in the search index.
1104 let orig_stripped_mod = match item.inner {
1105 clean::StrippedItem(box clean::ModuleItem(..)) => {
1106 mem::replace(&mut self.stripped_mod, true)
1108 _ => self.stripped_mod,
1111 // If the impl is from a masked crate or references something from a
1112 // masked crate then remove it completely.
1113 if let clean::ImplItem(ref i) = item.inner {
1114 if self.masked_crates.contains(&item.def_id.krate) ||
1115 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1116 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1121 // Register any generics to their corresponding string. This is used
1122 // when pretty-printing types.
1123 if let Some(generics) = item.inner.generics() {
1124 self.generics(generics);
1127 // Propagate a trait method's documentation to all implementors of the
1129 if let clean::TraitItem(ref t) = item.inner {
1130 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1133 // Collect all the implementors of traits.
1134 if let clean::ImplItem(ref i) = item.inner {
1135 if let Some(did) = i.trait_.def_id() {
1136 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1137 impl_item: item.clone(),
1142 // Index this method for searching later on.
1143 if let Some(ref s) = item.name {
1144 let (parent, is_inherent_impl_item) = match item.inner {
1145 clean::StrippedItem(..) => ((None, None), false),
1146 clean::AssociatedConstItem(..) |
1147 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1148 // skip associated items in trait impls
1149 ((None, None), false)
1151 clean::AssociatedTypeItem(..) |
1152 clean::TyMethodItem(..) |
1153 clean::StructFieldItem(..) |
1154 clean::VariantItem(..) => {
1155 ((Some(*self.parent_stack.last().unwrap()),
1156 Some(&self.stack[..self.stack.len() - 1])),
1159 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1160 if self.parent_stack.is_empty() {
1161 ((None, None), false)
1163 let last = self.parent_stack.last().unwrap();
1165 let path = match self.paths.get(&did) {
1166 // The current stack not necessarily has correlation
1167 // for where the type was defined. On the other
1168 // hand, `paths` always has the right
1169 // information if present.
1170 Some(&(ref fqp, ItemType::Trait)) |
1171 Some(&(ref fqp, ItemType::Struct)) |
1172 Some(&(ref fqp, ItemType::Union)) |
1173 Some(&(ref fqp, ItemType::Enum)) =>
1174 Some(&fqp[..fqp.len() - 1]),
1175 Some(..) => Some(&*self.stack),
1178 ((Some(*last), path), true)
1181 _ => ((None, Some(&*self.stack)), false)
1185 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1186 debug_assert!(!item.is_stripped());
1188 // A crate has a module at its root, containing all items,
1189 // which should not be indexed. The crate-item itself is
1190 // inserted later on when serializing the search-index.
1191 if item.def_id.index != CRATE_DEF_INDEX {
1192 self.search_index.push(IndexItem {
1194 name: s.to_string(),
1195 path: path.join("::").to_string(),
1196 desc: plain_summary_line(item.doc_value()),
1199 search_type: get_index_search_type(&item),
1203 (Some(parent), None) if is_inherent_impl_item => {
1204 // We have a parent, but we don't know where they're
1205 // defined yet. Wait for later to index this item.
1206 self.orphan_impl_items.push((parent, item.clone()));
1212 // Keep track of the fully qualified path for this item.
1213 let pushed = match item.name {
1214 Some(ref n) if !n.is_empty() => {
1215 self.stack.push(n.to_string());
1222 clean::StructItem(..) | clean::EnumItem(..) |
1223 clean::TypedefItem(..) | clean::TraitItem(..) |
1224 clean::FunctionItem(..) | clean::ModuleItem(..) |
1225 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1226 clean::ConstantItem(..) | clean::StaticItem(..) |
1227 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1228 if !self.stripped_mod => {
1229 // Re-exported items mean that the same id can show up twice
1230 // in the rustdoc ast that we're looking at. We know,
1231 // however, that a re-exported item doesn't show up in the
1232 // `public_items` map, so we can skip inserting into the
1233 // paths map if there was already an entry present and we're
1234 // not a public item.
1236 !self.paths.contains_key(&item.def_id) ||
1237 self.access_levels.is_public(item.def_id)
1239 self.paths.insert(item.def_id,
1240 (self.stack.clone(), item.type_()));
1243 // Link variants to their parent enum because pages aren't emitted
1244 // for each variant.
1245 clean::VariantItem(..) if !self.stripped_mod => {
1246 let mut stack = self.stack.clone();
1248 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1251 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1252 self.paths.insert(item.def_id, (self.stack.clone(),
1259 // Maintain the parent stack
1260 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1261 let parent_pushed = match item.inner {
1262 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1263 clean::StructItem(..) | clean::UnionItem(..) => {
1264 self.parent_stack.push(item.def_id);
1265 self.parent_is_trait_impl = false;
1268 clean::ImplItem(ref i) => {
1269 self.parent_is_trait_impl = i.trait_.is_some();
1271 clean::ResolvedPath{ did, .. } => {
1272 self.parent_stack.push(did);
1276 let prim_did = t.primitive_type().and_then(|t| {
1277 self.primitive_locations.get(&t).cloned()
1281 self.parent_stack.push(did);
1292 // Once we've recursively found all the generics, hoard off all the
1293 // implementations elsewhere.
1294 let ret = self.fold_item_recur(item).and_then(|item| {
1295 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1296 // Figure out the id of this impl. This may map to a
1297 // primitive rather than always to a struct/enum.
1298 // Note: matching twice to restrict the lifetime of the `i` borrow.
1299 let mut dids = FxHashSet();
1300 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1302 clean::ResolvedPath { did, .. } |
1303 clean::BorrowedRef {
1304 type_: box clean::ResolvedPath { did, .. }, ..
1309 let did = t.primitive_type().and_then(|t| {
1310 self.primitive_locations.get(&t).cloned()
1313 if let Some(did) = did {
1319 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1320 for bound in generics {
1321 if let Some(did) = bound.def_id() {
1330 self.impls.entry(did).or_insert(vec![]).push(Impl {
1331 impl_item: item.clone(),
1340 if pushed { self.stack.pop().unwrap(); }
1341 if parent_pushed { self.parent_stack.pop().unwrap(); }
1342 self.stripped_mod = orig_stripped_mod;
1343 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1349 fn generics(&mut self, generics: &clean::Generics) {
1350 for param in &generics.params {
1351 if let clean::GenericParam::Type(ref typ) = *param {
1352 self.typarams.insert(typ.did, typ.name.clone());
1359 /// String representation of how to get back to the root path of the 'doc/'
1360 /// folder in terms of a relative URL.
1361 fn root_path(&self) -> String {
1362 repeat("../").take(self.current.len()).collect::<String>()
1365 /// Recurse in the directory structure and change the "root path" to make
1366 /// sure it always points to the top (relatively).
1367 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1368 F: FnOnce(&mut Context) -> T,
1371 panic!("Unexpected empty destination: {:?}", self.current);
1373 let prev = self.dst.clone();
1375 self.current.push(s);
1377 info!("Recursing into {}", self.dst.display());
1381 info!("Recursed; leaving {}", self.dst.display());
1383 // Go back to where we were at
1385 self.current.pop().unwrap();
1390 /// Main method for rendering a crate.
1392 /// This currently isn't parallelized, but it'd be pretty easy to add
1393 /// parallelization to this function.
1394 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1395 let mut item = match krate.module.take() {
1397 None => return Ok(()),
1399 item.name = Some(krate.name);
1401 // Render the crate documentation
1402 let mut work = vec![(self, item)];
1404 while let Some((mut cx, item)) = work.pop() {
1405 cx.item(item, |cx, item| {
1406 work.push((cx.clone(), item))
1412 fn render_item(&self,
1413 writer: &mut io::Write,
1417 // A little unfortunate that this is done like this, but it sure
1418 // does make formatting *a lot* nicer.
1419 CURRENT_LOCATION_KEY.with(|slot| {
1420 *slot.borrow_mut() = self.current.clone();
1423 let mut title = if it.is_primitive() {
1424 // No need to include the namespace for primitive types
1427 self.current.join("::")
1430 if !title.is_empty() {
1431 title.push_str("::");
1433 title.push_str(it.name.as_ref().unwrap());
1435 title.push_str(" - Rust");
1436 let tyname = it.type_().css_class();
1437 let desc = if it.is_crate() {
1438 format!("API documentation for the Rust `{}` crate.",
1439 self.shared.layout.krate)
1441 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1442 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1444 let keywords = make_item_keywords(it);
1445 let page = layout::Page {
1447 root_path: &self.root_path(),
1450 keywords: &keywords,
1455 if !self.render_redirect_pages {
1456 layout::render(writer, &self.shared.layout, &page,
1457 &Sidebar{ cx: self, item: it },
1458 &Item{ cx: self, item: it },
1459 self.shared.css_file_extension.is_some(),
1460 &self.shared.themes)?;
1462 let mut url = self.root_path();
1463 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1464 for name in &names[..names.len() - 1] {
1468 url.push_str(&item_path(ty, names.last().unwrap()));
1469 layout::redirect(writer, &url)?;
1475 /// Non-parallelized version of rendering an item. This will take the input
1476 /// item, render its contents, and then invoke the specified closure with
1477 /// all sub-items which need to be rendered.
1479 /// The rendering driver uses this closure to queue up more work.
1480 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1481 F: FnMut(&mut Context, clean::Item),
1483 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1484 // if they contain impls for public types. These modules can also
1485 // contain items such as publicly re-exported structures.
1487 // External crates will provide links to these structures, so
1488 // these modules are recursed into, but not rendered normally
1489 // (a flag on the context).
1490 if !self.render_redirect_pages {
1491 self.render_redirect_pages = item.is_stripped();
1495 // modules are special because they add a namespace. We also need to
1496 // recurse into the items of the module as well.
1497 let name = item.name.as_ref().unwrap().to_string();
1498 let mut item = Some(item);
1499 self.recurse(name, |this| {
1500 let item = item.take().unwrap();
1502 let mut buf = Vec::new();
1503 this.render_item(&mut buf, &item, false).unwrap();
1504 // buf will be empty if the module is stripped and there is no redirect for it
1505 if !buf.is_empty() {
1506 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1507 let joint_dst = this.dst.join("index.html");
1508 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1509 try_err!(dst.write_all(&buf), &joint_dst);
1512 let m = match item.inner {
1513 clean::StrippedItem(box clean::ModuleItem(m)) |
1514 clean::ModuleItem(m) => m,
1518 // Render sidebar-items.js used throughout this module.
1519 if !this.render_redirect_pages {
1520 let items = this.build_sidebar_items(&m);
1521 let js_dst = this.dst.join("sidebar-items.js");
1522 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1523 try_err!(write!(&mut js_out, "initSidebarItems({});",
1524 as_json(&items)), &js_dst);
1527 for item in m.items {
1533 } else if item.name.is_some() {
1534 let mut buf = Vec::new();
1535 self.render_item(&mut buf, &item, true).unwrap();
1536 // buf will be empty if the item is stripped and there is no redirect for it
1537 if !buf.is_empty() {
1538 let name = item.name.as_ref().unwrap();
1539 let item_type = item.type_();
1540 let file_name = &item_path(item_type, name);
1541 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1542 let joint_dst = self.dst.join(file_name);
1543 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1544 try_err!(dst.write_all(&buf), &joint_dst);
1546 // Redirect from a sane URL using the namespace to Rustdoc's
1547 // URL for the page.
1548 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1549 let redir_dst = self.dst.join(redir_name);
1550 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1553 let mut redirect_out = BufWriter::new(redirect_out);
1554 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1557 // If the item is a macro, redirect from the old macro URL (with !)
1558 // to the new one (without).
1559 // FIXME(#35705) remove this redirect.
1560 if item_type == ItemType::Macro {
1561 let redir_name = format!("{}.{}!.html", item_type, name);
1562 let redir_dst = self.dst.join(redir_name);
1563 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1564 let mut redirect_out = BufWriter::new(redirect_out);
1565 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1572 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1573 // BTreeMap instead of HashMap to get a sorted output
1574 let mut map = BTreeMap::new();
1575 for item in &m.items {
1576 if item.is_stripped() { continue }
1578 let short = item.type_().css_class();
1579 let myname = match item.name {
1581 Some(ref s) => s.to_string(),
1583 let short = short.to_string();
1584 map.entry(short).or_insert(vec![])
1585 .push((myname, Some(plain_summary_line(item.doc_value()))));
1588 if self.shared.sort_modules_alphabetically {
1589 for (_, items) in &mut map {
1598 /// Generate a url appropriate for an `href` attribute back to the source of
1601 /// The url generated, when clicked, will redirect the browser back to the
1602 /// original source code.
1604 /// If `None` is returned, then a source link couldn't be generated. This
1605 /// may happen, for example, with externally inlined items where the source
1606 /// of their crate documentation isn't known.
1607 fn src_href(&self) -> Option<String> {
1608 let mut root = self.cx.root_path();
1610 let cache = cache();
1611 let mut path = String::new();
1613 // We can safely ignore macros from other libraries
1614 let file = match self.item.source.filename {
1615 FileName::Real(ref path) => path,
1619 let (krate, path) = if self.item.def_id.is_local() {
1620 if let Some(path) = self.cx.shared.local_sources.get(file) {
1621 (&self.cx.shared.layout.krate, path)
1626 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1627 Some(&(ref name, ref src, Local)) => (name, src),
1628 Some(&(ref name, ref src, Remote(ref s))) => {
1629 root = s.to_string();
1632 Some(&(_, _, Unknown)) | None => return None,
1635 clean_srcpath(&src_root, file, false, |component| {
1636 path.push_str(component);
1639 let mut fname = file.file_name().expect("source has no filename")
1641 fname.push(".html");
1642 path.push_str(&fname.to_string_lossy());
1646 let lines = if self.item.source.loline == self.item.source.hiline {
1647 format!("{}", self.item.source.loline)
1649 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1651 Some(format!("{root}src/{krate}/{path}#{lines}",
1652 root = Escape(&root),
1659 impl<'a> fmt::Display for Item<'a> {
1660 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1661 debug_assert!(!self.item.is_stripped());
1662 // Write the breadcrumb trail header for the top
1663 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1664 match self.item.inner {
1665 clean::ModuleItem(ref m) => if m.is_crate {
1666 write!(fmt, "Crate ")?;
1668 write!(fmt, "Module ")?;
1670 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1671 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1672 clean::StructItem(..) => write!(fmt, "Struct ")?,
1673 clean::UnionItem(..) => write!(fmt, "Union ")?,
1674 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1675 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1676 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1677 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1678 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1679 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1680 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1682 // We don't generate pages for any other type.
1686 if !self.item.is_primitive() {
1687 let cur = &self.cx.current;
1688 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1689 for (i, component) in cur.iter().enumerate().take(amt) {
1690 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1691 repeat("../").take(cur.len() - i - 1)
1692 .collect::<String>(),
1696 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1697 self.item.type_(), self.item.name.as_ref().unwrap())?;
1699 write!(fmt, "</span>")?; // in-band
1700 write!(fmt, "<span class='out-of-band'>")?;
1701 if let Some(version) = self.item.stable_since() {
1702 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1706 r##"<span id='render-detail'>
1707 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1708 [<span class='inner'>−</span>]
1714 // When this item is part of a `pub use` in a downstream crate, the
1715 // [src] link in the downstream documentation will actually come back to
1716 // this page, and this link will be auto-clicked. The `id` attribute is
1717 // used to find the link to auto-click.
1718 if self.cx.shared.include_sources && !self.item.is_primitive() {
1719 if let Some(l) = self.src_href() {
1720 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1721 l, "goto source code")?;
1725 write!(fmt, "</span>")?; // out-of-band
1727 write!(fmt, "</h1>\n")?;
1729 match self.item.inner {
1730 clean::ModuleItem(ref m) => {
1731 item_module(fmt, self.cx, self.item, &m.items)
1733 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1734 item_function(fmt, self.cx, self.item, f),
1735 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1736 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1737 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1738 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1739 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1740 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1741 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1742 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1743 item_static(fmt, self.cx, self.item, i),
1744 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1745 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1747 // We don't generate pages for any other type.
1754 fn item_path(ty: ItemType, name: &str) -> String {
1756 ItemType::Module => format!("{}/index.html", name),
1757 _ => format!("{}.{}.html", ty.css_class(), name),
1761 fn full_path(cx: &Context, item: &clean::Item) -> String {
1762 let mut s = cx.current.join("::");
1764 s.push_str(item.name.as_ref().unwrap());
1768 fn shorter<'a>(s: Option<&'a str>) -> String {
1770 Some(s) => s.lines()
1771 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1773 (*line).chars().any(|chr|{
1774 !chr.is_whitespace()
1776 }).collect::<Vec<_>>().join("\n"),
1777 None => "".to_string()
1782 fn plain_summary_line(s: Option<&str>) -> String {
1783 let line = shorter(s).replace("\n", " ");
1784 markdown::plain_summary_line(&line[..])
1787 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1788 if let Some(ref name) = item.name {
1789 info!("Documenting {}", name);
1791 document_stability(w, cx, item)?;
1792 let prefix = render_assoc_const_value(item);
1793 document_full(w, item, cx, &prefix)?;
1797 /// Render md_text as markdown.
1798 fn render_markdown(w: &mut fmt::Formatter,
1800 links: Vec<(String, String)>,
1803 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1806 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1807 prefix: &str) -> fmt::Result {
1808 if let Some(s) = item.doc_value() {
1809 let markdown = if s.contains('\n') {
1810 format!("{} [Read more]({})",
1811 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1813 format!("{}", &plain_summary_line(Some(s)))
1815 render_markdown(w, &markdown, item.links(), prefix)?;
1816 } else if !prefix.is_empty() {
1817 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1822 fn render_assoc_const_value(item: &clean::Item) -> String {
1824 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1825 highlight::render_with_highlighting(
1826 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1837 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1838 cx: &Context, prefix: &str) -> fmt::Result {
1839 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1840 debug!("Doc block: =====\n{}\n=====", s);
1841 render_markdown(w, &*s, item.links(), prefix)?;
1842 } else if !prefix.is_empty() {
1843 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1848 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1849 let stabilities = short_stability(item, cx, true);
1850 if !stabilities.is_empty() {
1851 write!(w, "<div class='stability'>")?;
1852 for stability in stabilities {
1853 write!(w, "{}", stability)?;
1855 write!(w, "</div>")?;
1860 fn name_key(name: &str) -> (&str, u64, usize) {
1861 // find number at end
1862 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1864 // count leading zeroes
1866 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1868 // sort leading zeroes last
1869 let num_zeroes = after_zeroes - split;
1871 match name[split..].parse() {
1872 Ok(n) => (&name[..split], n, num_zeroes),
1873 Err(_) => (name, 0, num_zeroes),
1877 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1878 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1879 document(w, cx, item)?;
1881 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1883 // the order of item types in the listing
1884 fn reorder(ty: ItemType) -> u8 {
1886 ItemType::ExternCrate => 0,
1887 ItemType::Import => 1,
1888 ItemType::Primitive => 2,
1889 ItemType::Module => 3,
1890 ItemType::Macro => 4,
1891 ItemType::Struct => 5,
1892 ItemType::Enum => 6,
1893 ItemType::Constant => 7,
1894 ItemType::Static => 8,
1895 ItemType::Trait => 9,
1896 ItemType::Function => 10,
1897 ItemType::Typedef => 12,
1898 ItemType::Union => 13,
1903 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1904 let ty1 = i1.type_();
1905 let ty2 = i2.type_();
1907 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1909 let s1 = i1.stability.as_ref().map(|s| s.level);
1910 let s2 = i2.stability.as_ref().map(|s| s.level);
1912 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1913 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1916 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1917 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1918 name_key(lhs).cmp(&name_key(rhs))
1921 if cx.shared.sort_modules_alphabetically {
1922 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1924 // This call is to remove re-export duplicates in cases such as:
1929 // pub trait Double { fn foo(); }
1933 // pub use foo::bar::*;
1937 // `Double` will appear twice in the generated docs.
1939 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1940 // can be identical even if the elements are different (mostly in imports).
1941 // So in case this is an import, we keep everything by adding a "unique id"
1942 // (which is the position in the vector).
1943 indices.dedup_by_key(|i| (items[*i].def_id,
1944 if items[*i].name.as_ref().is_some() {
1945 Some(full_path(cx, &items[*i]).clone())
1950 if items[*i].is_import() {
1956 debug!("{:?}", indices);
1957 let mut curty = None;
1958 for &idx in &indices {
1959 let myitem = &items[idx];
1960 if myitem.is_stripped() {
1964 let myty = Some(myitem.type_());
1965 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1966 // Put `extern crate` and `use` re-exports in the same section.
1968 } else if myty != curty {
1969 if curty.is_some() {
1970 write!(w, "</table>")?;
1973 let (short, name) = match myty.unwrap() {
1974 ItemType::ExternCrate |
1975 ItemType::Import => ("reexports", "Re-exports"),
1976 ItemType::Module => ("modules", "Modules"),
1977 ItemType::Struct => ("structs", "Structs"),
1978 ItemType::Union => ("unions", "Unions"),
1979 ItemType::Enum => ("enums", "Enums"),
1980 ItemType::Function => ("functions", "Functions"),
1981 ItemType::Typedef => ("types", "Type Definitions"),
1982 ItemType::Static => ("statics", "Statics"),
1983 ItemType::Constant => ("constants", "Constants"),
1984 ItemType::Trait => ("traits", "Traits"),
1985 ItemType::Impl => ("impls", "Implementations"),
1986 ItemType::TyMethod => ("tymethods", "Type Methods"),
1987 ItemType::Method => ("methods", "Methods"),
1988 ItemType::StructField => ("fields", "Struct Fields"),
1989 ItemType::Variant => ("variants", "Variants"),
1990 ItemType::Macro => ("macros", "Macros"),
1991 ItemType::Primitive => ("primitives", "Primitive Types"),
1992 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1993 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1994 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
1996 write!(w, "<h2 id='{id}' class='section-header'>\
1997 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1998 id = derive_id(short.to_owned()), name = name)?;
2001 match myitem.inner {
2002 clean::ExternCrateItem(ref name, ref src) => {
2003 use html::format::HRef;
2007 write!(w, "<tr><td><code>{}extern crate {} as {};",
2008 VisSpace(&myitem.visibility),
2009 HRef::new(myitem.def_id, src),
2013 write!(w, "<tr><td><code>{}extern crate {};",
2014 VisSpace(&myitem.visibility),
2015 HRef::new(myitem.def_id, name))?
2018 write!(w, "</code></td></tr>")?;
2021 clean::ImportItem(ref import) => {
2022 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2023 VisSpace(&myitem.visibility), *import)?;
2027 if myitem.name.is_none() { continue }
2029 let stabilities = short_stability(myitem, cx, false);
2031 let stab_docs = if !stabilities.is_empty() {
2033 .map(|s| format!("[{}]", s))
2034 .collect::<Vec<_>>()
2041 let unsafety_flag = match myitem.inner {
2042 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2043 if func.unsafety == hir::Unsafety::Unsafe => {
2044 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2049 let doc_value = myitem.doc_value().unwrap_or("");
2051 <tr class='{stab} module-item'>
2052 <td><a class=\"{class}\" href=\"{href}\"
2053 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2054 <td class='docblock-short'>
2058 name = *myitem.name.as_ref().unwrap(),
2059 stab_docs = stab_docs,
2060 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2061 class = myitem.type_(),
2062 stab = myitem.stability_class().unwrap_or("".to_string()),
2063 unsafety_flag = unsafety_flag,
2064 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2065 title_type = myitem.type_(),
2066 title = full_path(cx, myitem))?;
2071 if curty.is_some() {
2072 write!(w, "</table>")?;
2077 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2078 let mut stability = vec![];
2080 if let Some(stab) = item.stability.as_ref() {
2081 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2082 format!(": {}", stab.deprecated_reason)
2086 if !stab.deprecated_since.is_empty() {
2087 let since = if show_reason {
2088 format!(" since {}", Escape(&stab.deprecated_since))
2092 let text = format!("Deprecated{}{}",
2094 MarkdownHtml(&deprecated_reason));
2095 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2098 if stab.level == stability::Unstable {
2100 let unstable_extra = match (!stab.feature.is_empty(),
2101 &cx.shared.issue_tracker_base_url,
2103 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2104 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2105 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2106 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2107 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2110 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2113 if stab.unstable_reason.is_empty() {
2114 stability.push(format!("<div class='stab unstable'>\
2115 <span class=microscope>🔬</span> \
2116 This is a nightly-only experimental API. {}\
2120 let text = format!("<summary><span class=microscope>🔬</span> \
2121 This is a nightly-only experimental API. {}\
2124 MarkdownHtml(&stab.unstable_reason));
2125 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2129 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2132 } else if let Some(depr) = item.deprecation.as_ref() {
2133 let note = if show_reason && !depr.note.is_empty() {
2134 format!(": {}", depr.note)
2138 let since = if show_reason && !depr.since.is_empty() {
2139 format!(" since {}", Escape(&depr.since))
2144 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e));
2145 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2148 if let Some(ref cfg) = item.attrs.cfg {
2149 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2150 cfg.render_long_html()
2152 cfg.render_short_html()
2159 struct Initializer<'a>(&'a str);
2161 impl<'a> fmt::Display for Initializer<'a> {
2162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2163 let Initializer(s) = *self;
2164 if s.is_empty() { return Ok(()); }
2165 write!(f, "<code> = </code>")?;
2166 write!(f, "<code>{}</code>", Escape(s))
2170 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2171 c: &clean::Constant) -> fmt::Result {
2172 write!(w, "<pre class='rust const'>")?;
2173 render_attributes(w, it)?;
2174 write!(w, "{vis}const \
2175 {name}: {typ}{init}</pre>",
2176 vis = VisSpace(&it.visibility),
2177 name = it.name.as_ref().unwrap(),
2179 init = Initializer(&c.expr))?;
2183 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2184 s: &clean::Static) -> fmt::Result {
2185 write!(w, "<pre class='rust static'>")?;
2186 render_attributes(w, it)?;
2187 write!(w, "{vis}static {mutability}\
2188 {name}: {typ}{init}</pre>",
2189 vis = VisSpace(&it.visibility),
2190 mutability = MutableSpace(s.mutability),
2191 name = it.name.as_ref().unwrap(),
2193 init = Initializer(&s.expr))?;
2197 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2198 f: &clean::Function) -> fmt::Result {
2199 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2200 VisSpace(&it.visibility),
2201 ConstnessSpace(f.constness),
2202 UnsafetySpace(f.unsafety),
2204 it.name.as_ref().unwrap(),
2206 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2207 render_attributes(w, it)?;
2209 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2210 vis = VisSpace(&it.visibility),
2211 constness = ConstnessSpace(f.constness),
2212 unsafety = UnsafetySpace(f.unsafety),
2213 abi = AbiSpace(f.abi),
2214 name = it.name.as_ref().unwrap(),
2215 generics = f.generics,
2216 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2225 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2226 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2228 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2229 write!(w, "<div class='out-of-band'>")?;
2230 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2231 l, "goto source code")?;
2232 write!(w, "</div>")?;
2234 write!(w, "<code>")?;
2235 // If there's already another implementor that has the same abbridged name, use the
2236 // full path, for example in `std::iter::ExactSizeIterator`
2237 let use_absolute = match implementor.inner_impl().for_ {
2238 clean::ResolvedPath { ref path, is_generic: false, .. } |
2239 clean::BorrowedRef {
2240 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2242 } => implementor_dups[path.last_name()].1,
2245 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2246 for it in &implementor.inner_impl().items {
2247 if let clean::TypedefItem(ref tydef, _) = it.inner {
2248 write!(w, "<span class=\"where fmt-newline\"> ")?;
2249 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2250 write!(w, ";</span>")?;
2253 writeln!(w, "</code></li>")?;
2257 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2258 traits: Vec<&&Impl>,
2259 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2261 let did = i.trait_did().unwrap();
2262 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2263 render_impl(w, cx, i, assoc_link,
2264 RenderMode::Normal, containing_item.stable_since(), true)?;
2269 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2270 t: &clean::Trait) -> fmt::Result {
2271 let mut bounds = String::new();
2272 let mut bounds_plain = String::new();
2273 if !t.bounds.is_empty() {
2274 if !bounds.is_empty() {
2276 bounds_plain.push(' ');
2278 bounds.push_str(": ");
2279 bounds_plain.push_str(": ");
2280 for (i, p) in t.bounds.iter().enumerate() {
2282 bounds.push_str(" + ");
2283 bounds_plain.push_str(" + ");
2285 bounds.push_str(&format!("{}", *p));
2286 bounds_plain.push_str(&format!("{:#}", *p));
2290 // Output the trait definition
2291 write!(w, "<pre class='rust trait'>")?;
2292 render_attributes(w, it)?;
2293 write!(w, "{}{}{}trait {}{}{}",
2294 VisSpace(&it.visibility),
2295 UnsafetySpace(t.unsafety),
2296 if t.is_auto { "auto " } else { "" },
2297 it.name.as_ref().unwrap(),
2301 if !t.generics.where_predicates.is_empty() {
2302 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2307 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2308 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2309 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2310 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2312 if t.items.is_empty() {
2313 write!(w, "{{ }}")?;
2315 // FIXME: we should be using a derived_id for the Anchors here
2319 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2322 if !types.is_empty() && !consts.is_empty() {
2327 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2330 if !consts.is_empty() && !required.is_empty() {
2333 for (pos, m) in required.iter().enumerate() {
2335 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2338 if pos < required.len() - 1 {
2339 write!(w, "<div class='item-spacer'></div>")?;
2342 if !required.is_empty() && !provided.is_empty() {
2345 for (pos, m) in provided.iter().enumerate() {
2347 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2349 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2350 write!(w, ",\n {{ ... }}\n")?;
2353 write!(w, " {{ ... }}\n")?;
2356 if pos < provided.len() - 1 {
2357 write!(w, "<div class='item-spacer'></div>")?;
2362 write!(w, "</pre>")?;
2364 // Trait documentation
2365 document(w, cx, it)?;
2367 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2369 let name = m.name.as_ref().unwrap();
2370 let item_type = m.type_();
2371 let id = derive_id(format!("{}.{}", item_type, name));
2372 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2373 write!(w, "{extra}<h3 id='{id}' class='method'>\
2374 <span id='{ns_id}' class='invisible'><code>",
2375 extra = render_spotlight_traits(m)?,
2378 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2379 write!(w, "</code>")?;
2380 render_stability_since(w, m, t)?;
2381 write!(w, "</span></h3>")?;
2382 document(w, cx, m)?;
2386 if !types.is_empty() {
2388 <h2 id='associated-types' class='small-section-header'>
2389 Associated Types<a href='#associated-types' class='anchor'></a>
2391 <div class='methods'>
2394 trait_item(w, cx, *t, it)?;
2396 write!(w, "</div>")?;
2399 if !consts.is_empty() {
2401 <h2 id='associated-const' class='small-section-header'>
2402 Associated Constants<a href='#associated-const' class='anchor'></a>
2404 <div class='methods'>
2407 trait_item(w, cx, *t, it)?;
2409 write!(w, "</div>")?;
2412 // Output the documentation for each function individually
2413 if !required.is_empty() {
2415 <h2 id='required-methods' class='small-section-header'>
2416 Required Methods<a href='#required-methods' class='anchor'></a>
2418 <div class='methods'>
2420 for m in &required {
2421 trait_item(w, cx, *m, it)?;
2423 write!(w, "</div>")?;
2425 if !provided.is_empty() {
2427 <h2 id='provided-methods' class='small-section-header'>
2428 Provided Methods<a href='#provided-methods' class='anchor'></a>
2430 <div class='methods'>
2432 for m in &provided {
2433 trait_item(w, cx, *m, it)?;
2435 write!(w, "</div>")?;
2438 // If there are methods directly on this trait object, render them here.
2439 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2441 let cache = cache();
2443 <h2 id='implementors' class='small-section-header'>
2444 Implementors<a href='#implementors' class='anchor'></a>
2446 <ul class='item-list' id='implementors-list'>
2449 let synthetic_impl_header = "
2450 <h2 id='synthetic-implementors' class='small-section-header'>
2451 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2453 <ul class='item-list' id='synthetic-implementors-list'>
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 render_implementor(cx, implementor, w, &implementor_dups)?;
2513 write!(w, "</ul>")?;
2516 write!(w, r#"<script type="text/javascript">
2517 window.inlined_types=new Set();"#)?;
2519 write!(w, r#"<script type="text/javascript" async
2520 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2522 root_path = vec![".."; cx.current.len()].join("/"),
2523 path = if it.def_id.is_local() {
2524 cx.current.join("/")
2526 let (ref path, _) = cache.external_paths[&it.def_id];
2527 path[..path.len() - 1].join("/")
2529 ty = it.type_().css_class(),
2530 name = *it.name.as_ref().unwrap())?;
2532 // even without any implementations to write in, we still want the heading and list, so the
2533 // implementors javascript file pulled in below has somewhere to write the impls into
2534 write!(w, "{}", impl_header)?;
2535 write!(w, "</ul>")?;
2537 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set();</script>"#)?;
2540 write!(w, "{}", synthetic_impl_header)?;
2541 write!(w, "</ul>")?;
2545 write!(w, r#"<script type="text/javascript" async
2546 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2548 root_path = vec![".."; cx.current.len()].join("/"),
2549 path = if it.def_id.is_local() {
2550 cx.current.join("/")
2552 let (ref path, _) = cache.external_paths[&it.def_id];
2553 path[..path.len() - 1].join("/")
2555 ty = it.type_().css_class(),
2556 name = *it.name.as_ref().unwrap())?;
2560 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2561 use html::item_type::ItemType::*;
2563 let name = it.name.as_ref().unwrap();
2564 let ty = match it.type_() {
2565 Typedef | AssociatedType => AssociatedType,
2569 let anchor = format!("#{}.{}", ty, name);
2571 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2572 AssocItemLink::Anchor(None) => anchor,
2573 AssocItemLink::GotoSource(did, _) => {
2574 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2579 fn assoc_const(w: &mut fmt::Formatter,
2582 _default: Option<&String>,
2583 link: AssocItemLink) -> fmt::Result {
2584 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2585 VisSpace(&it.visibility),
2586 naive_assoc_href(it, link),
2587 it.name.as_ref().unwrap(),
2592 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2593 bounds: &Vec<clean::TyParamBound>,
2594 default: Option<&clean::Type>,
2595 link: AssocItemLink) -> fmt::Result {
2596 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2597 naive_assoc_href(it, link),
2598 it.name.as_ref().unwrap())?;
2599 if !bounds.is_empty() {
2600 write!(w, ": {}", TyParamBounds(bounds))?
2602 if let Some(default) = default {
2603 write!(w, " = {}", default)?;
2608 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2609 ver: Option<&'a str>,
2610 containing_ver: Option<&'a str>) -> fmt::Result {
2611 if let Some(v) = ver {
2612 if containing_ver != ver && v.len() > 0 {
2613 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2620 fn render_stability_since(w: &mut fmt::Formatter,
2622 containing_item: &clean::Item) -> fmt::Result {
2623 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2626 fn render_assoc_item(w: &mut fmt::Formatter,
2628 link: AssocItemLink,
2629 parent: ItemType) -> fmt::Result {
2630 fn method(w: &mut fmt::Formatter,
2632 unsafety: hir::Unsafety,
2633 constness: hir::Constness,
2635 g: &clean::Generics,
2637 link: AssocItemLink,
2640 let name = meth.name.as_ref().unwrap();
2641 let anchor = format!("#{}.{}", meth.type_(), name);
2642 let href = match link {
2643 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2644 AssocItemLink::Anchor(None) => anchor,
2645 AssocItemLink::GotoSource(did, provided_methods) => {
2646 // We're creating a link from an impl-item to the corresponding
2647 // trait-item and need to map the anchored type accordingly.
2648 let ty = if provided_methods.contains(name) {
2654 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2657 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2658 VisSpace(&meth.visibility),
2659 ConstnessSpace(constness),
2660 UnsafetySpace(unsafety),
2664 let (indent, end_newline) = if parent == ItemType::Trait {
2670 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2671 {generics}{decl}{where_clause}",
2672 VisSpace(&meth.visibility),
2673 ConstnessSpace(constness),
2674 UnsafetySpace(unsafety),
2684 where_clause = WhereClause {
2691 clean::StrippedItem(..) => Ok(()),
2692 clean::TyMethodItem(ref m) => {
2693 method(w, item, m.unsafety, hir::Constness::NotConst,
2694 m.abi, &m.generics, &m.decl, link, parent)
2696 clean::MethodItem(ref m) => {
2697 method(w, item, m.unsafety, m.constness,
2698 m.abi, &m.generics, &m.decl, link, parent)
2700 clean::AssociatedConstItem(ref ty, ref default) => {
2701 assoc_const(w, item, ty, default.as_ref(), link)
2703 clean::AssociatedTypeItem(ref bounds, ref default) => {
2704 assoc_type(w, item, bounds, default.as_ref(), link)
2706 _ => panic!("render_assoc_item called on non-associated-item")
2710 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2711 s: &clean::Struct) -> fmt::Result {
2712 write!(w, "<pre class='rust struct'>")?;
2713 render_attributes(w, it)?;
2721 write!(w, "</pre>")?;
2723 document(w, cx, it)?;
2724 let mut fields = s.fields.iter().filter_map(|f| {
2726 clean::StructFieldItem(ref ty) => Some((f, ty)),
2730 if let doctree::Plain = s.struct_type {
2731 if fields.peek().is_some() {
2732 write!(w, "<h2 id='fields' class='fields small-section-header'>
2733 Fields<a href='#fields' class='anchor'></a></h2>")?;
2734 for (field, ty) in fields {
2735 let id = derive_id(format!("{}.{}",
2736 ItemType::StructField,
2737 field.name.as_ref().unwrap()));
2738 let ns_id = derive_id(format!("{}.{}",
2739 field.name.as_ref().unwrap(),
2740 ItemType::StructField.name_space()));
2741 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2742 <a href=\"#{id}\" class=\"anchor field\"></a>
2743 <span id=\"{ns_id}\" class='invisible'>
2744 <code>{name}: {ty}</code>
2746 item_type = ItemType::StructField,
2749 name = field.name.as_ref().unwrap(),
2751 if let Some(stability_class) = field.stability_class() {
2752 write!(w, "<span class='stab {stab}'></span>",
2753 stab = stability_class)?;
2755 document(w, cx, field)?;
2759 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2762 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2763 s: &clean::Union) -> fmt::Result {
2764 write!(w, "<pre class='rust union'>")?;
2765 render_attributes(w, it)?;
2772 write!(w, "</pre>")?;
2774 document(w, cx, it)?;
2775 let mut fields = s.fields.iter().filter_map(|f| {
2777 clean::StructFieldItem(ref ty) => Some((f, ty)),
2781 if fields.peek().is_some() {
2782 write!(w, "<h2 id='fields' class='fields small-section-header'>
2783 Fields<a href='#fields' class='anchor'></a></h2>")?;
2784 for (field, ty) in fields {
2785 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2787 shortty = ItemType::StructField,
2788 name = field.name.as_ref().unwrap(),
2790 if let Some(stability_class) = field.stability_class() {
2791 write!(w, "<span class='stab {stab}'></span>",
2792 stab = stability_class)?;
2794 document(w, cx, field)?;
2797 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2800 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2801 e: &clean::Enum) -> fmt::Result {
2802 write!(w, "<pre class='rust enum'>")?;
2803 render_attributes(w, it)?;
2804 write!(w, "{}enum {}{}{}",
2805 VisSpace(&it.visibility),
2806 it.name.as_ref().unwrap(),
2808 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2809 if e.variants.is_empty() && !e.variants_stripped {
2810 write!(w, " {{}}")?;
2812 write!(w, " {{\n")?;
2813 for v in &e.variants {
2815 let name = v.name.as_ref().unwrap();
2817 clean::VariantItem(ref var) => {
2819 clean::VariantKind::CLike => write!(w, "{}", name)?,
2820 clean::VariantKind::Tuple(ref tys) => {
2821 write!(w, "{}(", name)?;
2822 for (i, ty) in tys.iter().enumerate() {
2824 write!(w, ", ")?
2826 write!(w, "{}", *ty)?;
2830 clean::VariantKind::Struct(ref s) => {
2846 if e.variants_stripped {
2847 write!(w, " // some variants omitted\n")?;
2851 write!(w, "</pre>")?;
2853 document(w, cx, it)?;
2854 if !e.variants.is_empty() {
2855 write!(w, "<h2 id='variants' class='variants small-section-header'>
2856 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2857 for variant in &e.variants {
2858 let id = derive_id(format!("{}.{}",
2860 variant.name.as_ref().unwrap()));
2861 let ns_id = derive_id(format!("{}.{}",
2862 variant.name.as_ref().unwrap(),
2863 ItemType::Variant.name_space()));
2864 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2865 <a href=\"#{id}\" class=\"anchor field\"></a>\
2866 <span id='{ns_id}' class='invisible'><code>{name}",
2869 name = variant.name.as_ref().unwrap())?;
2870 if let clean::VariantItem(ref var) = variant.inner {
2871 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2873 for (i, ty) in tys.iter().enumerate() {
2875 write!(w, ", ")?;
2877 write!(w, "{}", *ty)?;
2882 write!(w, "</code></span></span>")?;
2883 document(w, cx, variant)?;
2885 use clean::{Variant, VariantKind};
2886 if let clean::VariantItem(Variant {
2887 kind: VariantKind::Struct(ref s)
2888 }) = variant.inner {
2889 let variant_id = derive_id(format!("{}.{}.fields",
2891 variant.name.as_ref().unwrap()));
2892 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2894 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2895 <table>", name = variant.name.as_ref().unwrap())?;
2896 for field in &s.fields {
2897 use clean::StructFieldItem;
2898 if let StructFieldItem(ref ty) = field.inner {
2899 let id = derive_id(format!("variant.{}.field.{}",
2900 variant.name.as_ref().unwrap(),
2901 field.name.as_ref().unwrap()));
2902 let ns_id = derive_id(format!("{}.{}.{}.{}",
2903 variant.name.as_ref().unwrap(),
2904 ItemType::Variant.name_space(),
2905 field.name.as_ref().unwrap(),
2906 ItemType::StructField.name_space()));
2907 write!(w, "<tr><td \
2909 <span id='{ns_id}' class='invisible'>\
2910 <code>{f}: {t}</code></span></td><td>",
2913 f = field.name.as_ref().unwrap(),
2915 document(w, cx, field)?;
2916 write!(w, "</td></tr>")?;
2919 write!(w, "</table></span>")?;
2921 render_stability_since(w, variant, it)?;
2924 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2928 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2929 let name = attr.name();
2932 Some(format!("{}", name))
2933 } else if let Some(v) = attr.value_str() {
2934 Some(format!("{} = {:?}", name, v.as_str()))
2935 } else if let Some(values) = attr.meta_item_list() {
2936 let display: Vec<_> = values.iter().filter_map(|attr| {
2937 attr.meta_item().and_then(|mi| render_attribute(mi))
2940 if display.len() > 0 {
2941 Some(format!("{}({})", name, display.join(", ")))
2950 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2957 "unsafe_destructor_blind_to_params"
2960 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2961 let mut attrs = String::new();
2963 for attr in &it.attrs.other_attrs {
2964 let name = attr.name().unwrap();
2965 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2968 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2969 attrs.push_str(&format!("#[{}]\n", s));
2972 if attrs.len() > 0 {
2973 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2978 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2979 g: Option<&clean::Generics>,
2980 ty: doctree::StructType,
2981 fields: &[clean::Item],
2983 structhead: bool) -> fmt::Result {
2985 VisSpace(&it.visibility),
2986 if structhead {"struct "} else {""},
2987 it.name.as_ref().unwrap())?;
2988 if let Some(g) = g {
2993 if let Some(g) = g {
2994 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2996 let mut has_visible_fields = false;
2998 for field in fields {
2999 if let clean::StructFieldItem(ref ty) = field.inner {
3000 write!(w, "\n{} {}{}: {},",
3002 VisSpace(&field.visibility),
3003 field.name.as_ref().unwrap(),
3005 has_visible_fields = true;
3009 if has_visible_fields {
3010 if it.has_stripped_fields().unwrap() {
3011 write!(w, "\n{} // some fields omitted", tab)?;
3013 write!(w, "\n{}", tab)?;
3014 } else if it.has_stripped_fields().unwrap() {
3015 // If there are no visible fields we can just display
3016 // `{ /* fields omitted */ }` to save space.
3017 write!(w, " /* fields omitted */ ")?;
3023 for (i, field) in fields.iter().enumerate() {
3028 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3031 clean::StructFieldItem(ref ty) => {
3032 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3038 if let Some(g) = g {
3039 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3044 // Needed for PhantomData.
3045 if let Some(g) = g {
3046 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3054 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3055 g: Option<&clean::Generics>,
3056 fields: &[clean::Item],
3058 structhead: bool) -> fmt::Result {
3060 VisSpace(&it.visibility),
3061 if structhead {"union "} else {""},
3062 it.name.as_ref().unwrap())?;
3063 if let Some(g) = g {
3064 write!(w, "{}", g)?;
3065 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3068 write!(w, " {{\n{}", tab)?;
3069 for field in fields {
3070 if let clean::StructFieldItem(ref ty) = field.inner {
3071 write!(w, " {}{}: {},\n{}",
3072 VisSpace(&field.visibility),
3073 field.name.as_ref().unwrap(),
3079 if it.has_stripped_fields().unwrap() {
3080 write!(w, " // some fields omitted\n{}", tab)?;
3086 #[derive(Copy, Clone)]
3087 enum AssocItemLink<'a> {
3088 Anchor(Option<&'a str>),
3089 GotoSource(DefId, &'a FxHashSet<String>),
3092 impl<'a> AssocItemLink<'a> {
3093 fn anchor(&self, id: &'a String) -> Self {
3095 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3096 ref other => *other,
3101 enum AssocItemRender<'a> {
3103 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3106 #[derive(Copy, Clone, PartialEq)]
3109 ForDeref { mut_: bool },
3112 fn render_assoc_items(w: &mut fmt::Formatter,
3114 containing_item: &clean::Item,
3116 what: AssocItemRender) -> fmt::Result {
3118 let v = match c.impls.get(&it) {
3120 None => return Ok(()),
3122 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3123 i.inner_impl().trait_.is_none()
3125 if !non_trait.is_empty() {
3126 let render_mode = match what {
3127 AssocItemRender::All => {
3129 <h2 id='methods' class='small-section-header'>
3130 Methods<a href='#methods' class='anchor'></a>
3135 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3137 <h2 id='deref-methods' class='small-section-header'>
3138 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3141 RenderMode::ForDeref { mut_: deref_mut_ }
3144 for i in &non_trait {
3145 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3146 containing_item.stable_since(), true)?;
3149 if let AssocItemRender::DerefFor { .. } = what {
3152 if !traits.is_empty() {
3153 let deref_impl = traits.iter().find(|t| {
3154 t.inner_impl().trait_.def_id() == c.deref_trait_did
3156 if let Some(impl_) = deref_impl {
3157 let has_deref_mut = traits.iter().find(|t| {
3158 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3160 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3163 let (synthetic, concrete) = traits
3165 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3168 <h2 id='implementations' class='small-section-header'>
3169 Trait Implementations<a href='#implementations' class='anchor'></a>
3171 <div id='implementations-list'>
3173 render_impls(cx, w, concrete, containing_item)?;
3174 write!(w, "</div>")?;
3177 <h2 id='synthetic-implementations' class='small-section-header'>
3178 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3180 <div id='synthetic-implementations-list'>
3182 render_impls(cx, w, synthetic, containing_item)?;
3183 write!(w, "</div>")?;
3188 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3189 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3190 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3191 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3193 clean::TypedefItem(ref t, true) => Some(&t.type_),
3196 }).next().expect("Expected associated type binding");
3197 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3198 deref_mut_: deref_mut };
3199 if let Some(did) = target.def_id() {
3200 render_assoc_items(w, cx, container_item, did, what)
3202 if let Some(prim) = target.primitive_type() {
3203 if let Some(&did) = cache().primitive_locations.get(&prim) {
3204 render_assoc_items(w, cx, container_item, did, what)?;
3211 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3212 let self_type_opt = match item.inner {
3213 clean::MethodItem(ref method) => method.decl.self_type(),
3214 clean::TyMethodItem(ref method) => method.decl.self_type(),
3218 if let Some(self_ty) = self_type_opt {
3219 let (by_mut_ref, by_box, by_value) = match self_ty {
3220 SelfTy::SelfBorrowed(_, mutability) |
3221 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3222 (mutability == Mutability::Mutable, false, false)
3224 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3225 (false, Some(did) == cache().owned_box_did, false)
3227 SelfTy::SelfValue => (false, false, true),
3228 _ => (false, false, false),
3231 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3237 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3238 let mut out = String::new();
3241 clean::FunctionItem(clean::Function { ref decl, .. }) |
3242 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3243 clean::MethodItem(clean::Method { ref decl, .. }) |
3244 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3245 out = spotlight_decl(decl)?;
3253 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3254 let mut out = String::new();
3255 let mut trait_ = String::new();
3257 if let Some(did) = decl.output.def_id() {
3259 if let Some(impls) = c.impls.get(&did) {
3261 let impl_ = i.inner_impl();
3262 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3265 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3266 <code class=\"content\">",
3268 trait_.push_str(&format!("{}", impl_.for_));
3271 //use the "where" class here to make it small
3272 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3273 let t_did = impl_.trait_.def_id().unwrap();
3274 for it in &impl_.items {
3275 if let clean::TypedefItem(ref tydef, _) = it.inner {
3276 out.push_str("<span class=\"where fmt-newline\"> ");
3277 assoc_type(&mut out, it, &vec![],
3279 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3280 out.push_str(";</span>");
3288 if !out.is_empty() {
3289 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3290 <span class='tooltiptext'>Important traits for {}</span></div>\
3291 <div class=\"content hidden\">",
3293 out.push_str("</code></div></div>");
3299 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3300 render_mode: RenderMode, outer_version: Option<&str>,
3301 show_def_docs: bool) -> fmt::Result {
3302 if render_mode == RenderMode::Normal {
3303 let id = derive_id(match i.inner_impl().trait_ {
3304 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3305 None => "impl".to_string(),
3307 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3308 id, i.inner_impl())?;
3309 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3310 write!(w, "</span><span class='out-of-band'>")?;
3311 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3312 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3313 write!(w, "<div class='ghost'></div>")?;
3314 render_stability_since_raw(w, since, outer_version)?;
3315 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3316 l, "goto source code")?;
3318 render_stability_since_raw(w, since, outer_version)?;
3320 write!(w, "</span>")?;
3321 write!(w, "</h3>\n")?;
3322 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3323 write!(w, "<div class='docblock'>{}</div>",
3324 Markdown(&*dox, &i.impl_item.links()))?;
3328 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3329 link: AssocItemLink, render_mode: RenderMode,
3330 is_default_item: bool, outer_version: Option<&str>,
3331 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3332 let item_type = item.type_();
3333 let name = item.name.as_ref().unwrap();
3335 let render_method_item: bool = match render_mode {
3336 RenderMode::Normal => true,
3337 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3341 clean::MethodItem(clean::Method { ref decl, .. }) |
3342 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3343 // Only render when the method is not static or we allow static methods
3344 if render_method_item {
3345 let id = derive_id(format!("{}.{}", item_type, name));
3346 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3347 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3348 write!(w, "{}", spotlight_decl(decl)?)?;
3349 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3350 write!(w, "<code>")?;
3351 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3352 write!(w, "</code>")?;
3353 if let Some(l) = (Item { cx, item }).src_href() {
3354 write!(w, "</span><span class='out-of-band'>")?;
3355 write!(w, "<div class='ghost'></div>")?;
3356 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3357 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3358 l, "goto source code")?;
3360 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3362 write!(w, "</span></h4>\n")?;
3365 clean::TypedefItem(ref tydef, _) => {
3366 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3367 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3368 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3369 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3370 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3371 write!(w, "</code></span></h4>\n")?;
3373 clean::AssociatedConstItem(ref ty, ref default) => {
3374 let id = derive_id(format!("{}.{}", item_type, name));
3375 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3376 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3377 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3378 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3379 write!(w, "</code></span></h4>\n")?;
3381 clean::AssociatedTypeItem(ref bounds, ref default) => {
3382 let id = derive_id(format!("{}.{}", item_type, name));
3383 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3384 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3385 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3386 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3387 write!(w, "</code></span></h4>\n")?;
3389 clean::StrippedItem(..) => return Ok(()),
3390 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3393 if render_method_item || render_mode == RenderMode::Normal {
3394 let prefix = render_assoc_const_value(item);
3396 if !is_default_item {
3397 if let Some(t) = trait_ {
3398 // The trait item may have been stripped so we might not
3399 // find any documentation or stability for it.
3400 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3401 // We need the stability of the item from the trait
3402 // because impls can't have a stability.
3403 document_stability(w, cx, it)?;
3404 if item.doc_value().is_some() {
3405 document_full(w, item, cx, &prefix)?;
3406 } else if show_def_docs {
3407 // In case the item isn't documented,
3408 // provide short documentation from the trait.
3409 document_short(w, it, link, &prefix)?;
3413 document_stability(w, cx, item)?;
3415 document_full(w, item, cx, &prefix)?;
3419 document_stability(w, cx, item)?;
3421 document_short(w, item, link, &prefix)?;
3428 let traits = &cache().traits;
3429 let trait_ = i.trait_did().map(|did| &traits[&did]);
3432 write!(w, "<span class='docblock autohide'>")?;
3435 write!(w, "<div class='impl-items'>")?;
3436 for trait_item in &i.inner_impl().items {
3437 doc_impl_item(w, cx, trait_item, link, render_mode,
3438 false, outer_version, trait_, show_def_docs)?;
3441 fn render_default_items(w: &mut fmt::Formatter,
3445 render_mode: RenderMode,
3446 outer_version: Option<&str>,
3447 show_def_docs: bool) -> fmt::Result {
3448 for trait_item in &t.items {
3449 let n = trait_item.name.clone();
3450 if i.items.iter().find(|m| m.name == n).is_some() {
3453 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3454 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3456 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3457 outer_version, None, show_def_docs)?;
3462 // If we've implemented a trait, then also emit documentation for all
3463 // default items which weren't overridden in the implementation block.
3464 if let Some(t) = trait_ {
3465 render_default_items(w, cx, t, &i.inner_impl(),
3466 render_mode, outer_version, show_def_docs)?;
3468 write!(w, "</div>")?;
3471 write!(w, "</span>")?;
3477 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3478 t: &clean::Typedef) -> fmt::Result {
3479 write!(w, "<pre class='rust typedef'>")?;
3480 render_attributes(w, it)?;
3481 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3482 it.name.as_ref().unwrap(),
3484 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3487 document(w, cx, it)?;
3489 // Render any items associated directly to this alias, as otherwise they
3490 // won't be visible anywhere in the docs. It would be nice to also show
3491 // associated items from the aliased type (see discussion in #32077), but
3492 // we need #14072 to make sense of the generics.
3493 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3496 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3497 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3498 render_attributes(w, it)?;
3501 " {}type {};\n}}</pre>",
3502 VisSpace(&it.visibility),
3503 it.name.as_ref().unwrap(),
3506 document(w, cx, it)?;
3508 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3511 impl<'a> fmt::Display for Sidebar<'a> {
3512 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3515 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3516 let mut should_close = false;
3518 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3519 || it.is_enum() || it.is_mod() || it.is_typedef()
3521 write!(fmt, "<p class='location'>")?;
3523 clean::StructItem(..) => write!(fmt, "Struct ")?,
3524 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3525 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3526 clean::UnionItem(..) => write!(fmt, "Union ")?,
3527 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3528 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3529 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3530 clean::ModuleItem(..) => if it.is_crate() {
3531 write!(fmt, "Crate ")?;
3533 write!(fmt, "Module ")?;
3537 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3538 write!(fmt, "</p>")?;
3541 if let Some(ref version) = cache().crate_version {
3543 "<div class='block version'>\
3550 write!(fmt, "<div class=\"sidebar-elems\">")?;
3551 should_close = true;
3553 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3554 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3555 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3556 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3557 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3558 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3559 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3560 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3565 // The sidebar is designed to display sibling functions, modules and
3566 // other miscellaneous information. since there are lots of sibling
3567 // items (and that causes quadratic growth in large modules),
3568 // we refactor common parts into a shared JavaScript file per module.
3569 // still, we don't move everything into JS because we want to preserve
3570 // as much HTML as possible in order to allow non-JS-enabled browsers
3571 // to navigate the documentation (though slightly inefficiently).
3573 write!(fmt, "<p class='location'>")?;
3574 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3576 write!(fmt, "::<wbr>")?;
3578 write!(fmt, "<a href='{}index.html'>{}</a>",
3579 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3582 write!(fmt, "</p>")?;
3584 // Sidebar refers to the enclosing module, not this module.
3585 let relpath = if it.is_mod() { "../" } else { "" };
3587 "<script>window.sidebarCurrent = {{\
3592 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3593 ty = it.type_().css_class(),
3596 // There is no sidebar-items.js beyond the crate root path
3597 // FIXME maybe dynamic crate loading can be merged here
3599 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3603 // Closes sidebar-elems div.
3604 write!(fmt, "</div>")?;
3611 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3612 i.items.iter().filter_map(|item| {
3614 // Maybe check with clean::Visibility::Public as well?
3615 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3616 if !for_deref || should_render_item(item, false) {
3617 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3624 }).collect::<Vec<_>>()
3627 // The point is to url encode any potential character from a type with genericity.
3628 fn small_url_encode(s: &str) -> String {
3629 s.replace("<", "%3C")
3630 .replace(">", "%3E")
3631 .replace(" ", "%20")
3632 .replace("?", "%3F")
3633 .replace("'", "%27")
3634 .replace("&", "%26")
3635 .replace(",", "%2C")
3636 .replace(":", "%3A")
3637 .replace(";", "%3B")
3638 .replace("[", "%5B")
3639 .replace("]", "%5D")
3640 .replace("\"", "%22")
3643 fn sidebar_assoc_items(it: &clean::Item) -> String {
3644 let mut out = String::new();
3646 if let Some(v) = c.impls.get(&it.def_id) {
3648 .filter(|i| i.inner_impl().trait_.is_none())
3649 .flat_map(|i| get_methods(i.inner_impl(), false))
3650 .collect::<String>();
3651 if !ret.is_empty() {
3652 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3653 </a><div class=\"sidebar-links\">{}</div>", ret));
3656 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3657 if let Some(impl_) = v.iter()
3658 .filter(|i| i.inner_impl().trait_.is_some())
3659 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3660 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3662 clean::TypedefItem(ref t, true) => Some(&t.type_),
3666 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3667 c.primitive_locations.get(&prim).cloned()
3668 })).and_then(|did| c.impls.get(&did));
3669 if let Some(impls) = inner_impl {
3670 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3671 out.push_str(&format!("Methods from {}<Target={}>",
3672 Escape(&format!("{:#}",
3673 impl_.inner_impl().trait_.as_ref().unwrap())),
3674 Escape(&format!("{:#}", target))));
3675 out.push_str("</a>");
3676 let ret = impls.iter()
3677 .filter(|i| i.inner_impl().trait_.is_none())
3678 .flat_map(|i| get_methods(i.inner_impl(), true))
3679 .collect::<String>();
3680 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3684 let format_impls = |impls: Vec<&Impl>| {
3685 let mut links = HashSet::new();
3688 let is_negative_impl = is_negative_impl(i.inner_impl());
3689 if let Some(ref i) = i.inner_impl().trait_ {
3690 let i_display = format!("{:#}", i);
3691 let out = Escape(&i_display);
3692 let encoded = small_url_encode(&format!("{:#}", i));
3693 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3695 if is_negative_impl { "!" } else { "" },
3697 if links.insert(generated.clone()) {
3706 .collect::<String>()
3709 let (synthetic, concrete) = v
3711 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3713 let concrete_format = format_impls(concrete);
3714 let synthetic_format = format_impls(synthetic);
3716 if !concrete_format.is_empty() {
3717 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3718 Trait Implementations</a>");
3719 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3722 if !synthetic_format.is_empty() {
3723 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3724 Auto Trait Implementations</a>");
3725 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3733 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3734 s: &clean::Struct) -> fmt::Result {
3735 let mut sidebar = String::new();
3736 let fields = get_struct_fields_name(&s.fields);
3738 if !fields.is_empty() {
3739 if let doctree::Plain = s.struct_type {
3740 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3741 <div class=\"sidebar-links\">{}</div>", fields));
3745 sidebar.push_str(&sidebar_assoc_items(it));
3747 if !sidebar.is_empty() {
3748 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3753 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3755 clean::ItemEnum::ImplItem(ref i) => {
3756 if let Some(ref trait_) = i.trait_ {
3757 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3766 fn is_negative_impl(i: &clean::Impl) -> bool {
3767 i.polarity == Some(clean::ImplPolarity::Negative)
3770 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3771 t: &clean::Trait) -> fmt::Result {
3772 let mut sidebar = String::new();
3778 Some(ref name) if m.is_associated_type() => {
3779 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3785 .collect::<String>();
3786 let consts = t.items
3790 Some(ref name) if m.is_associated_const() => {
3791 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3797 .collect::<String>();
3798 let required = t.items
3802 Some(ref name) if m.is_ty_method() => {
3803 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3809 .collect::<String>();
3810 let provided = t.items
3814 Some(ref name) if m.is_method() => {
3815 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3820 .collect::<String>();
3822 if !types.is_empty() {
3823 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3824 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3827 if !consts.is_empty() {
3828 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3829 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3832 if !required.is_empty() {
3833 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3834 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3837 if !provided.is_empty() {
3838 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3839 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3845 if let Some(implementors) = c.implementors.get(&it.def_id) {
3846 let res = implementors.iter()
3847 .filter(|i| i.inner_impl().for_.def_id()
3848 .map_or(false, |d| !c.paths.contains_key(&d)))
3850 match extract_for_impl_name(&i.impl_item) {
3851 Some((ref name, ref url)) => {
3852 Some(format!("<a href=\"#impl-{}\">{}</a>",
3853 small_url_encode(url),
3859 .collect::<String>();
3860 if !res.is_empty() {
3861 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3862 Implementations on Foreign Types</a><div \
3863 class=\"sidebar-links\">{}</div>",
3868 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3870 sidebar.push_str("<a class=\"sidebar-title\" \
3871 href=\"#synthetic-implementors\">Auto Implementors</a>");
3874 sidebar.push_str(&sidebar_assoc_items(it));
3876 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3879 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3880 _p: &clean::PrimitiveType) -> fmt::Result {
3881 let sidebar = sidebar_assoc_items(it);
3883 if !sidebar.is_empty() {
3884 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3889 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3890 _t: &clean::Typedef) -> fmt::Result {
3891 let sidebar = sidebar_assoc_items(it);
3893 if !sidebar.is_empty() {
3894 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3899 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3901 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3906 .filter_map(|f| match f.name {
3907 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3908 {name}</a>", name=name)),
3914 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3915 u: &clean::Union) -> fmt::Result {
3916 let mut sidebar = String::new();
3917 let fields = get_struct_fields_name(&u.fields);
3919 if !fields.is_empty() {
3920 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3921 <div class=\"sidebar-links\">{}</div>", fields));
3924 sidebar.push_str(&sidebar_assoc_items(it));
3926 if !sidebar.is_empty() {
3927 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3932 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3933 e: &clean::Enum) -> fmt::Result {
3934 let mut sidebar = String::new();
3936 let variants = e.variants.iter()
3937 .filter_map(|v| match v.name {
3938 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3939 </a>", name = name)),
3942 .collect::<String>();
3943 if !variants.is_empty() {
3944 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3945 <div class=\"sidebar-links\">{}</div>", variants));
3948 sidebar.push_str(&sidebar_assoc_items(it));
3950 if !sidebar.is_empty() {
3951 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3956 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3957 items: &[clean::Item]) -> fmt::Result {
3958 let mut sidebar = String::new();
3960 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3961 it.type_() == ItemType::Import) {
3962 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3964 name = "Re-exports"));
3967 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3968 // to print its headings
3969 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3970 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3971 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3972 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3973 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3974 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3975 let (short, name) = match myty {
3976 ItemType::ExternCrate |
3977 ItemType::Import => ("reexports", "Re-exports"),
3978 ItemType::Module => ("modules", "Modules"),
3979 ItemType::Struct => ("structs", "Structs"),
3980 ItemType::Union => ("unions", "Unions"),
3981 ItemType::Enum => ("enums", "Enums"),
3982 ItemType::Function => ("functions", "Functions"),
3983 ItemType::Typedef => ("types", "Type Definitions"),
3984 ItemType::Static => ("statics", "Statics"),
3985 ItemType::Constant => ("constants", "Constants"),
3986 ItemType::Trait => ("traits", "Traits"),
3987 ItemType::Impl => ("impls", "Implementations"),
3988 ItemType::TyMethod => ("tymethods", "Type Methods"),
3989 ItemType::Method => ("methods", "Methods"),
3990 ItemType::StructField => ("fields", "Struct Fields"),
3991 ItemType::Variant => ("variants", "Variants"),
3992 ItemType::Macro => ("macros", "Macros"),
3993 ItemType::Primitive => ("primitives", "Primitive Types"),
3994 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3995 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3996 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
3998 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4004 if !sidebar.is_empty() {
4005 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4010 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4011 let sidebar = sidebar_assoc_items(it);
4012 if !sidebar.is_empty() {
4013 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4018 impl<'a> fmt::Display for Source<'a> {
4019 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4020 let Source(s) = *self;
4021 let lines = s.lines().count();
4023 let mut tmp = lines;
4028 write!(fmt, "<pre class=\"line-numbers\">")?;
4029 for i in 1..lines + 1 {
4030 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4032 write!(fmt, "</pre>")?;
4034 highlight::render_with_highlighting(s, None, None, None, None))?;
4039 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4040 t: &clean::Macro) -> fmt::Result {
4041 w.write_str(&highlight::render_with_highlighting(&t.source,
4049 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4051 _p: &clean::PrimitiveType) -> fmt::Result {
4052 document(w, cx, it)?;
4053 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4056 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4058 fn make_item_keywords(it: &clean::Item) -> String {
4059 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4062 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4063 let decl = match item.inner {
4064 clean::FunctionItem(ref f) => &f.decl,
4065 clean::MethodItem(ref m) => &m.decl,
4066 clean::TyMethodItem(ref m) => &m.decl,
4070 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4071 let output = match decl.output {
4072 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4076 Some(IndexItemFunctionType { inputs: inputs, output: output })
4079 fn get_index_type(clean_type: &clean::Type) -> Type {
4081 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4082 generics: get_generics(clean_type),
4087 /// Returns a list of all paths used in the type.
4088 /// This is used to help deduplicate imported impls
4089 /// for reexported types. If any of the contained
4090 /// types are re-exported, we don't use the corresponding
4091 /// entry from the js file, as inlining will have already
4092 /// picked up the impl
4093 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4094 let mut out = Vec::new();
4095 let mut visited = FxHashSet();
4096 let mut work = VecDeque::new();
4097 let cache = cache();
4099 work.push_back(first_ty);
4101 while let Some(ty) = work.pop_front() {
4102 if !visited.insert(ty.clone()) {
4107 clean::Type::ResolvedPath { did, .. } => {
4108 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4109 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4113 out.push(path.join("::"));
4119 clean::Type::Tuple(tys) => {
4120 work.extend(tys.into_iter());
4122 clean::Type::Slice(ty) => {
4123 work.push_back(*ty);
4125 clean::Type::Array(ty, _) => {
4126 work.push_back(*ty);
4128 clean::Type::Unique(ty) => {
4129 work.push_back(*ty);
4131 clean::Type::RawPointer(_, ty) => {
4132 work.push_back(*ty);
4134 clean::Type::BorrowedRef { type_, .. } => {
4135 work.push_back(*type_);
4137 clean::Type::QPath { self_type, trait_, .. } => {
4138 work.push_back(*self_type);
4139 work.push_back(*trait_);
4147 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4149 clean::ResolvedPath { ref path, .. } => {
4150 let segments = &path.segments;
4151 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4152 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4153 clean_type, accept_generic
4155 Some(path_segment.name.clone())
4157 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4158 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4159 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4160 // FIXME: add all from clean::Type.
4165 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4166 clean_type.generics()
4168 let r = types.iter()
4169 .filter_map(|t| get_index_type_name(t, false))
4170 .map(|s| s.to_ascii_lowercase())
4171 .collect::<Vec<_>>();
4180 pub fn cache() -> Arc<Cache> {
4181 CACHE_KEY.with(|c| c.borrow().clone())
4186 fn test_unique_id() {
4187 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4188 "method.into_iter", "foo", "main", "search", "methods",
4189 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4190 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4191 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4192 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4195 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4196 assert_eq!(&actual[..], expected);
4205 fn test_name_key() {
4206 assert_eq!(name_key("0"), ("", 0, 1));
4207 assert_eq!(name_key("123"), ("", 123, 0));
4208 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4209 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4210 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4211 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4212 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4213 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4218 fn test_name_sorting() {
4219 let names = ["Apple",
4221 "Fruit", "Fruit0", "Fruit00",
4222 "Fruit1", "Fruit01",
4223 "Fruit2", "Fruit02",
4227 let mut sorted = names.to_owned();
4228 sorted.sort_by_key(|&s| name_key(s));
4229 assert_eq!(names, sorted);