diff options
Diffstat (limited to 'src/librustdoc/html/render.rs')
| -rw-r--r-- | src/librustdoc/html/render.rs | 2705 |
1 files changed, 1520 insertions, 1185 deletions
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 100aed1af19..506f84baaa5 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -32,46 +32,46 @@ use std::collections::{BTreeMap, VecDeque}; use std::default::Default; use std::error; -use std::fmt::{self, Formatter, Write}; use std::ffi::OsStr; +use std::fmt::{self, Formatter, Write}; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{self, BufReader}; -use std::path::{PathBuf, Path, Component}; +use std::path::{Component, Path, PathBuf}; +use std::rc::Rc; use std::str; use std::sync::Arc; -use std::rc::Rc; use errors; -use serde::{Serialize, Serializer}; -use serde::ser::SerializeSeq; -use syntax::ast; -use syntax::edition::Edition; -use syntax::print::pprust; -use syntax::source_map::FileName; -use syntax::symbol::{Symbol, sym}; -use syntax_pos::hygiene::MacroKind; use rustc::hir::def_id::DefId; +use rustc::hir::{self, Mutability}; use rustc::middle::privacy::AccessLevels; use rustc::middle::stability; -use rustc::hir::{self, Mutability}; use rustc::util::nodemap::{FxHashMap, FxHashSet}; use rustc_data_structures::flock; use rustc_feature::UnstableFeatures; +use serde::ser::SerializeSeq; +use serde::{Serialize, Serializer}; +use syntax::ast; +use syntax::edition::Edition; +use syntax::print::pprust; +use syntax::source_map::FileName; +use syntax::symbol::{sym, Symbol}; +use syntax_pos::hygiene::MacroKind; use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy}; use crate::config::RenderOptions; use crate::docfs::{DocFS, ErrorStorage, PathError}; use crate::doctree; use crate::html::escape::Escape; -use crate::html::format::{Buffer, PrintWithSpace, print_abi_with_space}; -use crate::html::format::{print_generic_bounds, WhereClause, href, print_default_space}; -use crate::html::format::{Function}; use crate::html::format::fmt_impl_for_trait_page; +use crate::html::format::Function; +use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause}; +use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace}; use crate::html::item_type::ItemType; -use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap}; -use crate::html::{highlight, layout, static_files}; +use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine}; use crate::html::sources; +use crate::html::{highlight, layout, static_files}; use minifier; @@ -88,11 +88,7 @@ pub type NameDoc = (String, Option<String>); crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { - if !v.ends_with("/") && !v.is_empty() { - write!(f, "{}/", v) - } else { - write!(f, "{}", v) - } + if !v.ends_with("/") && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) } }) } @@ -121,31 +117,29 @@ impl std::fmt::Display for Error { impl PathError for Error { fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error { - Error { - file: path.as_ref().to_path_buf(), - error: e, - } + Error { file: path.as_ref().to_path_buf(), error: e } } } macro_rules! try_none { - ($e:expr, $file:expr) => ({ + ($e:expr, $file:expr) => {{ use std::io; match $e { Some(e) => e, - None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"), - $file)) + None => { + return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"), $file)); + } } - }) + }}; } macro_rules! try_err { - ($e:expr, $file:expr) => ({ + ($e:expr, $file:expr) => {{ match $e { Ok(e) => e, Err(e) => return Err(Error::new(e, $file)), } - }) + }}; } /// Major driving force in all rustdoc rendering. This contains information @@ -225,12 +219,7 @@ impl Context { let mut iter = filename.splitn(2, '.'); let base = iter.next().unwrap(); let ext = iter.next().unwrap(); - let filename = format!( - "{}{}.{}", - base, - self.shared.resource_suffix, - ext, - ); + let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,); self.dst.join(&filename) } } @@ -267,7 +256,7 @@ impl Impl { fn inner_impl(&self) -> &clean::Impl { match self.impl_item.inner { clean::ImplItem(ref impl_) => impl_, - _ => panic!("non-impl item found in impl") + _ => panic!("non-impl item found in impl"), } } @@ -312,14 +301,7 @@ impl Serialize for IndexItem { { assert_eq!(self.parent.is_some(), self.parent_idx.is_some()); - ( - self.ty, - &self.name, - &self.path, - &self.desc, - self.parent_idx, - &self.search_type, - ) + (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type) .serialize(serializer) } } @@ -388,31 +370,36 @@ thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0)); pub fn initial_ids() -> Vec<String> { [ - "main", - "search", - "help", - "TOC", - "render-detail", - "associated-types", - "associated-const", - "required-methods", - "provided-methods", - "implementors", - "synthetic-implementors", - "implementors-list", - "synthetic-implementors-list", - "methods", - "deref-methods", - "implementations", - ].iter().map(|id| (String::from(*id))).collect() + "main", + "search", + "help", + "TOC", + "render-detail", + "associated-types", + "associated-const", + "required-methods", + "provided-methods", + "implementors", + "synthetic-implementors", + "implementors-list", + "synthetic-implementors-list", + "methods", + "deref-methods", + "implementations", + ] + .iter() + .map(|id| (String::from(*id))) + .collect() } /// Generates the documentation for `crate` into the directory `dst` -pub fn run(mut krate: clean::Crate, - options: RenderOptions, - renderinfo: RenderInfo, - diag: &errors::Handler, - edition: Edition) -> Result<(), Error> { +pub fn run( + mut krate: clean::Crate, + options: RenderOptions, + renderinfo: RenderInfo, + diag: &errors::Handler, + edition: Edition, +) -> Result<(), Error> { // need to save a copy of the options for rendering the index page let md_opts = options.clone(); let RenderOptions { @@ -442,10 +429,7 @@ pub fn run(mut krate: clean::Crate, // If user passed in `--playground-url` arg, we fill in crate name here let mut playground = None; if let Some(url) = playground_url { - playground = Some(markdown::Playground { - crate_name: Some(krate.name.clone()), - url, - }); + playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url }); } let mut layout = layout::Layout { logo: String::new(), @@ -507,12 +491,8 @@ pub fn run(mut krate: clean::Crate, let dst = output; scx.ensure_dir(&dst)?; krate = sources::render(&dst, &mut scx, krate)?; - let (new_crate, index, cache) = Cache::from_krate( - renderinfo, - &extern_html_root_urls, - &dst, - krate, - ); + let (new_crate, index, cache) = + Cache::from_krate(renderinfo, &extern_html_root_urls, &dst, krate); krate = new_crate; let cache = Arc::new(cache); let mut cx = Context { @@ -562,15 +542,24 @@ fn write_shared( // Add all the static files. These may already exist, but we just // overwrite them anyway to make sure that they're fresh and up-to-date. - write_minify(&cx.shared.fs, cx.path("rustdoc.css"), - static_files::RUSTDOC_CSS, - options.enable_minification)?; - write_minify(&cx.shared.fs, cx.path("settings.css"), - static_files::SETTINGS_CSS, - options.enable_minification)?; - write_minify(&cx.shared.fs, cx.path("noscript.css"), - static_files::NOSCRIPT_CSS, - options.enable_minification)?; + write_minify( + &cx.shared.fs, + cx.path("rustdoc.css"), + static_files::RUSTDOC_CSS, + options.enable_minification, + )?; + write_minify( + &cx.shared.fs, + cx.path("settings.css"), + static_files::SETTINGS_CSS, + options.enable_minification, + )?; + write_minify( + &cx.shared.fs, + cx.path("noscript.css"), + static_files::NOSCRIPT_CSS, + options.enable_minification, + )?; // To avoid "light.css" to be overwritten, we'll first run over the received themes and only // then we'll run over the "official" styles. @@ -584,7 +573,7 @@ fn write_shared( themes.insert(theme.to_owned()); } - let write = |p, c| { cx.shared.fs.write(p, c) }; + let write = |p, c| cx.shared.fs.write(p, c); if (*cx.shared).layout.logo.is_empty() { write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?; } @@ -594,11 +583,19 @@ fn write_shared( write(cx.path("brush.svg"), static_files::BRUSH_SVG)?; write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?; write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?; - write_minify(&cx.shared.fs, - cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification)?; + write_minify( + &cx.shared.fs, + cx.path("light.css"), + static_files::themes::LIGHT, + options.enable_minification, + )?; themes.insert("light".to_owned()); - write_minify(&cx.shared.fs, - cx.path("dark.css"), static_files::themes::DARK, options.enable_minification)?; + write_minify( + &cx.shared.fs, + cx.path("dark.css"), + static_files::themes::DARK, + options.enable_minification, + )?; themes.insert("dark".to_owned()); let mut themes: Vec<&String> = themes.iter().collect(); @@ -652,33 +649,43 @@ themePicker.onblur = handleThemeButtonsBlur; }}; but.onblur = handleThemeButtonsBlur; themes.appendChild(but); -}});"#, serde_json::to_string(&themes).unwrap()); - - write_minify(&cx.shared.fs, cx.path("theme.js"), - &theme_js, - options.enable_minification)?; - write_minify(&cx.shared.fs, cx.path("main.js"), - static_files::MAIN_JS, - options.enable_minification)?; - write_minify(&cx.shared.fs, cx.path("settings.js"), - static_files::SETTINGS_JS, - options.enable_minification)?; +}});"#, + serde_json::to_string(&themes).unwrap() + ); + + write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?; + write_minify( + &cx.shared.fs, + cx.path("main.js"), + static_files::MAIN_JS, + options.enable_minification, + )?; + write_minify( + &cx.shared.fs, + cx.path("settings.js"), + static_files::SETTINGS_JS, + options.enable_minification, + )?; if cx.shared.include_sources { write_minify( &cx.shared.fs, cx.path("source-script.js"), static_files::sidebar::SOURCE_SCRIPT, - options.enable_minification)?; + options.enable_minification, + )?; } { write_minify( &cx.shared.fs, cx.path("storage.js"), - &format!("var resourcesSuffix = \"{}\";{}", - cx.shared.resource_suffix, - static_files::STORAGE_JS), - options.enable_minification)?; + &format!( + "var resourcesSuffix = \"{}\";{}", + cx.shared.resource_suffix, + static_files::STORAGE_JS + ), + options.enable_minification, + )?; } if let Some(ref css) = cx.shared.layout.css_file_extension { @@ -690,41 +697,27 @@ themePicker.onblur = handleThemeButtonsBlur; write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?; } } - write_minify(&cx.shared.fs, cx.path("normalize.css"), - static_files::NORMALIZE_CSS, - options.enable_minification)?; - write(cx.dst.join("FiraSans-Regular.woff"), - static_files::fira_sans::REGULAR)?; - write(cx.dst.join("FiraSans-Medium.woff"), - static_files::fira_sans::MEDIUM)?; - write(cx.dst.join("FiraSans-LICENSE.txt"), - static_files::fira_sans::LICENSE)?; - write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), - static_files::source_serif_pro::REGULAR)?; - write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), - static_files::source_serif_pro::BOLD)?; - write(cx.dst.join("SourceSerifPro-It.ttf.woff"), - static_files::source_serif_pro::ITALIC)?; - write(cx.dst.join("SourceSerifPro-LICENSE.md"), - static_files::source_serif_pro::LICENSE)?; - write(cx.dst.join("SourceCodePro-Regular.woff"), - static_files::source_code_pro::REGULAR)?; - write(cx.dst.join("SourceCodePro-Semibold.woff"), - static_files::source_code_pro::SEMIBOLD)?; - write(cx.dst.join("SourceCodePro-LICENSE.txt"), - static_files::source_code_pro::LICENSE)?; - write(cx.dst.join("LICENSE-MIT.txt"), - static_files::LICENSE_MIT)?; - write(cx.dst.join("LICENSE-APACHE.txt"), - static_files::LICENSE_APACHE)?; - write(cx.dst.join("COPYRIGHT.txt"), - static_files::COPYRIGHT)?; - - fn collect( - path: &Path, - krate: &str, - key: &str, - ) -> io::Result<(Vec<String>, Vec<String>)> { + write_minify( + &cx.shared.fs, + cx.path("normalize.css"), + static_files::NORMALIZE_CSS, + options.enable_minification, + )?; + write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?; + write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?; + write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?; + write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?; + write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?; + write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?; + write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?; + write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?; + write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?; + write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?; + write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?; + write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?; + write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?; + + fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> { let mut ret = Vec::new(); let mut krates = Vec::new(); @@ -738,23 +731,28 @@ themePicker.onblur = handleThemeButtonsBlur; continue; } ret.push(line.to_string()); - krates.push(line[key.len() + 2..].split('"') - .next() - .map(|s| s.to_owned()) - .unwrap_or_else(|| String::new())); + krates.push( + line[key.len() + 2..] + .split('"') + .next() + .map(|s| s.to_owned()) + .unwrap_or_else(|| String::new()), + ); } } Ok((ret, krates)) } fn show_item(item: &IndexItem, krate: &str) -> String { - format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}", - krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path, - if let Some(p) = item.parent_idx { - format!(",'parent':{}", p) - } else { - String::new() - }) + format!( + "{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}", + krate, + item.ty as usize, + item.name, + item.desc.replace("'", "\\'"), + item.path, + if let Some(p) = item.parent_idx { format!(",'parent':{}", p) } else { String::new() } + ) } let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix)); @@ -763,14 +761,13 @@ themePicker.onblur = handleThemeButtonsBlur; let mut output = String::with_capacity(100); for (alias, items) in &cx.cache.aliases { if items.is_empty() { - continue + continue; } - output.push_str(&format!("\"{}\":[{}],", - alias, - items.iter() - .map(|v| show_item(v, &krate.name)) - .collect::<Vec<_>>() - .join(","))); + output.push_str(&format!( + "\"{}\":[{}],", + alias, + items.iter().map(|v| show_item(v, &krate.name)).collect::<Vec<_>>().join(",") + )); } all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output)); all_aliases.sort(); @@ -793,55 +790,49 @@ themePicker.onblur = handleThemeButtonsBlur; impl Hierarchy { fn new(elem: OsString) -> Hierarchy { - Hierarchy { - elem, - children: FxHashMap::default(), - elems: FxHashSet::default(), - } + Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() } } fn to_json_string(&self) -> String { let mut subs: Vec<&Hierarchy> = self.children.values().collect(); subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem)); - let mut files = self.elems.iter() - .map(|s| format!("\"{}\"", - s.to_str() - .expect("invalid osstring conversion"))) - .collect::<Vec<_>>(); + let mut files = self + .elems + .iter() + .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion"))) + .collect::<Vec<_>>(); files.sort_unstable_by(|a, b| a.cmp(b)); let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","); - let dirs = if subs.is_empty() { - String::new() - } else { - format!(",\"dirs\":[{}]", subs) - }; + let dirs = + if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) }; let files = files.join(","); - let files = if files.is_empty() { - String::new() - } else { - format!(",\"files\":[{}]", files) - }; - format!("{{\"name\":\"{name}\"{dirs}{files}}}", - name=self.elem.to_str().expect("invalid osstring conversion"), - dirs=dirs, - files=files) + let files = + if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) }; + format!( + "{{\"name\":\"{name}\"{dirs}{files}}}", + name = self.elem.to_str().expect("invalid osstring conversion"), + dirs = dirs, + files = files + ) } } if cx.shared.include_sources { let mut hierarchy = Hierarchy::new(OsString::new()); - for source in cx.shared.local_sources.iter() - .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root) - .ok()) { + for source in cx + .shared + .local_sources + .iter() + .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok()) + { let mut h = &mut hierarchy; - let mut elems = source.components() - .filter_map(|s| { - match s { - Component::Normal(s) => Some(s.to_owned()), - _ => None, - } - }) - .peekable(); + let mut elems = source + .components() + .filter_map(|s| match s { + Component::Normal(s) => Some(s.to_owned()), + _ => None, + }) + .peekable(); loop { let cur_elem = elems.next().expect("empty file path"); if elems.peek().is_none() { @@ -857,12 +848,16 @@ themePicker.onblur = handleThemeButtonsBlur; let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix)); let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst); - all_sources.push(format!("sourcesIndex[\"{}\"] = {};", - &krate.name, - hierarchy.to_json_string())); + all_sources.push(format!( + "sourcesIndex[\"{}\"] = {};", + &krate.name, + hierarchy.to_json_string() + )); all_sources.sort(); - let v = format!("var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n", - all_sources.join("\n")); + let v = format!( + "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n", + all_sources.join("\n") + ); cx.shared.fs.write(&dst, v.as_bytes())?; } @@ -907,19 +902,17 @@ themePicker.onblur = handleThemeButtonsBlur; krates.dedup(); let content = format!( -"<h1 class='fqn'>\ + "<h1 class='fqn'>\ <span class='in-band'>List of all crates</span>\ </h1><ul class='mod'>{}</ul>", - krates - .iter() - .map(|s| { - format!("<li><a href=\"{}index.html\">{}</li>", - ensure_trailing_slash(s), s) - }) - .collect::<String>()); - let v = layout::render(&cx.shared.layout, - &page, "", content, - &cx.shared.themes); + krates + .iter() + .map(|s| { + format!("<li><a href=\"{}index.html\">{}</li>", ensure_trailing_slash(s), s) + }) + .collect::<String>() + ); + let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.themes); cx.shared.fs.write(&dst, v.as_bytes())?; } } @@ -939,7 +932,7 @@ themePicker.onblur = handleThemeButtonsBlur; None => match cx.cache.external_paths.get(&did) { Some(p) => p, None => continue, - } + }, }; #[derive(Serialize)] @@ -989,12 +982,10 @@ themePicker.onblur = handleThemeButtonsBlur; mydst.push(part); } cx.shared.ensure_dir(&mydst)?; - mydst.push(&format!("{}.{}.js", - remote_item_type, - remote_path[remote_path.len() - 1])); + mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1])); - let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name, "implementors"), - &mydst); + let (mut all_implementors, _) = + try_err!(collect(&mydst, &krate.name, "implementors"), &mydst); all_implementors.push(implementors); // Sort the implementors by crate so the file will be generated // identically even with rustdoc running in parallel. @@ -1004,21 +995,27 @@ themePicker.onblur = handleThemeButtonsBlur; for implementor in &all_implementors { writeln!(v, "{}", *implementor).unwrap(); } - v.push_str(r" + v.push_str( + r" if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } - "); + ", + ); v.push_str("})()"); cx.shared.fs.write(&mydst, &v)?; } Ok(()) } -fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool - ) -> Result<(), Error> { +fn write_minify( + fs: &DocFS, + dst: PathBuf, + contents: &str, + enable_minification: bool, +) -> Result<(), Error> { if enable_minification { if dst.extension() == Some(&OsStr::new("css")) { let res = try_none!(minifier::css::minify(contents).ok(), &dst); @@ -1042,10 +1039,7 @@ impl ItemEntry { while url.starts_with('/') { url.remove(0); } - ItemEntry { - url, - name, - } + ItemEntry { url, name } } } @@ -1141,18 +1135,22 @@ fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: & if !e.is_empty() { let mut e: Vec<&ItemEntry> = e.iter().collect(); e.sort(); - write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>", - title, - Escape(title), - class, - e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()); + write!( + f, + "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>", + title, + Escape(title), + class, + e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>() + ); } } impl AllTypes { fn print(self, f: &mut Buffer) { - write!(f, - "<h1 class='fqn'>\ + write!( + f, + "<h1 class='fqn'>\ <span class='out-of-band'>\ <span id='render-detail'>\ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\ @@ -1161,7 +1159,8 @@ impl AllTypes { </span> </span> <span class='in-band'>List of all items</span>\ - </h1>"); + </h1>" + ); print_entries(f, &self.structs, "Structs", "structs"); print_entries(f, &self.enums, "Enums", "enums"); print_entries(f, &self.unions, "Unions", "unions"); @@ -1181,55 +1180,40 @@ impl AllTypes { #[derive(Debug)] enum Setting { - Section { - description: &'static str, - sub_settings: Vec<Setting>, - }, - Entry { - js_data_name: &'static str, - description: &'static str, - default_value: bool, - } + Section { description: &'static str, sub_settings: Vec<Setting> }, + Entry { js_data_name: &'static str, description: &'static str, default_value: bool }, } impl Setting { fn display(&self) -> String { match *self { - Setting::Section { ref description, ref sub_settings } => { - format!( - "<div class='setting-line'>\ + Setting::Section { ref description, ref sub_settings } => format!( + "<div class='setting-line'>\ <div class='title'>{}</div>\ <div class='sub-settings'>{}</div> </div>", - description, - sub_settings.iter().map(|s| s.display()).collect::<String>() - ) - } - Setting::Entry { ref js_data_name, ref description, ref default_value } => { - format!( - "<div class='setting-line'>\ + description, + sub_settings.iter().map(|s| s.display()).collect::<String>() + ), + Setting::Entry { ref js_data_name, ref description, ref default_value } => format!( + "<div class='setting-line'>\ <label class='toggle'>\ <input type='checkbox' id='{}' {}>\ <span class='slider'></span>\ </label>\ <div>{}</div>\ </div>", - js_data_name, - if *default_value { " checked" } else { "" }, - description, - ) - } + js_data_name, + if *default_value { " checked" } else { "" }, + description, + ), } } } impl From<(&'static str, &'static str, bool)> for Setting { fn from(values: (&'static str, &'static str, bool)) -> Setting { - Setting::Entry { - js_data_name: values.0, - description: values.1, - default_value: values.2, - } + Setting::Entry { js_data_name: values.0, description: values.1, default_value: values.2 } } } @@ -1245,31 +1229,36 @@ impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting { fn settings(root_path: &str, suffix: &str) -> String { // (id, explanation, default value) let settings: &[Setting] = &[ - ("Auto-hide item declarations", vec![ - ("auto-hide-struct", "Auto-hide structs declaration", true), - ("auto-hide-enum", "Auto-hide enums declaration", false), - ("auto-hide-union", "Auto-hide unions declaration", true), - ("auto-hide-trait", "Auto-hide traits declaration", true), - ("auto-hide-macro", "Auto-hide macros declaration", false), - ]).into(), + ( + "Auto-hide item declarations", + vec![ + ("auto-hide-struct", "Auto-hide structs declaration", true), + ("auto-hide-enum", "Auto-hide enums declaration", false), + ("auto-hide-union", "Auto-hide unions declaration", true), + ("auto-hide-trait", "Auto-hide traits declaration", true), + ("auto-hide-macro", "Auto-hide macros declaration", false), + ], + ) + .into(), ("auto-hide-attributes", "Auto-hide item attributes.", true).into(), ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(), - ("auto-hide-trait-implementations", "Auto-hide trait implementations documentation", - true).into(), - ("go-to-only-result", "Directly go to item in search if there is only one result", - false).into(), + ("auto-hide-trait-implementations", "Auto-hide trait implementations documentation", true) + .into(), + ("go-to-only-result", "Directly go to item in search if there is only one result", false) + .into(), ("line-numbers", "Show line numbers on code examples", false).into(), ("disable-shortcuts", "Disable keyboard shortcuts", false).into(), ]; format!( -"<h1 class='fqn'>\ + "<h1 class='fqn'>\ <span class='in-band'>Rustdoc settings</span>\ </h1>\ <div class='settings'>{}</div>\ <script src='{}settings{}.js'></script>", - settings.iter().map(|s| s.display()).collect::<String>(), - root_path, - suffix) + settings.iter().map(|s| s.display()).collect::<String>(), + root_path, + suffix + ) } impl Context { @@ -1293,8 +1282,7 @@ impl Context { Some(i) => i, None => return Ok(()), }; - let final_file = self.dst.join(&krate.name) - .join("all.html"); + let final_file = self.dst.join(&krate.name).join("all.html"); let settings_file = self.dst.join("settings.html"); let crate_name = krate.name.clone(); @@ -1307,9 +1295,7 @@ impl Context { let mut work = vec![(self.clone(), item)]; while let Some((mut cx, item)) = work.pop() { - cx.item(item, &mut all, |cx, item| { - work.push((cx.clone(), item)) - })? + cx.item(item, &mut all, |cx, item| work.push((cx.clone(), item)))? } } @@ -1329,18 +1315,24 @@ impl Context { static_extra_scripts: &[], }; let sidebar = if let Some(ref version) = self.cache.crate_version { - format!("<p class='location'>Crate {}</p>\ + format!( + "<p class='location'>Crate {}</p>\ <div class='block version'>\ <p>Version {}</p>\ </div>\ <a id='all-types' href='index.html'><p>Back to index</p></a>", - crate_name, version) + crate_name, version + ) } else { String::new() }; - let v = layout::render(&self.shared.layout, - &page, sidebar, |buf: &mut Buffer| all.print(buf), - &self.shared.themes); + let v = layout::render( + &self.shared.layout, + &page, + sidebar, + |buf: &mut Buffer| all.print(buf), + &self.shared.themes, + ); self.shared.fs.write(&final_file, v.as_bytes())?; // Generating settings page. @@ -1353,19 +1345,20 @@ impl Context { themes.push(PathBuf::from("settings.css")); let v = layout::render( &self.shared.layout, - &page, sidebar, settings( + &page, + sidebar, + settings( self.shared.static_root_path.as_deref().unwrap_or("./"), - &self.shared.resource_suffix + &self.shared.resource_suffix, ), - &themes); + &themes, + ); self.shared.fs.write(&settings_file, v.as_bytes())?; Ok(()) } - fn render_item(&self, - it: &clean::Item, - pushname: bool) -> String { + fn render_item(&self, it: &clean::Item, pushname: bool) -> String { // A little unfortunate that this is done like this, but it sure // does make formatting *a lot* nicer. CURRENT_DEPTH.with(|slot| { @@ -1387,11 +1380,14 @@ impl Context { title.push_str(" - Rust"); let tyname = it.type_(); let desc = if it.is_crate() { - format!("API documentation for the Rust `{}` crate.", - self.shared.layout.krate) + format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) } else { - format!("API documentation for the Rust `{}` {} in crate `{}`.", - it.name.as_ref().unwrap(), tyname, self.shared.layout.krate) + format!( + "API documentation for the Rust `{}` {} in crate `{}`.", + it.name.as_ref().unwrap(), + tyname, + self.shared.layout.krate + ) }; let keywords = make_item_keywords(it); let page = layout::Page { @@ -1412,10 +1408,13 @@ impl Context { } if !self.render_redirect_pages { - layout::render(&self.shared.layout, &page, - |buf: &mut _| print_sidebar(self, it, buf), - |buf: &mut _| print_item(self, it, buf), - &self.shared.themes) + layout::render( + &self.shared.layout, + &page, + |buf: &mut _| print_sidebar(self, it, buf), + |buf: &mut _| print_item(self, it, buf), + &self.shared.themes, + ) } else { let mut url = self.root_path(); if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) { @@ -1437,7 +1436,8 @@ impl Context { /// /// The rendering driver uses this closure to queue up more work. fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error> - where F: FnMut(&mut Context, clean::Item), + where + F: FnMut(&mut Context, clean::Item), { // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also @@ -1473,9 +1473,8 @@ impl Context { } let m = match item.inner { - clean::StrippedItem(box clean::ModuleItem(m)) | - clean::ModuleItem(m) => m, - _ => unreachable!() + clean::StrippedItem(box clean::ModuleItem(m)) | clean::ModuleItem(m) => m, + _ => unreachable!(), }; // Render sidebar-items.js used throughout this module. @@ -1534,7 +1533,9 @@ impl Context { // BTreeMap instead of HashMap to get a sorted output let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new(); for item in &m.items { - if item.is_stripped() { continue } + if item.is_stripped() { + continue; + } let short = item.type_(); let myname = match item.name { @@ -1542,7 +1543,8 @@ impl Context { Some(ref s) => s.to_string(), }; let short = short.to_string(); - map.entry(short).or_default() + map.entry(short) + .or_default() .push((myname, Some(plain_summary_line(item.doc_value())))); } @@ -1596,8 +1598,7 @@ impl Context { path.push_str(&component.to_string_lossy()); path.push('/'); }); - let mut fname = file.file_name().expect("source has no filename") - .to_os_string(); + let mut fname = file.file_name().expect("source has no filename").to_os_string(); fname.push(".html"); path.push_str(&fname.to_string_lossy()); (krate, &path) @@ -1608,16 +1609,19 @@ impl Context { } else { format!("{}-{}", item.source.loline, item.source.hiline) }; - Some(format!("{root}src/{krate}/{path}#{lines}", - root = Escape(&root), - krate = krate, - path = path, - lines = lines)) + Some(format!( + "{root}src/{krate}/{path}#{lines}", + root = Escape(&root), + krate = krate, + path = path, + lines = lines + )) } } fn wrap_into_docblock<F>(w: &mut Buffer, f: F) - where F: FnOnce(&mut Buffer) +where + F: FnOnce(&mut Buffer), { write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">"); f(w); @@ -1629,16 +1633,21 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) { // Write the breadcrumb trail header for the top write!(buf, "<h1 class='fqn'><span class='out-of-band'>"); if let Some(version) = item.stable_since() { - write!(buf, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", - version); + write!( + buf, + "<span class='since' title='Stable since Rust version {0}'>{0}</span>", + version + ); } - write!(buf, - "<span id='render-detail'>\ + write!( + buf, + "<span id='render-detail'>\ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \ title=\"collapse all docs\">\ [<span class='inner'>−</span>]\ </a>\ - </span>"); + </span>" + ); // Write `src` tag // @@ -1648,19 +1657,20 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) { // used to find the link to auto-click. if cx.shared.include_sources && !item.is_primitive() { if let Some(l) = cx.src_href(item) { - write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", - l, "goto source code"); + write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code"); } } write!(buf, "</span>"); // out-of-band write!(buf, "<span class='in-band'>"); let name = match item.inner { - clean::ModuleItem(ref m) => if m.is_crate { + clean::ModuleItem(ref m) => { + if m.is_crate { "Crate " } else { "Module " - }, + } + } clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ", clean::TraitItem(..) => "Trait ", clean::StructItem(..) => "Struct ", @@ -1672,7 +1682,7 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) { MacroKind::Bang => "Macro ", MacroKind::Attr => "Attribute Macro ", MacroKind::Derive => "Derive Macro ", - } + }, clean::PrimitiveItem(..) => "Primitive Type ", clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ", clean::ConstantItem(..) => "Constant ", @@ -1690,21 +1700,23 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) { let cur = &cx.current; let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() }; for (i, component) in cur.iter().enumerate().take(amt) { - write!(buf, "<a href='{}index.html'>{}</a>::<wbr>", - "../".repeat(cur.len() - i - 1), - component); + write!( + buf, + "<a href='{}index.html'>{}</a>::<wbr>", + "../".repeat(cur.len() - i - 1), + component + ); } } - write!(buf, "<a class=\"{}\" href=''>{}</a>", - item.type_(), item.name.as_ref().unwrap()); + write!(buf, "<a class=\"{}\" href=''>{}</a>", item.type_(), item.name.as_ref().unwrap()); write!(buf, "</span></h1>"); // in-band match item.inner { - clean::ModuleItem(ref m) => - item_module(buf, cx, item, &m.items), - clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => - item_function(buf, cx, item, f), + clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items), + clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => { + item_function(buf, cx, item, f) + } clean::TraitItem(ref t) => item_trait(buf, cx, item, t), clean::StructItem(ref s) => item_struct(buf, cx, item, s), clean::UnionItem(ref s) => item_union(buf, cx, item, s), @@ -1713,8 +1725,7 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) { clean::MacroItem(ref m) => item_macro(buf, cx, item, m), clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m), clean::PrimitiveItem(_) => item_primitive(buf, cx, item), - clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => - item_static(buf, cx, item, i), + clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i), clean::ConstantItem(ref c) => item_constant(buf, cx, item, c), clean::ForeignTypeItem => item_foreign_type(buf, cx, item), clean::KeywordItem(_) => item_keyword(buf, cx, item), @@ -1745,7 +1756,8 @@ fn full_path(cx: &Context, item: &clean::Item) -> String { fn plain_summary_line(s: Option<&str>) -> String { let s = s.unwrap_or(""); // This essentially gets the first paragraph of text in one line. - let mut line = s.lines() + let mut line = s + .lines() .skip_while(|line| line.chars().all(|c| c.is_whitespace())) .take_while(|line| line.chars().any(|c| !c.is_whitespace())) .fold(String::new(), |mut acc, line| { @@ -1761,14 +1773,15 @@ fn plain_summary_line(s: Option<&str>) -> String { fn shorten(s: String) -> String { if s.chars().count() > 60 { let mut len = 0; - let mut ret = s.split_whitespace() - .take_while(|p| { - // + 1 for the added character after the word. - len += p.chars().count() + 1; - len < 60 - }) - .collect::<Vec<_>>() - .join(" "); + let mut ret = s + .split_whitespace() + .take_while(|p| { + // + 1 for the added character after the word. + len += p.chars().count() + 1; + len < 60 + }) + .collect::<Vec<_>>() + .join(" "); ret.push('…'); ret } else { @@ -1794,11 +1807,21 @@ fn render_markdown( is_hidden: bool, ) { let mut ids = cx.id_map.borrow_mut(); - write!(w, "<div class='docblock{}'>{}{}</div>", - if is_hidden { " hidden" } else { "" }, - prefix, - Markdown(md_text, &links, &mut ids, - cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string()) + write!( + w, + "<div class='docblock{}'>{}{}</div>", + if is_hidden { " hidden" } else { "" }, + prefix, + Markdown( + md_text, + &links, + &mut ids, + cx.shared.codes, + cx.shared.edition, + &cx.shared.playground + ) + .to_string() + ) } fn document_short( @@ -1811,16 +1834,22 @@ fn document_short( ) { if let Some(s) = item.doc_value() { let markdown = if s.contains('\n') { - format!("{} [Read more]({})", - &plain_summary_line(Some(s)), naive_assoc_href(item, link)) + format!( + "{} [Read more]({})", + &plain_summary_line(Some(s)), + naive_assoc_href(item, link) + ) } else { plain_summary_line(Some(s)) }; render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden); } else if !prefix.is_empty() { - write!(w, "<div class='docblock{}'>{}</div>", - if is_hidden { " hidden" } else { "" }, - prefix); + write!( + w, + "<div class='docblock{}'>{}</div>", + if is_hidden { " hidden" } else { "" }, + prefix + ); } } @@ -1829,9 +1858,12 @@ fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, debug!("Doc block: =====\n{}\n=====", s); render_markdown(w, cx, &*s, item.links(), prefix, is_hidden); } else if !prefix.is_empty() { - write!(w, "<div class='docblock{}'>{}</div>", - if is_hidden { " hidden" } else { "" }, - prefix); + write!( + w, + "<div class='docblock{}'>{}</div>", + if is_hidden { " hidden" } else { "" }, + prefix + ); } } @@ -1865,22 +1897,34 @@ fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) { }); if item.is_struct() { - write!(w, "Non-exhaustive structs could have additional fields added in future. \ + write!( + w, + "Non-exhaustive structs could have additional fields added in future. \ Therefore, non-exhaustive structs cannot be constructed in external crates \ using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \ matched against without a wildcard <code>..</code>; and \ - struct update syntax will not work."); + struct update syntax will not work." + ); } else if item.is_enum() { - write!(w, "Non-exhaustive enums could have additional variants added in future. \ + write!( + w, + "Non-exhaustive enums could have additional variants added in future. \ Therefore, when matching against variants of non-exhaustive enums, an \ - extra wildcard arm must be added to account for any future variants."); + extra wildcard arm must be added to account for any future variants." + ); } else if item.is_variant() { - write!(w, "Non-exhaustive enum variants could have additional fields added in future. \ + write!( + w, + "Non-exhaustive enum variants could have additional fields added in future. \ Therefore, non-exhaustive enum variants cannot be constructed in external \ - crates and cannot be matched against."); + crates and cannot be matched against." + ); } else { - write!(w, "This type will require a wildcard arm in any match statements or \ - constructors."); + write!( + w, + "This type will require a wildcard arm in any match statements or \ + constructors." + ); } write!(w, "</div>"); @@ -1888,12 +1932,10 @@ fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) { } fn name_key(name: &str) -> (&str, u64, usize) { - let end = name.bytes() - .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1); + let end = name.bytes().rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1); // find number at end - let split = name[0..end].bytes() - .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1); + let split = name[0..end].bytes().rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1); // count leading zeroes let after_zeroes = @@ -1916,20 +1958,20 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean: // the order of item types in the listing fn reorder(ty: ItemType) -> u8 { match ty { - ItemType::ExternCrate => 0, - ItemType::Import => 1, - ItemType::Primitive => 2, - ItemType::Module => 3, - ItemType::Macro => 4, - ItemType::Struct => 5, - ItemType::Enum => 6, - ItemType::Constant => 7, - ItemType::Static => 8, - ItemType::Trait => 9, - ItemType::Function => 10, - ItemType::Typedef => 12, - ItemType::Union => 13, - _ => 14 + ty as u8, + ItemType::ExternCrate => 0, + ItemType::Import => 1, + ItemType::Primitive => 2, + ItemType::Module => 3, + ItemType::Macro => 4, + ItemType::Struct => 5, + ItemType::Enum => 6, + ItemType::Constant => 7, + ItemType::Static => 8, + ItemType::Trait => 9, + ItemType::Function => 10, + ItemType::Typedef => 12, + ItemType::Union => 13, + _ => 14 + ty as u8, } } @@ -1937,7 +1979,7 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean: let ty1 = i1.type_(); let ty2 = i2.type_(); if ty1 != ty2 { - return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2)) + return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2)); } let s1 = i1.stability.as_ref().map(|s| s.level); let s2 = i2.stability.as_ref().map(|s| s.level); @@ -1973,18 +2015,14 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean: // can be identical even if the elements are different (mostly in imports). // So in case this is an import, we keep everything by adding a "unique id" // (which is the position in the vector). - indices.dedup_by_key(|i| (items[*i].def_id, - if items[*i].name.as_ref().is_some() { - Some(full_path(cx, &items[*i])) - } else { - None - }, - items[*i].type_(), - if items[*i].is_import() { - *i - } else { - 0 - })); + indices.dedup_by_key(|i| { + ( + items[*i].def_id, + if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None }, + items[*i].type_(), + if items[*i].is_import() { *i } else { 0 }, + ) + }); debug!("{:?}", indices); let mut curty = None; @@ -2004,9 +2042,13 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean: } curty = myty; let (short, name) = item_ty_to_strs(&myty.unwrap()); - write!(w, "<h2 id='{id}' class='section-header'>\ + write!( + w, + "<h2 id='{id}' class='section-header'>\ <a href=\"#{id}\">{name}</a></h2>\n<table>", - id = cx.derive_id(short.to_owned()), name = name); + id = cx.derive_id(short.to_owned()), + name = name + ); } match myitem.inner { @@ -2014,69 +2056,72 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean: use crate::html::format::anchor; match *src { - Some(ref src) => { - write!(w, "<tr><td><code>{}extern crate {} as {};", - myitem.visibility.print_with_space(), - anchor(myitem.def_id, src), - name) - } - None => { - write!(w, "<tr><td><code>{}extern crate {};", - myitem.visibility.print_with_space(), - anchor(myitem.def_id, name)) - } + Some(ref src) => write!( + w, + "<tr><td><code>{}extern crate {} as {};", + myitem.visibility.print_with_space(), + anchor(myitem.def_id, src), + name + ), + None => write!( + w, + "<tr><td><code>{}extern crate {};", + myitem.visibility.print_with_space(), + anchor(myitem.def_id, name) + ), } write!(w, "</code></td></tr>"); } clean::ImportItem(ref import) => { - write!(w, "<tr><td><code>{}{}</code></td></tr>", - myitem.visibility.print_with_space(), import.print()); + write!( + w, + "<tr><td><code>{}{}</code></td></tr>", + myitem.visibility.print_with_space(), + import.print() + ); } _ => { - if myitem.name.is_none() { continue } + if myitem.name.is_none() { + continue; + } let unsafety_flag = match myitem.inner { clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func) - if func.header.unsafety == hir::Unsafety::Unsafe => { + if func.header.unsafety == hir::Unsafety::Unsafe => + { "<a title='unsafe function' href='#'><sup>âš </sup></a>" } _ => "", }; let stab = myitem.stability_class(); - let add = if stab.is_some() { - " " - } else { - "" - }; + let add = if stab.is_some() { " " } else { "" }; let doc_value = myitem.doc_value().unwrap_or(""); - write!(w, "\ + write!( + w, + "\ <tr class='{stab}{add}module-item'>\ <td><a class=\"{class}\" href=\"{href}\" \ title='{title}'>{name}</a>{unsafety_flag}</td>\ <td class='docblock-short'>{stab_tags}{docs}</td>\ </tr>", - name = *myitem.name.as_ref().unwrap(), - stab_tags = stability_tags(myitem), - docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(), - class = myitem.type_(), - add = add, - stab = stab.unwrap_or_else(|| String::new()), - unsafety_flag = unsafety_flag, - href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()), - title = [full_path(cx, myitem), myitem.type_().to_string()] - .iter() - .filter_map(|s| if !s.is_empty() { - Some(s.as_str()) - } else { - None - }) - .collect::<Vec<_>>() - .join(" "), - ); + name = *myitem.name.as_ref().unwrap(), + stab_tags = stability_tags(myitem), + docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(), + class = myitem.type_(), + add = add, + stab = stab.unwrap_or_else(|| String::new()), + unsafety_flag = unsafety_flag, + href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()), + title = [full_path(cx, myitem), myitem.type_().to_string()] + .iter() + .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None }) + .collect::<Vec<_>>() + .join(" "), + ); } } } @@ -2110,11 +2155,7 @@ fn stability_tags(item: &clean::Item) -> String { tags += &tag_html("deprecated", message); } - if let Some(stab) = item - .stability - .as_ref() - .filter(|s| s.level == stability::Unstable) - { + if let Some(stab) = item.stability.as_ref().filter(|s| s.level == stability::Unstable) { if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") { tags += &tag_html("internal", "Internal"); } else { @@ -2156,17 +2197,18 @@ fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> { if let Some(note) = note { let mut ids = cx.id_map.borrow_mut(); let html = MarkdownHtml( - ¬e, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground); + ¬e, + &mut ids, + error_codes, + cx.shared.edition, + &cx.shared.playground, + ); message.push_str(&format!(": {}", html.to_string())); } stability.push(format!("<div class='stab deprecated'>{}</div>", message)); } - if let Some(stab) = item - .stability - .as_ref() - .filter(|stab| stab.level == stability::Unstable) - { + if let Some(stab) = item.stability.as_ref().filter(|stab| stab.level == stability::Unstable) { let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private"); let mut message = if is_rustc_private { @@ -2211,23 +2253,17 @@ fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> { error_codes, cx.shared.edition, &cx.shared.playground, - ).to_string() + ) + .to_string() ); } - let class = if is_rustc_private { - "internal" - } else { - "unstable" - }; + let class = if is_rustc_private { "internal" } else { "unstable" }; stability.push(format!("<div class='stab {}'>{}</div>", class, message)); } if let Some(ref cfg) = item.attrs.cfg { - stability.push(format!( - "<div class='stab portability'>{}</div>", - cfg.render_long_html() - )); + stability.push(format!("<div class='stab portability'>{}</div>", cfg.render_long_html())); } stability @@ -2236,23 +2272,29 @@ fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> { fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) { write!(w, "<pre class='rust const'>"); render_attributes(w, it, false); - write!(w, "{vis}const \ + write!( + w, + "{vis}const \ {name}: {typ}</pre>", - vis = it.visibility.print_with_space(), - name = it.name.as_ref().unwrap(), - typ = c.type_.print()); + vis = it.visibility.print_with_space(), + name = it.name.as_ref().unwrap(), + typ = c.type_.print() + ); document(w, cx, it) } fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) { write!(w, "<pre class='rust static'>"); render_attributes(w, it, false); - write!(w, "{vis}static {mutability}\ + write!( + w, + "{vis}static {mutability}\ {name}: {typ}</pre>", - vis = it.visibility.print_with_space(), - mutability = s.mutability.print_with_space(), - name = it.name.as_ref().unwrap(), - typ = s.type_.print()); + vis = it.visibility.print_with_space(), + mutability = s.mutability.print_with_space(), + name = it.name.as_ref().unwrap(), + typ = s.type_.print() + ); document(w, cx, it) } @@ -2266,60 +2308,77 @@ fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Func print_abi_with_space(f.header.abi), it.name.as_ref().unwrap(), f.generics.print() - ).len(); + ) + .len(); write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)); render_attributes(w, it, false); - write!(w, - "{vis}{constness}{unsafety}{asyncness}{abi}fn \ + write!( + w, + "{vis}{constness}{unsafety}{asyncness}{abi}fn \ {name}{generics}{decl}{where_clause}</pre>", - vis = it.visibility.print_with_space(), - constness = f.header.constness.print_with_space(), - unsafety = f.header.unsafety.print_with_space(), - asyncness = f.header.asyncness.print_with_space(), - abi = print_abi_with_space(f.header.abi), - name = it.name.as_ref().unwrap(), - generics = f.generics.print(), - where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true }, - decl = Function { - decl: &f.decl, - header_len, - indent: 0, - asyncness: f.header.asyncness, - }.print()); + vis = it.visibility.print_with_space(), + constness = f.header.constness.print_with_space(), + unsafety = f.header.unsafety.print_with_space(), + asyncness = f.header.asyncness.print_with_space(), + abi = print_abi_with_space(f.header.abi), + name = it.name.as_ref().unwrap(), + generics = f.generics.print(), + where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true }, + decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness } + .print() + ); document(w, cx, it) } -fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer, - implementor_dups: &FxHashMap<&str, (DefId, bool)>) { +fn render_implementor( + cx: &Context, + implementor: &Impl, + w: &mut Buffer, + implementor_dups: &FxHashMap<&str, (DefId, bool)>, +) { // If there's already another implementor that has the same abbridged name, use the // full path, for example in `std::iter::ExactSizeIterator` let use_absolute = match implementor.inner_impl().for_ { - clean::ResolvedPath { ref path, is_generic: false, .. } | - clean::BorrowedRef { + clean::ResolvedPath { ref path, is_generic: false, .. } + | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, is_generic: false, .. }, .. } => implementor_dups[path.last_name()].1, _ => false, }; - render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal, - implementor.impl_item.stable_since(), false, Some(use_absolute), false, false); + render_impl( + w, + cx, + implementor, + AssocItemLink::Anchor(None), + RenderMode::Normal, + implementor.impl_item.stable_since(), + false, + Some(use_absolute), + false, + false, + ); } -fn render_impls(cx: &Context, w: &mut Buffer, - traits: &[&&Impl], - containing_item: &clean::Item) { - let mut impls = traits.iter() +fn render_impls(cx: &Context, w: &mut Buffer, traits: &[&&Impl], containing_item: &clean::Item) { + let mut impls = traits + .iter() .map(|i| { let did = i.trait_did().unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods); - let mut buffer = if w.is_for_html() { - Buffer::html() - } else { - Buffer::new() - }; - render_impl(&mut buffer, cx, i, assoc_link, - RenderMode::Normal, containing_item.stable_since(), - true, None, false, true); + let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() }; + render_impl( + &mut buffer, + cx, + i, + assoc_link, + RenderMode::Normal, + containing_item.stable_since(), + true, + None, + false, + true, + ); buffer.into_inner() }) .collect::<Vec<_>>(); @@ -2351,12 +2410,7 @@ fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering { name_key(&lhs).cmp(&name_key(&rhs)) } -fn item_trait( - w: &mut Buffer, - cx: &Context, - it: &clean::Item, - t: &clean::Trait, -) { +fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait) { let bounds = bounds(&t.bounds, false); let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>(); let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>(); @@ -2367,13 +2421,16 @@ fn item_trait( wrap_into_docblock(w, |w| { write!(w, "<pre class='rust trait'>"); render_attributes(w, it, true); - write!(w, "{}{}{}trait {}{}{}", - it.visibility.print_with_space(), - t.unsafety.print_with_space(), - if t.is_auto { "auto " } else { "" }, - it.name.as_ref().unwrap(), - t.generics.print(), - bounds); + write!( + w, + "{}{}{}trait {}{}{}", + it.visibility.print_with_space(), + t.unsafety.print_with_space(), + if t.is_auto { "auto " } else { "" }, + it.name.as_ref().unwrap(), + t.generics.print(), + bounds + ); if !t.generics.where_predicates.is_empty() { write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true }); @@ -2405,7 +2462,7 @@ fn item_trait( write!(w, ";\n"); if pos < required.len() - 1 { - write!(w, "<div class='item-spacer'></div>"); + write!(w, "<div class='item-spacer'></div>"); } } if !required.is_empty() && !provided.is_empty() { @@ -2416,13 +2473,13 @@ fn item_trait( match m.inner { clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => { write!(w, ",\n {{ ... }}\n"); - }, + } _ => { write!(w, " {{ ... }}\n"); - }, + } } if pos < provided.len() - 1 { - write!(w, "<div class='item-spacer'></div>"); + write!(w, "<div class='item-spacer'></div>"); } } write!(w, "}}"); @@ -2433,16 +2490,15 @@ fn item_trait( // Trait documentation document(w, cx, it); - fn write_small_section_header( - w: &mut Buffer, - id: &str, - title: &str, - extra_content: &str, - ) { - write!(w, " + fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) { + write!( + w, + " <h2 id='{0}' class='small-section-header'>\ {1}<a href='#{0}' class='anchor'></a>\ - </h2>{2}", id, title, extra_content) + </h2>{2}", + id, title, extra_content + ) } fn write_loading_content(w: &mut Buffer, extra_content: &str) { @@ -2454,10 +2510,13 @@ fn item_trait( let item_type = m.type_(); let id = cx.derive_id(format!("{}.{}", item_type, name)); let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space())); - write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>", - extra = render_spotlight_traits(m), - id = id, - ns_id = ns_id); + write!( + w, + "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>", + extra = render_spotlight_traits(m), + id = id, + ns_id = ns_id + ); render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl); write!(w, "</code>"); render_stability_since(w, m, t); @@ -2466,8 +2525,12 @@ fn item_trait( } if !types.is_empty() { - write_small_section_header(w, "associated-types", "Associated Types", - "<div class='methods'>"); + write_small_section_header( + w, + "associated-types", + "Associated Types", + "<div class='methods'>", + ); for t in &types { trait_item(w, cx, *t, it); } @@ -2475,8 +2538,12 @@ fn item_trait( } if !consts.is_empty() { - write_small_section_header(w, "associated-const", "Associated Constants", - "<div class='methods'>"); + write_small_section_header( + w, + "associated-const", + "Associated Constants", + "<div class='methods'>", + ); for t in &consts { trait_item(w, cx, *t, it); } @@ -2485,16 +2552,24 @@ fn item_trait( // Output the documentation for each function individually if !required.is_empty() { - write_small_section_header(w, "required-methods", "Required methods", - "<div class='methods'>"); + write_small_section_header( + w, + "required-methods", + "Required methods", + "<div class='methods'>", + ); for m in &required { trait_item(w, cx, *m, it); } write_loading_content(w, "</div>"); } if !provided.is_empty() { - write_small_section_header(w, "provided-methods", "Provided methods", - "<div class='methods'>"); + write_small_section_header( + w, + "provided-methods", + "Provided methods", + "<div class='methods'>", + ); for m in &provided { trait_item(w, cx, *m, it); } @@ -2512,8 +2587,8 @@ fn item_trait( let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default(); for implementor in implementors { match implementor.inner_impl().for_ { - clean::ResolvedPath { ref path, did, is_generic: false, .. } | - clean::BorrowedRef { + clean::ResolvedPath { ref path, did, is_generic: false, .. } + | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. }, .. } => { @@ -2527,13 +2602,12 @@ fn item_trait( } } - let (local, foreign) = implementors.iter() - .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id() - .map_or(true, |d| cx.cache.paths.contains_key(&d))); - + let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| { + i.inner_impl().for_.def_id().map_or(true, |d| cx.cache.paths.contains_key(&d)) + }); - let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter() - .partition(|i| i.inner_impl().synthetic); + let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = + local.iter().partition(|i| i.inner_impl().synthetic); synthetic.sort_by(compare_impl); concrete.sort_by(compare_impl); @@ -2544,29 +2618,45 @@ fn item_trait( for implementor in foreign { let assoc_link = AssocItemLink::GotoSource( implementor.impl_item.def_id, - &implementor.inner_impl().provided_trait_methods + &implementor.inner_impl().provided_trait_methods, + ); + render_impl( + w, + cx, + &implementor, + assoc_link, + RenderMode::Normal, + implementor.impl_item.stable_since(), + false, + None, + true, + false, ); - render_impl(w, cx, &implementor, assoc_link, - RenderMode::Normal, implementor.impl_item.stable_since(), false, - None, true, false); } write_loading_content(w, ""); } - write_small_section_header(w, "implementors", "Implementors", - "<div class='item-list' id='implementors-list'>"); + write_small_section_header( + w, + "implementors", + "Implementors", + "<div class='item-list' id='implementors-list'>", + ); for implementor in concrete { render_implementor(cx, implementor, w, &implementor_dups); } write_loading_content(w, "</div>"); if t.auto { - write_small_section_header(w, "synthetic-implementors", "Auto implementors", - "<div class='item-list' id='synthetic-implementors-list'>"); + write_small_section_header( + w, + "synthetic-implementors", + "Auto implementors", + "<div class='item-list' id='synthetic-implementors-list'>", + ); for implementor in synthetic { - synthetic_types.extend( - collect_paths_for_type(implementor.inner_impl().for_.clone()) - ); + synthetic_types + .extend(collect_paths_for_type(implementor.inner_impl().for_.clone())); render_implementor(cx, implementor, w, &implementor_dups); } write_loading_content(w, "</div>"); @@ -2574,13 +2664,21 @@ fn item_trait( } else { // even without any implementations to write in, we still want the heading and list, so the // implementors javascript file pulled in below has somewhere to write the impls into - write_small_section_header(w, "implementors", "Implementors", - "<div class='item-list' id='implementors-list'>"); + write_small_section_header( + w, + "implementors", + "Implementors", + "<div class='item-list' id='implementors-list'>", + ); write_loading_content(w, "</div>"); if t.auto { - write_small_section_header(w, "synthetic-implementors", "Auto implementors", - "<div class='item-list' id='synthetic-implementors-list'>"); + write_small_section_header( + w, + "synthetic-implementors", + "Auto implementors", + "<div class='item-list' id='synthetic-implementors-list'>", + ); write_loading_content(w, "</div>"); } } @@ -2590,18 +2688,21 @@ fn item_trait( serde_json::to_string(&synthetic_types).unwrap(), ); - write!(w, r#"<script type="text/javascript" async + write!( + w, + r#"<script type="text/javascript" async src="{root_path}/implementors/{path}/{ty}.{name}.js"> </script>"#, - root_path = vec![".."; cx.current.len()].join("/"), - path = if it.def_id.is_local() { - cx.current.join("/") - } else { - let (ref path, _) = cx.cache.external_paths[&it.def_id]; - path[..path.len() - 1].join("/") - }, - ty = it.type_(), - name = *it.name.as_ref().unwrap()); + root_path = vec![".."; cx.current.len()].join("/"), + path = if it.def_id.is_local() { + cx.current.join("/") + } else { + let (ref path, _) = cx.cache.external_paths[&it.def_id]; + path[..path.len() - 1].join("/") + }, + ty = it.type_(), + name = *it.name.as_ref().unwrap() + ); } fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String { @@ -2610,7 +2711,7 @@ fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String { let name = it.name.as_ref().unwrap(); let ty = match it.type_() { Typedef | AssocType => AssocType, - s@_ => s, + s @ _ => s, }; let anchor = format!("#{}.{}", ty, name); @@ -2623,29 +2724,40 @@ fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String { } } -fn assoc_const(w: &mut Buffer, - it: &clean::Item, - ty: &clean::Type, - _default: Option<&String>, - link: AssocItemLink<'_>, - extra: &str) { - write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}", - extra, - it.visibility.print_with_space(), - naive_assoc_href(it, link), - it.name.as_ref().unwrap(), - ty.print()); +fn assoc_const( + w: &mut Buffer, + it: &clean::Item, + ty: &clean::Type, + _default: Option<&String>, + link: AssocItemLink<'_>, + extra: &str, +) { + write!( + w, + "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}", + extra, + it.visibility.print_with_space(), + naive_assoc_href(it, link), + it.name.as_ref().unwrap(), + ty.print() + ); } -fn assoc_type(w: &mut Buffer, it: &clean::Item, - bounds: &[clean::GenericBound], - default: Option<&clean::Type>, - link: AssocItemLink<'_>, - extra: &str) { - write!(w, "{}type <a href='{}' class=\"type\">{}</a>", - extra, - naive_assoc_href(it, link), - it.name.as_ref().unwrap()); +fn assoc_type( + w: &mut Buffer, + it: &clean::Item, + bounds: &[clean::GenericBound], + default: Option<&clean::Type>, + link: AssocItemLink<'_>, + extra: &str, +) { + write!( + w, + "{}type <a href='{}' class=\"type\">{}</a>", + extra, + naive_assoc_href(it, link), + it.name.as_ref().unwrap() + ); if !bounds.is_empty() { write!(w, ": {}", print_generic_bounds(bounds)) } @@ -2666,17 +2778,21 @@ fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: & render_stability_since_raw(w, item.stable_since(), containing_item.stable_since()) } -fn render_assoc_item(w: &mut Buffer, - item: &clean::Item, - link: AssocItemLink<'_>, - parent: ItemType) { - fn method(w: &mut Buffer, - meth: &clean::Item, - header: hir::FnHeader, - g: &clean::Generics, - d: &clean::FnDecl, - link: AssocItemLink<'_>, - parent: ItemType) { +fn render_assoc_item( + w: &mut Buffer, + item: &clean::Item, + link: AssocItemLink<'_>, + parent: ItemType, +) { + fn method( + w: &mut Buffer, + meth: &clean::Item, + header: hir::FnHeader, + g: &clean::Generics, + d: &clean::FnDecl, + link: AssocItemLink<'_>, + parent: ItemType, + ) { let name = meth.name.as_ref().unwrap(); let anchor = format!("#{}.{}", meth.type_(), name); let href = match link { @@ -2704,7 +2820,8 @@ fn render_assoc_item(w: &mut Buffer, print_abi_with_space(header.abi), name, g.print() - ).len(); + ) + .len(); let (indent, end_newline) = if parent == ItemType::Trait { header_len += 4; (4, false) @@ -2712,47 +2829,45 @@ fn render_assoc_item(w: &mut Buffer, (0, true) }; render_attributes(w, meth, false); - write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\ + write!( + w, + "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\ {generics}{decl}{where_clause}", - if parent == ItemType::Trait { " " } else { "" }, - meth.visibility.print_with_space(), - header.constness.print_with_space(), - header.unsafety.print_with_space(), - header.asyncness.print_with_space(), - print_default_space(meth.is_default()), - print_abi_with_space(header.abi), - href = href, - name = name, - generics = g.print(), - decl = Function { - decl: d, - header_len, - indent, - asyncness: header.asyncness, - }.print(), - where_clause = WhereClause { - gens: g, - indent, - end_newline, - }) + if parent == ItemType::Trait { " " } else { "" }, + meth.visibility.print_with_space(), + header.constness.print_with_space(), + header.unsafety.print_with_space(), + header.asyncness.print_with_space(), + print_default_space(meth.is_default()), + print_abi_with_space(header.abi), + href = href, + name = name, + generics = g.print(), + decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(), + where_clause = WhereClause { gens: g, indent, end_newline } + ) } match item.inner { - clean::StrippedItem(..) => {}, - clean::TyMethodItem(ref m) => { - method(w, item, m.header, &m.generics, &m.decl, link, parent) - } - clean::MethodItem(ref m) => { - method(w, item, m.header, &m.generics, &m.decl, link, parent) - } - clean::AssocConstItem(ref ty, ref default) => { - assoc_const(w, item, ty, default.as_ref(), link, - if parent == ItemType::Trait { " " } else { "" }) - } - clean::AssocTypeItem(ref bounds, ref default) => { - assoc_type(w, item, bounds, default.as_ref(), link, - if parent == ItemType::Trait { " " } else { "" }) - } - _ => panic!("render_assoc_item called on non-associated-item") + clean::StrippedItem(..) => {} + clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent), + clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent), + clean::AssocConstItem(ref ty, ref default) => assoc_const( + w, + item, + ty, + default.as_ref(), + link, + if parent == ItemType::Trait { " " } else { "" }, + ), + clean::AssocTypeItem(ref bounds, ref default) => assoc_type( + w, + item, + bounds, + default.as_ref(), + link, + if parent == ItemType::Trait { " " } else { "" }, + ), + _ => panic!("render_assoc_item called on non-associated-item"), } } @@ -2760,45 +2875,51 @@ fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct wrap_into_docblock(w, |w| { write!(w, "<pre class='rust struct'>"); render_attributes(w, it, true); - render_struct(w, - it, - Some(&s.generics), - s.struct_type, - &s.fields, - "", - true); + render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true); write!(w, "</pre>") }); document(w, cx, it); - let mut fields = s.fields.iter().filter_map(|f| { - match f.inner { + let mut fields = s + .fields + .iter() + .filter_map(|f| match f.inner { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, - } - }).peekable(); + }) + .peekable(); if let doctree::Plain = s.struct_type { if fields.peek().is_some() { - write!(w, "<h2 id='fields' class='fields small-section-header'> + write!( + w, + "<h2 id='fields' class='fields small-section-header'> Fields{}<a href='#fields' class='anchor'></a></h2>", - document_non_exhaustive_header(it)); + document_non_exhaustive_header(it) + ); document_non_exhaustive(w, it); for (field, ty) in fields { - let id = cx.derive_id(format!("{}.{}", - ItemType::StructField, - field.name.as_ref().unwrap())); - let ns_id = cx.derive_id(format!("{}.{}", - field.name.as_ref().unwrap(), - ItemType::StructField.name_space())); - write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\ + let id = cx.derive_id(format!( + "{}.{}", + ItemType::StructField, + field.name.as_ref().unwrap() + )); + let ns_id = cx.derive_id(format!( + "{}.{}", + field.name.as_ref().unwrap(), + ItemType::StructField.name_space() + )); + write!( + w, + "<span id=\"{id}\" class=\"{item_type} small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code id=\"{ns_id}\">{name}: {ty}</code>\ </span>", - item_type = ItemType::StructField, - id = id, - ns_id = ns_id, - name = field.name.as_ref().unwrap(), - ty = ty.print()); + item_type = ItemType::StructField, + id = id, + ns_id = ns_id, + name = field.name.as_ref().unwrap(), + ty = ty.print() + ); document(w, cx, field); } } @@ -2810,39 +2931,41 @@ fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) wrap_into_docblock(w, |w| { write!(w, "<pre class='rust union'>"); render_attributes(w, it, true); - render_union(w, - it, - Some(&s.generics), - &s.fields, - "", - true); + render_union(w, it, Some(&s.generics), &s.fields, "", true); write!(w, "</pre>") }); document(w, cx, it); - let mut fields = s.fields.iter().filter_map(|f| { - match f.inner { + let mut fields = s + .fields + .iter() + .filter_map(|f| match f.inner { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, - } - }).peekable(); + }) + .peekable(); if fields.peek().is_some() { - write!(w, "<h2 id='fields' class='fields small-section-header'> - Fields<a href='#fields' class='anchor'></a></h2>"); + write!( + w, + "<h2 id='fields' class='fields small-section-header'> + Fields<a href='#fields' class='anchor'></a></h2>" + ); for (field, ty) in fields { let name = field.name.as_ref().expect("union field name"); let id = format!("{}.{}", ItemType::StructField, name); - write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\ + write!( + w, + "<span id=\"{id}\" class=\"{shortty} small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code>{name}: {ty}</code>\ </span>", - id = id, - name = name, - shortty = ItemType::StructField, - ty = ty.print()); + id = id, + name = name, + shortty = ItemType::StructField, + ty = ty.print() + ); if let Some(stability_class) = field.stability_class() { - write!(w, "<span class='stab {stab}'></span>", - stab = stability_class); + write!(w, "<span class='stab {stab}'></span>", stab = stability_class); } document(w, cx, field); } @@ -2854,11 +2977,14 @@ fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) { wrap_into_docblock(w, |w| { write!(w, "<pre class='rust enum'>"); render_attributes(w, it, true); - write!(w, "{}enum {}{}{}", - it.visibility.print_with_space(), - it.name.as_ref().unwrap(), - e.generics.print(), - WhereClause { gens: &e.generics, indent: 0, end_newline: true }); + write!( + w, + "{}enum {}{}{}", + it.visibility.print_with_space(), + it.name.as_ref().unwrap(), + e.generics.print(), + WhereClause { gens: &e.generics, indent: 0, end_newline: true } + ); if e.variants.is_empty() && !e.variants_stripped { write!(w, " {{}}"); } else { @@ -2867,31 +2993,23 @@ fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) { write!(w, " "); let name = v.name.as_ref().unwrap(); match v.inner { - clean::VariantItem(ref var) => { - match var.kind { - clean::VariantKind::CLike => write!(w, "{}", name), - clean::VariantKind::Tuple(ref tys) => { - write!(w, "{}(", name); - for (i, ty) in tys.iter().enumerate() { - if i > 0 { - write!(w, ", ") - } - write!(w, "{}", ty.print()); + clean::VariantItem(ref var) => match var.kind { + clean::VariantKind::CLike => write!(w, "{}", name), + clean::VariantKind::Tuple(ref tys) => { + write!(w, "{}(", name); + for (i, ty) in tys.iter().enumerate() { + if i > 0 { + write!(w, ", ") } - write!(w, ")"); - } - clean::VariantKind::Struct(ref s) => { - render_struct(w, - v, - None, - s.struct_type, - &s.fields, - " ", - false); + write!(w, "{}", ty.print()); } + write!(w, ")"); } - } - _ => unreachable!() + clean::VariantKind::Struct(ref s) => { + render_struct(w, v, None, s.struct_type, &s.fields, " ", false); + } + }, + _ => unreachable!(), } write!(w, ",\n"); } @@ -2906,23 +3024,30 @@ fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) { document(w, cx, it); if !e.variants.is_empty() { - write!(w, "<h2 id='variants' class='variants small-section-header'> + write!( + w, + "<h2 id='variants' class='variants small-section-header'> Variants{}<a href='#variants' class='anchor'></a></h2>\n", - document_non_exhaustive_header(it)); + document_non_exhaustive_header(it) + ); document_non_exhaustive(w, it); for variant in &e.variants { - let id = cx.derive_id(format!("{}.{}", - ItemType::Variant, - variant.name.as_ref().unwrap())); - let ns_id = cx.derive_id(format!("{}.{}", - variant.name.as_ref().unwrap(), - ItemType::Variant.name_space())); - write!(w, "<div id=\"{id}\" class=\"variant small-section-header\">\ + let id = + cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap())); + let ns_id = cx.derive_id(format!( + "{}.{}", + variant.name.as_ref().unwrap(), + ItemType::Variant.name_space() + )); + write!( + w, + "<div id=\"{id}\" class=\"variant small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code id='{ns_id}'>{name}", - id = id, - ns_id = ns_id, - name = variant.name.as_ref().unwrap()); + id = id, + ns_id = ns_id, + name = variant.name.as_ref().unwrap() + ); if let clean::VariantItem(ref var) = variant.inner { if let clean::VariantKind::Tuple(ref tys) = var.kind { write!(w, "("); @@ -2940,35 +3065,45 @@ fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) { document_non_exhaustive(w, variant); use crate::clean::{Variant, VariantKind}; - if let clean::VariantItem(Variant { - kind: VariantKind::Struct(ref s) - }) = variant.inner { - let variant_id = cx.derive_id(format!("{}.{}.fields", - ItemType::Variant, - variant.name.as_ref().unwrap())); - write!(w, "<div class='autohide sub-variant' id='{id}'>", - id = variant_id); - write!(w, "<h3>Fields of <b>{name}</b></h3><div>", - name = variant.name.as_ref().unwrap()); + if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner + { + let variant_id = cx.derive_id(format!( + "{}.{}.fields", + ItemType::Variant, + variant.name.as_ref().unwrap() + )); + write!(w, "<div class='autohide sub-variant' id='{id}'>", id = variant_id); + write!( + w, + "<h3>Fields of <b>{name}</b></h3><div>", + name = variant.name.as_ref().unwrap() + ); for field in &s.fields { use crate::clean::StructFieldItem; if let StructFieldItem(ref ty) = field.inner { - let id = cx.derive_id(format!("variant.{}.field.{}", - variant.name.as_ref().unwrap(), - field.name.as_ref().unwrap())); - let ns_id = cx.derive_id(format!("{}.{}.{}.{}", - variant.name.as_ref().unwrap(), - ItemType::Variant.name_space(), - field.name.as_ref().unwrap(), - ItemType::StructField.name_space())); - write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\ + let id = cx.derive_id(format!( + "variant.{}.field.{}", + variant.name.as_ref().unwrap(), + field.name.as_ref().unwrap() + )); + let ns_id = cx.derive_id(format!( + "{}.{}.{}.{}", + variant.name.as_ref().unwrap(), + ItemType::Variant.name_space(), + field.name.as_ref().unwrap(), + ItemType::StructField.name_space() + )); + write!( + w, + "<span id=\"{id}\" class=\"variant small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code id='{ns_id}'>{f}: {t}\ </code></span>", - id = id, - ns_id = ns_id, - f = field.name.as_ref().unwrap(), - t = ty.print()); + id = id, + ns_id = ns_id, + f = field.name.as_ref().unwrap(), + t = ty.print() + ); document(w, cx, field); } } @@ -2988,15 +3123,12 @@ fn render_attribute(attr: &ast::MetaItem) -> Option<String> { } else if let Some(v) = attr.value_str() { Some(format!("{} = {:?}", path, v)) } else if let Some(values) = attr.meta_item_list() { - let display: Vec<_> = values.iter().filter_map(|attr| { - attr.meta_item().and_then(|mi| render_attribute(mi)) - }).collect(); + let display: Vec<_> = values + .iter() + .filter_map(|attr| attr.meta_item().and_then(|mi| render_attribute(mi))) + .collect(); - if display.len() > 0 { - Some(format!("{}({})", path, display.join(", "))) - } else { - None - } + if display.len() > 0 { Some(format!("{}({})", path, display.join(", "))) } else { None } } else { None } @@ -3009,7 +3141,7 @@ const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[ sym::must_use, sym::no_mangle, sym::repr, - sym::non_exhaustive + sym::non_exhaustive, ]; // The `top` parameter is used when generating the item declaration to ensure it doesn't have a @@ -3032,21 +3164,31 @@ fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) { } } if attrs.len() > 0 { - write!(w, "<span class=\"docblock attributes{}\">{}</span>", - if top { " top-attr" } else { "" }, &attrs); + write!( + w, + "<span class=\"docblock attributes{}\">{}</span>", + if top { " top-attr" } else { "" }, + &attrs + ); } } -fn render_struct(w: &mut Buffer, it: &clean::Item, - g: Option<&clean::Generics>, - ty: doctree::StructType, - fields: &[clean::Item], - tab: &str, - structhead: bool) { - write!(w, "{}{}{}", - it.visibility.print_with_space(), - if structhead {"struct "} else {""}, - it.name.as_ref().unwrap()); +fn render_struct( + w: &mut Buffer, + it: &clean::Item, + g: Option<&clean::Generics>, + ty: doctree::StructType, + fields: &[clean::Item], + tab: &str, + structhead: bool, +) { + write!( + w, + "{}{}{}", + it.visibility.print_with_space(), + if structhead { "struct " } else { "" }, + it.name.as_ref().unwrap() + ); if let Some(g) = g { write!(w, "{}", g.print()) } @@ -3059,11 +3201,14 @@ fn render_struct(w: &mut Buffer, it: &clean::Item, write!(w, " {{"); for field in fields { if let clean::StructFieldItem(ref ty) = field.inner { - write!(w, "\n{} {}{}: {},", - tab, - field.visibility.print_with_space(), - field.name.as_ref().unwrap(), - ty.print()); + write!( + w, + "\n{} {}{}: {},", + tab, + field.visibility.print_with_space(), + field.name.as_ref().unwrap(), + ty.print() + ); has_visible_fields = true; } } @@ -3087,13 +3232,11 @@ fn render_struct(w: &mut Buffer, it: &clean::Item, write!(w, ", "); } match field.inner { - clean::StrippedItem(box clean::StructFieldItem(..)) => { - write!(w, "_") - } + clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"), clean::StructFieldItem(ref ty) => { write!(w, "{}{}", field.visibility.print_with_space(), ty.print()) } - _ => unreachable!() + _ => unreachable!(), } } write!(w, ")"); @@ -3112,15 +3255,21 @@ fn render_struct(w: &mut Buffer, it: &clean::Item, } } -fn render_union(w: &mut Buffer, it: &clean::Item, - g: Option<&clean::Generics>, - fields: &[clean::Item], - tab: &str, - structhead: bool) { - write!(w, "{}{}{}", - it.visibility.print_with_space(), - if structhead {"union "} else {""}, - it.name.as_ref().unwrap()); +fn render_union( + w: &mut Buffer, + it: &clean::Item, + g: Option<&clean::Generics>, + fields: &[clean::Item], + tab: &str, + structhead: bool, +) { + write!( + w, + "{}{}{}", + it.visibility.print_with_space(), + if structhead { "union " } else { "" }, + it.name.as_ref().unwrap() + ); if let Some(g) = g { write!(w, "{}", g.print()); write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }); @@ -3129,11 +3278,14 @@ fn render_union(w: &mut Buffer, it: &clean::Item, write!(w, " {{\n{}", tab); for field in fields { if let clean::StructFieldItem(ref ty) = field.inner { - write!(w, " {}{}: {},\n{}", - field.visibility.print_with_space(), - field.name.as_ref().unwrap(), - ty.print(), - tab); + write!( + w, + " {}{}: {},\n{}", + field.visibility.print_with_space(), + field.name.as_ref().unwrap(), + ty.print(), + tab + ); } } @@ -3152,7 +3304,7 @@ enum AssocItemLink<'a> { impl<'a> AssocItemLink<'a> { fn anchor(&self, id: &'a String) -> Self { match *self { - AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) }, + AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)), ref other => *other, } } @@ -3160,7 +3312,7 @@ impl<'a> AssocItemLink<'a> { enum AssocItemRender<'a> { All, - DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool } + DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }, } #[derive(Copy, Clone, PartialEq)] @@ -3169,113 +3321,148 @@ enum RenderMode { ForDeref { mut_: bool }, } -fn render_assoc_items(w: &mut Buffer, - cx: &Context, - containing_item: &clean::Item, - it: DefId, - what: AssocItemRender<'_>) { +fn render_assoc_items( + w: &mut Buffer, + cx: &Context, + containing_item: &clean::Item, + it: DefId, + what: AssocItemRender<'_>, +) { let c = &cx.cache; let v = match c.impls.get(&it) { Some(v) => v, None => return, }; - let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| { - i.inner_impl().trait_.is_none() - }); + let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none()); if !non_trait.is_empty() { let render_mode = match what { AssocItemRender::All => { - write!(w, "\ + write!( + w, + "\ <h2 id='methods' class='small-section-header'>\ Methods<a href='#methods' class='anchor'></a>\ </h2>\ - "); + " + ); RenderMode::Normal } AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => { - write!(w, "\ + write!( + w, + "\ <h2 id='deref-methods' class='small-section-header'>\ Methods from {}<Target = {}>\ <a href='#deref-methods' class='anchor'></a>\ </h2>\ - ", trait_.print(), type_.print()); + ", + trait_.print(), + type_.print() + ); RenderMode::ForDeref { mut_: deref_mut_ } } }; for i in &non_trait { - render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode, - containing_item.stable_since(), true, None, false, true); + render_impl( + w, + cx, + i, + AssocItemLink::Anchor(None), + render_mode, + containing_item.stable_since(), + true, + None, + false, + true, + ); } } if let AssocItemRender::DerefFor { .. } = what { return; } if !traits.is_empty() { - let deref_impl = traits.iter().find(|t| { - t.inner_impl().trait_.def_id() == c.deref_trait_did - }); + let deref_impl = + traits.iter().find(|t| t.inner_impl().trait_.def_id() == c.deref_trait_did); if let Some(impl_) = deref_impl { - let has_deref_mut = traits.iter().find(|t| { - t.inner_impl().trait_.def_id() == c.deref_mut_trait_did - }).is_some(); + let has_deref_mut = traits + .iter() + .find(|t| t.inner_impl().trait_.def_id() == c.deref_mut_trait_did) + .is_some(); render_deref_methods(w, cx, impl_, containing_item, has_deref_mut); } - let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits - .iter() - .partition(|t| t.inner_impl().synthetic); - let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete - .into_iter() - .partition(|t| t.inner_impl().blanket_impl.is_some()); + let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = + traits.iter().partition(|t| t.inner_impl().synthetic); + let (blanket_impl, concrete): (Vec<&&Impl>, _) = + concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some()); let mut impls = Buffer::empty_from(&w); render_impls(cx, &mut impls, &concrete, containing_item); let impls = impls.into_inner(); if !impls.is_empty() { - write!(w, "\ + write!( + w, + "\ <h2 id='implementations' class='small-section-header'>\ Trait Implementations<a href='#implementations' class='anchor'></a>\ </h2>\ - <div id='implementations-list'>{}</div>", impls); + <div id='implementations-list'>{}</div>", + impls + ); } if !synthetic.is_empty() { - write!(w, "\ + write!( + w, + "\ <h2 id='synthetic-implementations' class='small-section-header'>\ Auto Trait Implementations\ <a href='#synthetic-implementations' class='anchor'></a>\ </h2>\ <div id='synthetic-implementations-list'>\ - "); + " + ); render_impls(cx, w, &synthetic, containing_item); write!(w, "</div>"); } if !blanket_impl.is_empty() { - write!(w, "\ + write!( + w, + "\ <h2 id='blanket-implementations' class='small-section-header'>\ Blanket Implementations\ <a href='#blanket-implementations' class='anchor'></a>\ </h2>\ <div id='blanket-implementations-list'>\ - "); + " + ); render_impls(cx, w, &blanket_impl, containing_item); write!(w, "</div>"); } } } -fn render_deref_methods(w: &mut Buffer, cx: &Context, impl_: &Impl, - container_item: &clean::Item, deref_mut: bool) { +fn render_deref_methods( + w: &mut Buffer, + cx: &Context, + impl_: &Impl, + container_item: &clean::Item, + deref_mut: bool, +) { let deref_type = impl_.inner_impl().trait_.as_ref().unwrap(); - let target = impl_.inner_impl().items.iter().filter_map(|item| { - match item.inner { + let target = impl_ + .inner_impl() + .items + .iter() + .filter_map(|item| match item.inner { clean::TypedefItem(ref t, true) => Some(&t.type_), _ => None, - } - }).next().expect("Expected associated type binding"); - let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target, - deref_mut_: deref_mut }; + }) + .next() + .expect("Expected associated type binding"); + let what = + AssocItemRender::DerefFor { trait_: deref_type, type_: target, deref_mut_: deref_mut }; if let Some(did) = target.def_id() { render_assoc_items(w, cx, container_item, did, what) } else { @@ -3291,18 +3478,18 @@ fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool { let self_type_opt = match item.inner { clean::MethodItem(ref method) => method.decl.self_type(), clean::TyMethodItem(ref method) => method.decl.self_type(), - _ => None + _ => None, }; if let Some(self_ty) = self_type_opt { let (by_mut_ref, by_box, by_value) = match self_ty { - SelfTy::SelfBorrowed(_, mutability) | - SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => { + SelfTy::SelfBorrowed(_, mutability) + | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => { (mutability == Mutability::Mut, false, false) - }, + } SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => { (false, Some(did) == cache().owned_box_did, false) - }, + } SelfTy::SelfValue => (false, false, true), _ => (false, false, false), }; @@ -3315,13 +3502,11 @@ fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool { fn render_spotlight_traits(item: &clean::Item) -> String { match item.inner { - clean::FunctionItem(clean::Function { ref decl, .. }) | - clean::TyMethodItem(clean::TyMethod { ref decl, .. }) | - clean::MethodItem(clean::Method { ref decl, .. }) | - clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => { - spotlight_decl(decl) - } - _ => String::new() + clean::FunctionItem(clean::Function { ref decl, .. }) + | clean::TyMethodItem(clean::TyMethod { ref decl, .. }) + | clean::MethodItem(clean::Method { ref decl, .. }) + | clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => spotlight_decl(decl), + _ => String::new(), } } @@ -3336,24 +3521,31 @@ fn spotlight_decl(decl: &clean::FnDecl) -> String { let impl_ = i.inner_impl(); if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) { if out.is_empty() { - out.push_str( - &format!("<h3 class=\"important\">Important traits for {}</h3>\ + out.push_str(&format!( + "<h3 class=\"important\">Important traits for {}</h3>\ <code class=\"content\">", - impl_.for_.print())); + impl_.for_.print() + )); trait_.push_str(&impl_.for_.print().to_string()); } //use the "where" class here to make it small - out.push_str( - &format!("<span class=\"where fmt-newline\">{}</span>", impl_.print())); + out.push_str(&format!( + "<span class=\"where fmt-newline\">{}</span>", + impl_.print() + )); let t_did = impl_.trait_.def_id().unwrap(); for it in &impl_.items { if let clean::TypedefItem(ref tydef, _) = it.inner { out.push_str("<span class=\"where fmt-newline\"> "); - assoc_type(&mut out, it, &[], - Some(&tydef.type_), - AssocItemLink::GotoSource(t_did, &FxHashSet::default()), - ""); + assoc_type( + &mut out, + it, + &[], + Some(&tydef.type_), + AssocItemLink::GotoSource(t_did, &FxHashSet::default()), + "", + ); out.push_str(";</span>"); } } @@ -3363,27 +3555,42 @@ fn spotlight_decl(decl: &clean::FnDecl) -> String { } if !out.is_empty() { - out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\ + out.insert_str( + 0, + &format!( + "<div class=\"important-traits\"><div class='tooltip'>ⓘ\ <span class='tooltiptext'>Important traits for {}</span></div>\ <div class=\"content hidden\">", - trait_)); + trait_ + ), + ); out.push_str("</code></div></div>"); } out.into_inner() } -fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, - render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool, - use_absolute: Option<bool>, is_on_foreign_type: bool, - show_default_items: bool) { +fn render_impl( + w: &mut Buffer, + cx: &Context, + i: &Impl, + link: AssocItemLink<'_>, + render_mode: RenderMode, + outer_version: Option<&str>, + show_def_docs: bool, + use_absolute: Option<bool>, + is_on_foreign_type: bool, + show_default_items: bool, +) { if render_mode == RenderMode::Normal { let id = cx.derive_id(match i.inner_impl().trait_ { - Some(ref t) => if is_on_foreign_type { - get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t) - } else { - format!("impl-{}", small_url_encode(&format!("{:#}", t.print()))) - }, + Some(ref t) => { + if is_on_foreign_type { + get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t) + } else { + format!("impl-{}", small_url_encode(&format!("{:#}", t.print()))) + } + } None => "impl".to_string(), }); if let Some(use_absolute) = use_absolute { @@ -3393,39 +3600,63 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, for it in &i.inner_impl().items { if let clean::TypedefItem(ref tydef, _) = it.inner { write!(w, "<span class=\"where fmt-newline\"> "); - assoc_type(w, it, &vec![], Some(&tydef.type_), - AssocItemLink::Anchor(None), - ""); + assoc_type( + w, + it, + &vec![], + Some(&tydef.type_), + AssocItemLink::Anchor(None), + "", + ); write!(w, ";</span>"); } } } write!(w, "</code>"); } else { - write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>", - id, i.inner_impl().print() + write!( + w, + "<h3 id='{}' class='impl'><code class='in-band'>{}</code>", + id, + i.inner_impl().print() ); } write!(w, "<a href='#{}' class='anchor'></a>", id); let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]); render_stability_since_raw(w, since, outer_version); if let Some(l) = cx.src_href(&i.impl_item) { - write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", - l, "goto source code"); + write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code"); } write!(w, "</h3>"); if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) { let mut ids = cx.id_map.borrow_mut(); - write!(w, "<div class='docblock'>{}</div>", - Markdown(&*dox, &i.impl_item.links(), &mut ids, - cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string()); + write!( + w, + "<div class='docblock'>{}</div>", + Markdown( + &*dox, + &i.impl_item.links(), + &mut ids, + cx.shared.codes, + cx.shared.edition, + &cx.shared.playground + ) + .to_string() + ); } } - fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item, - link: AssocItemLink<'_>, render_mode: RenderMode, - is_default_item: bool, outer_version: Option<&str>, - trait_: Option<&clean::Trait>, show_def_docs: bool) { + fn doc_impl_item( + w: &mut Buffer, + cx: &Context, + item: &clean::Item, + link: AssocItemLink<'_>, + render_mode: RenderMode, + is_default_item: bool, + outer_version: Option<&str>, + trait_: Option<&clean::Trait>, + show_def_docs: bool, + ) { let item_type = item.type_(); let name = item.name.as_ref().unwrap(); @@ -3434,32 +3665,33 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_), }; - let (is_hidden, extra_class) = if (trait_.is_none() || - item.doc_value().is_some() || - item.inner.is_associated()) && - !is_default_item { - (false, "") - } else { - (true, " hidden") - }; + let (is_hidden, extra_class) = + if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_associated()) + && !is_default_item + { + (false, "") + } else { + (true, " hidden") + }; match item.inner { - clean::MethodItem(clean::Method { ref decl, .. }) | - clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => { + clean::MethodItem(clean::Method { ref decl, .. }) + | clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => { // Only render when the method is not static or we allow static methods if render_method_item { let id = cx.derive_id(format!("{}.{}", item_type, name)); - let ns_id = cx.derive_id(format!("{}.{}", - name, item_type.name_space())); - write!(w, "<h4 id='{}' class=\"{}{}\">", - id, item_type, extra_class); + let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space())); + write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class); write!(w, "{}", spotlight_decl(decl)); write!(w, "<code id='{}'>", ns_id); render_assoc_item(w, item, link.anchor(&id), ItemType::Impl); write!(w, "</code>"); render_stability_since_raw(w, item.stable_since(), outer_version); if let Some(l) = cx.src_href(item) { - write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", - l, "goto source code"); + write!( + w, + "<a class='srclink' href='{}' title='{}'>[src]</a>", + l, "goto source code" + ); } write!(w, "</h4>"); } @@ -3481,8 +3713,11 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, write!(w, "</code>"); render_stability_since_raw(w, item.stable_since(), outer_version); if let Some(l) = cx.src_href(item) { - write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", - l, "goto source code"); + write!( + w, + "<a class='srclink' href='{}' title='{}'>[src]</a>", + l, "goto source code" + ); } write!(w, "</h4>"); } @@ -3495,7 +3730,7 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, write!(w, "</code></h4>"); } clean::StrippedItem(..) => return, - _ => panic!("can't make docs for trait item with name {:?}", item.name) + _ => panic!("can't make docs for trait item with name {:?}", item.name), } if render_method_item { @@ -3535,17 +3770,28 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, write!(w, "<div class='impl-items'>"); for trait_item in &i.inner_impl().items { - doc_impl_item(w, cx, trait_item, link, render_mode, - false, outer_version, trait_, show_def_docs); + doc_impl_item( + w, + cx, + trait_item, + link, + render_mode, + false, + outer_version, + trait_, + show_def_docs, + ); } - fn render_default_items(w: &mut Buffer, - cx: &Context, - t: &clean::Trait, - i: &clean::Impl, - render_mode: RenderMode, - outer_version: Option<&str>, - show_def_docs: bool) { + fn render_default_items( + w: &mut Buffer, + cx: &Context, + t: &clean::Trait, + i: &clean::Impl, + render_mode: RenderMode, + outer_version: Option<&str>, + show_def_docs: bool, + ) { for trait_item in &t.items { let n = trait_item.name.clone(); if i.items.iter().find(|m| m.name == n).is_some() { @@ -3554,8 +3800,17 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, let did = i.trait_.as_ref().unwrap().def_id().unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods); - doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true, - outer_version, None, show_def_docs); + doc_impl_item( + w, + cx, + trait_item, + assoc_link, + render_mode, + true, + outer_version, + None, + show_def_docs, + ); } } @@ -3565,26 +3820,31 @@ fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>, // Implementations on Foreign Types or Implementors sections. if show_default_items { if let Some(t) = trait_ { - render_default_items(w, cx, t, &i.inner_impl(), - render_mode, outer_version, show_def_docs); + render_default_items( + w, + cx, + t, + &i.inner_impl(), + render_mode, + outer_version, + show_def_docs, + ); } } write!(w, "</div>"); } -fn item_opaque_ty( - w: &mut Buffer, - cx: &Context, - it: &clean::Item, - t: &clean::OpaqueTy, -) { +fn item_opaque_ty(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::OpaqueTy) { write!(w, "<pre class='rust opaque'>"); render_attributes(w, it, false); - write!(w, "type {}{}{where_clause} = impl {bounds};</pre>", - it.name.as_ref().unwrap(), - t.generics.print(), - where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }, - bounds = bounds(&t.bounds, false)); + write!( + w, + "type {}{}{where_clause} = impl {bounds};</pre>", + it.name.as_ref().unwrap(), + t.generics.print(), + where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }, + bounds = bounds(&t.bounds, false) + ); document(w, cx, it); @@ -3595,15 +3855,17 @@ fn item_opaque_ty( render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } -fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item, - t: &clean::TraitAlias) { +fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::TraitAlias) { write!(w, "<pre class='rust trait-alias'>"); render_attributes(w, it, false); - write!(w, "trait {}{}{} = {};</pre>", - it.name.as_ref().unwrap(), - t.generics.print(), - WhereClause { gens: &t.generics, indent: 0, end_newline: true }, - bounds(&t.bounds, true)); + write!( + w, + "trait {}{}{} = {};</pre>", + it.name.as_ref().unwrap(), + t.generics.print(), + WhereClause { gens: &t.generics, indent: 0, end_newline: true }, + bounds(&t.bounds, true) + ); document(w, cx, it); @@ -3617,11 +3879,14 @@ fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item, fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) { write!(w, "<pre class='rust typedef'>"); render_attributes(w, it, false); - write!(w, "type {}{}{where_clause} = {type_};</pre>", - it.name.as_ref().unwrap(), - t.generics.print(), - where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }, - type_ = t.type_.print()); + write!( + w, + "type {}{}{where_clause} = {type_};</pre>", + it.name.as_ref().unwrap(), + t.generics.print(), + where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }, + type_ = t.type_.print() + ); document(w, cx, it); @@ -3648,11 +3913,19 @@ fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) { } fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) { - let parentlen = cx.current.len() - if it.is_mod() {1} else {0}; - - if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union() - || it.is_enum() || it.is_mod() || it.is_typedef() { - write!(buffer, "<p class='location'>{}{}</p>", + let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 }; + + if it.is_struct() + || it.is_trait() + || it.is_primitive() + || it.is_union() + || it.is_enum() + || it.is_mod() + || it.is_typedef() + { + write!( + buffer, + "<p class='location'>{}{}</p>", match it.inner { clean::StructItem(..) => "Struct ", clean::TraitItem(..) => "Trait ", @@ -3661,30 +3934,37 @@ fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) { clean::EnumItem(..) => "Enum ", clean::TypedefItem(..) => "Type Definition ", clean::ForeignTypeItem => "Foreign Type ", - clean::ModuleItem(..) => if it.is_crate() { - "Crate " - } else { - "Module " - }, + clean::ModuleItem(..) => + if it.is_crate() { + "Crate " + } else { + "Module " + }, _ => "", }, - it.name.as_ref().unwrap()); + it.name.as_ref().unwrap() + ); } if it.is_crate() { if let Some(ref version) = cx.cache.crate_version { - write!(buffer, - "<div class='block version'>\ + write!( + buffer, + "<div class='block version'>\ <p>Version {}</p>\ </div>", - version); + version + ); } } write!(buffer, "<div class=\"sidebar-elems\">"); if it.is_crate() { - write!(buffer, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>", - it.name.as_ref().expect("crates always have a name")); + write!( + buffer, + "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>", + it.name.as_ref().expect("crates always have a name") + ); } match it.inner { clean::StructItem(ref s) => sidebar_struct(buffer, it, s), @@ -3711,29 +3991,33 @@ fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) { if i > 0 { write!(buffer, "::<wbr>"); } - write!(buffer, "<a href='{}index.html'>{}</a>", - &cx.root_path()[..(cx.current.len() - i - 1) * 3], - *name); + write!( + buffer, + "<a href='{}index.html'>{}</a>", + &cx.root_path()[..(cx.current.len() - i - 1) * 3], + *name + ); } write!(buffer, "</p>"); // Sidebar refers to the enclosing module, not this module. let relpath = if it.is_mod() { "../" } else { "" }; - write!(buffer, - "<script>window.sidebarCurrent = {{\ + write!( + buffer, + "<script>window.sidebarCurrent = {{\ name: '{name}', \ ty: '{ty}', \ relpath: '{path}'\ }};</script>", - name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""), - ty = it.type_(), - path = relpath); + name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""), + ty = it.type_(), + path = relpath + ); if parentlen == 0 { // There is no sidebar-items.js beyond the crate root path // FIXME maybe dynamic crate loading can be merged here } else { - write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", - path = relpath); + write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath); } // Closes sidebar-elems div. write!(buffer, "</div>"); @@ -3756,36 +4040,39 @@ fn get_methods( used_links: &mut FxHashSet<String>, deref_mut: bool, ) -> Vec<String> { - i.items.iter().filter_map(|item| { - match item.name { + i.items + .iter() + .filter_map(|item| match item.name { Some(ref name) if !name.is_empty() && item.is_method() => { if !for_deref || should_render_item(item, deref_mut) { - Some(format!("<a href=\"#{}\">{}</a>", - get_next_url(used_links, format!("method.{}", name)), - name)) + Some(format!( + "<a href=\"#{}\">{}</a>", + get_next_url(used_links, format!("method.{}", name)), + name + )) } else { None } } _ => None, - } - }).collect::<Vec<_>>() + }) + .collect::<Vec<_>>() } // The point is to url encode any potential character from a type with genericity. fn small_url_encode(s: &str) -> String { s.replace("<", "%3C") - .replace(">", "%3E") - .replace(" ", "%20") - .replace("?", "%3F") - .replace("'", "%27") - .replace("&", "%26") - .replace(",", "%2C") - .replace(":", "%3A") - .replace(";", "%3B") - .replace("[", "%5B") - .replace("]", "%5D") - .replace("\"", "%22") + .replace(">", "%3E") + .replace(" ", "%20") + .replace("?", "%3F") + .replace("'", "%27") + .replace("&", "%26") + .replace(",", "%2C") + .replace(":", "%3A") + .replace(";", "%3B") + .replace("[", "%5B") + .replace("]", "%5D") + .replace("\"", "%22") } fn sidebar_assoc_items(it: &clean::Item) -> String { @@ -3796,53 +4083,67 @@ fn sidebar_assoc_items(it: &clean::Item) -> String { { let used_links_bor = &mut used_links; - let mut ret = v.iter() - .filter(|i| i.inner_impl().trait_.is_none()) - .flat_map(move |i| get_methods(i.inner_impl(), - false, - used_links_bor, false)) - .collect::<Vec<_>>(); + let mut ret = v + .iter() + .filter(|i| i.inner_impl().trait_.is_none()) + .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false)) + .collect::<Vec<_>>(); // We want links' order to be reproducible so we don't use unstable sort. ret.sort(); if !ret.is_empty() { - out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\ - </a><div class=\"sidebar-links\">{}</div>", ret.join(""))); + out.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#methods\">Methods\ + </a><div class=\"sidebar-links\">{}</div>", + ret.join("") + )); } } if v.iter().any(|i| i.inner_impl().trait_.is_some()) { - if let Some(impl_) = v.iter() - .filter(|i| i.inner_impl().trait_.is_some()) - .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) { - if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| { - match item.inner { + if let Some(impl_) = v + .iter() + .filter(|i| i.inner_impl().trait_.is_some()) + .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) + { + if let Some(target) = impl_ + .inner_impl() + .items + .iter() + .filter_map(|item| match item.inner { clean::TypedefItem(ref t, true) => Some(&t.type_), _ => None, - } - }).next() { - let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| { - c.primitive_locations.get(&prim).cloned() - })).and_then(|did| c.impls.get(&did)); + }) + .next() + { + let inner_impl = target + .def_id() + .or(target + .primitive_type() + .and_then(|prim| c.primitive_locations.get(&prim).cloned())) + .and_then(|did| c.impls.get(&did)); if let Some(impls) = inner_impl { out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">"); - out.push_str(&format!("Methods from {}<Target={}>", + out.push_str(&format!( + "Methods from {}<Target={}>", Escape(&format!( - "{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print() + "{:#}", + impl_.inner_impl().trait_.as_ref().unwrap().print() )), - Escape(&format!("{:#}", target.print())))); + Escape(&format!("{:#}", target.print())) + )); out.push_str("</a>"); - let mut ret = impls.iter() - .filter(|i| i.inner_impl().trait_.is_none()) - .flat_map(|i| get_methods(i.inner_impl(), - true, - &mut used_links, - true)) - .collect::<Vec<_>>(); + let mut ret = impls + .iter() + .filter(|i| i.inner_impl().trait_.is_none()) + .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, true)) + .collect::<Vec<_>>(); // We want links' order to be reproducible so we don't use unstable sort. ret.sort(); if !ret.is_empty() { - out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", - ret.join(""))); + out.push_str(&format!( + "<div class=\"sidebar-links\">{}</div>", + ret.join("") + )); } } } @@ -3850,22 +4151,21 @@ fn sidebar_assoc_items(it: &clean::Item) -> String { let format_impls = |impls: Vec<&Impl>| { let mut links = FxHashSet::default(); - let mut ret = impls.iter() + let mut ret = impls + .iter() .filter_map(|i| { let is_negative_impl = is_negative_impl(i.inner_impl()); if let Some(ref i) = i.inner_impl().trait_ { let i_display = format!("{:#}", i.print()); let out = Escape(&i_display); let encoded = small_url_encode(&format!("{:#}", i.print())); - let generated = format!("<a href=\"#impl-{}\">{}{}</a>", - encoded, - if is_negative_impl { "!" } else { "" }, - out); - if links.insert(generated.clone()) { - Some(generated) - } else { - None - } + let generated = format!( + "<a href=\"#impl-{}\">{}{}</a>", + encoded, + if is_negative_impl { "!" } else { "" }, + out + ); + if links.insert(generated.clone()) { Some(generated) } else { None } } else { None } @@ -3875,9 +4175,8 @@ fn sidebar_assoc_items(it: &clean::Item) -> String { ret.join("") }; - let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v - .iter() - .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic); + let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = + v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic); let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete .into_iter() .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some()); @@ -3887,20 +4186,26 @@ fn sidebar_assoc_items(it: &clean::Item) -> String { let blanket_format = format_impls(blanket_impl); if !concrete_format.is_empty() { - out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\ - Trait Implementations</a>"); + out.push_str( + "<a class=\"sidebar-title\" href=\"#implementations\">\ + Trait Implementations</a>", + ); out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format)); } if !synthetic_format.is_empty() { - out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\ - Auto Trait Implementations</a>"); + out.push_str( + "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\ + Auto Trait Implementations</a>", + ); out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format)); } if !blanket_format.is_empty() { - out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\ - Blanket Implementations</a>"); + out.push_str( + "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\ + Blanket Implementations</a>", + ); out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format)); } } @@ -3915,8 +4220,11 @@ fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) { if !fields.is_empty() { if let doctree::Plain = s.struct_type { - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ - <div class=\"sidebar-links\">{}</div>", fields)); + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ + <div class=\"sidebar-links\">{}</div>", + fields + )); } } @@ -3942,7 +4250,7 @@ fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> { } else { None } - }, + } _ => None, } } @@ -3954,107 +4262,108 @@ fn is_negative_impl(i: &clean::Impl) -> bool { fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) { let mut sidebar = String::new(); - let types = t.items - .iter() - .filter_map(|m| { - match m.name { - Some(ref name) if m.is_associated_type() => { - Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", - name=name)) - } - _ => None, - } - }) - .collect::<String>(); - let consts = t.items - .iter() - .filter_map(|m| { - match m.name { - Some(ref name) if m.is_associated_const() => { - Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", - name=name)) - } - _ => None, - } - }) - .collect::<String>(); - let mut required = t.items - .iter() - .filter_map(|m| { - match m.name { - Some(ref name) if m.is_ty_method() => { - Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", - name=name)) - } - _ => None, - } - }) - .collect::<Vec<String>>(); - let mut provided = t.items - .iter() - .filter_map(|m| { - match m.name { - Some(ref name) if m.is_method() => { - Some(format!("<a href=\"#method.{0}\">{0}</a>", name)) - } - _ => None, - } - }) - .collect::<Vec<String>>(); + let types = t + .items + .iter() + .filter_map(|m| match m.name { + Some(ref name) if m.is_associated_type() => { + Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name)) + } + _ => None, + }) + .collect::<String>(); + let consts = t + .items + .iter() + .filter_map(|m| match m.name { + Some(ref name) if m.is_associated_const() => { + Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name)) + } + _ => None, + }) + .collect::<String>(); + let mut required = t + .items + .iter() + .filter_map(|m| match m.name { + Some(ref name) if m.is_ty_method() => { + Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name)) + } + _ => None, + }) + .collect::<Vec<String>>(); + let mut provided = t + .items + .iter() + .filter_map(|m| match m.name { + Some(ref name) if m.is_method() => { + Some(format!("<a href=\"#method.{0}\">{0}</a>", name)) + } + _ => None, + }) + .collect::<Vec<String>>(); if !types.is_empty() { - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\ + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#associated-types\">\ Associated Types</a><div class=\"sidebar-links\">{}</div>", - types)); + types + )); } if !consts.is_empty() { - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\ + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#associated-const\">\ Associated Constants</a><div class=\"sidebar-links\">{}</div>", - consts)); + consts + )); } if !required.is_empty() { required.sort(); - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\ + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#required-methods\">\ Required Methods</a><div class=\"sidebar-links\">{}</div>", - required.join(""))); + required.join("") + )); } if !provided.is_empty() { provided.sort(); - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\ + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#provided-methods\">\ Provided Methods</a><div class=\"sidebar-links\">{}</div>", - provided.join(""))); + provided.join("") + )); } let c = cache(); if let Some(implementors) = c.implementors.get(&it.def_id) { - let mut res = implementors.iter() - .filter(|i| i.inner_impl().for_.def_id() - .map_or(false, |d| !c.paths.contains_key(&d))) - .filter_map(|i| { - match extract_for_impl_name(&i.impl_item) { - Some((ref name, ref id)) => { - Some(format!("<a href=\"#{}\">{}</a>", - id, - Escape(name))) - } - _ => None, - } - }) - .collect::<Vec<String>>(); + let mut res = implementors + .iter() + .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d))) + .filter_map(|i| match extract_for_impl_name(&i.impl_item) { + Some((ref name, ref id)) => { + Some(format!("<a href=\"#{}\">{}</a>", id, Escape(name))) + } + _ => None, + }) + .collect::<Vec<String>>(); if !res.is_empty() { res.sort(); - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\ + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#foreign-impls\">\ Implementations on Foreign Types</a><div \ class=\"sidebar-links\">{}</div>", - res.join(""))); + res.join("") + )); } } sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>"); if t.auto { - sidebar.push_str("<a class=\"sidebar-title\" \ - href=\"#synthetic-implementors\">Auto Implementors</a>"); + sidebar.push_str( + "<a class=\"sidebar-title\" \ + href=\"#synthetic-implementors\">Auto Implementors</a>", + ); } sidebar.push_str(&sidebar_assoc_items(it)); @@ -4079,18 +4388,18 @@ fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) { } fn get_struct_fields_name(fields: &[clean::Item]) -> String { - fields.iter() - .filter(|f| if let clean::StructFieldItem(..) = f.inner { - true - } else { - false - }) - .filter_map(|f| match f.name { - Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\ - {name}</a>", name=name)), - _ => None, - }) - .collect() + fields + .iter() + .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) + .filter_map(|f| match f.name { + Some(ref name) => Some(format!( + "<a href=\"#structfield.{name}\">\ + {name}</a>", + name = name + )), + _ => None, + }) + .collect() } fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) { @@ -4098,8 +4407,11 @@ fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) { let fields = get_struct_fields_name(&u.fields); if !fields.is_empty() { - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ - <div class=\"sidebar-links\">{}</div>", fields)); + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ + <div class=\"sidebar-links\">{}</div>", + fields + )); } sidebar.push_str(&sidebar_assoc_items(it)); @@ -4112,16 +4424,24 @@ fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) { fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) { let mut sidebar = String::new(); - let variants = e.variants.iter() - .filter_map(|v| match v.name { - Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\ - </a>", name = name)), - _ => None, - }) - .collect::<String>(); + let variants = e + .variants + .iter() + .filter_map(|v| match v.name { + Some(ref name) => Some(format!( + "<a href=\"#variant.{name}\">{name}\ + </a>", + name = name + )), + _ => None, + }) + .collect::<String>(); if !variants.is_empty() { - sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\ - <div class=\"sidebar-links\">{}</div>", variants)); + sidebar.push_str(&format!( + "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\ + <div class=\"sidebar-links\">{}</div>", + variants + )); } sidebar.push_str(&sidebar_assoc_items(it)); @@ -4133,58 +4453,77 @@ fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) { fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) { match *ty { - ItemType::ExternCrate | - ItemType::Import => ("reexports", "Re-exports"), - ItemType::Module => ("modules", "Modules"), - ItemType::Struct => ("structs", "Structs"), - ItemType::Union => ("unions", "Unions"), - ItemType::Enum => ("enums", "Enums"), - ItemType::Function => ("functions", "Functions"), - ItemType::Typedef => ("types", "Type Definitions"), - ItemType::Static => ("statics", "Statics"), - ItemType::Constant => ("constants", "Constants"), - ItemType::Trait => ("traits", "Traits"), - ItemType::Impl => ("impls", "Implementations"), - ItemType::TyMethod => ("tymethods", "Type Methods"), - ItemType::Method => ("methods", "Methods"), - ItemType::StructField => ("fields", "Struct Fields"), - ItemType::Variant => ("variants", "Variants"), - ItemType::Macro => ("macros", "Macros"), - ItemType::Primitive => ("primitives", "Primitive Types"), - ItemType::AssocType => ("associated-types", "Associated Types"), - ItemType::AssocConst => ("associated-consts", "Associated Constants"), - ItemType::ForeignType => ("foreign-types", "Foreign Types"), - ItemType::Keyword => ("keywords", "Keywords"), - ItemType::OpaqueTy => ("opaque-types", "Opaque Types"), - ItemType::ProcAttribute => ("attributes", "Attribute Macros"), - ItemType::ProcDerive => ("derives", "Derive Macros"), - ItemType::TraitAlias => ("trait-aliases", "Trait aliases"), + ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"), + ItemType::Module => ("modules", "Modules"), + ItemType::Struct => ("structs", "Structs"), + ItemType::Union => ("unions", "Unions"), + ItemType::Enum => ("enums", "Enums"), + ItemType::Function => ("functions", "Functions"), + ItemType::Typedef => ("types", "Type Definitions"), + ItemType::Static => ("statics", "Statics"), + ItemType::Constant => ("constants", "Constants"), + ItemType::Trait => ("traits", "Traits"), + ItemType::Impl => ("impls", "Implementations"), + ItemType::TyMethod => ("tymethods", "Type Methods"), + ItemType::Method => ("methods", "Methods"), + ItemType::StructField => ("fields", "Struct Fields"), + ItemType::Variant => ("variants", "Variants"), + ItemType::Macro => ("macros", "Macros"), + ItemType::Primitive => ("primitives", "Primitive Types"), + ItemType::AssocType => ("associated-types", "Associated Types"), + ItemType::AssocConst => ("associated-consts", "Associated Constants"), + ItemType::ForeignType => ("foreign-types", "Foreign Types"), + ItemType::Keyword => ("keywords", "Keywords"), + ItemType::OpaqueTy => ("opaque-types", "Opaque Types"), + ItemType::ProcAttribute => ("attributes", "Attribute Macros"), + ItemType::ProcDerive => ("derives", "Derive Macros"), + ItemType::TraitAlias => ("trait-aliases", "Trait aliases"), } } fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) { let mut sidebar = String::new(); - if items.iter().any(|it| it.type_() == ItemType::ExternCrate || - it.type_() == ItemType::Import) { - sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>", - id = "reexports", - name = "Re-exports")); + if items.iter().any(|it| it.type_() == ItemType::ExternCrate || it.type_() == ItemType::Import) + { + sidebar.push_str(&format!( + "<li><a href=\"#{id}\">{name}</a></li>", + id = "reexports", + name = "Re-exports" + )); } // ordering taken from item_module, reorder, where it prioritized elements in a certain order // to print its headings - for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct, - ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait, - ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl, - ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant, - ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType, - ItemType::Keyword] { + for &myty in &[ + ItemType::Primitive, + ItemType::Module, + ItemType::Macro, + ItemType::Struct, + ItemType::Enum, + ItemType::Constant, + ItemType::Static, + ItemType::Trait, + ItemType::Function, + ItemType::Typedef, + ItemType::Union, + ItemType::Impl, + ItemType::TyMethod, + ItemType::Method, + ItemType::StructField, + ItemType::Variant, + ItemType::AssocType, + ItemType::AssocConst, + ItemType::ForeignType, + ItemType::Keyword, + ] { if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) { let (short, name) = item_ty_to_strs(&myty); - sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>", - id = short, - name = name)); + sidebar.push_str(&format!( + "<li><a href=\"#{id}\">{name}</a></li>", + id = short, + name = name + )); } } @@ -4202,10 +4541,7 @@ fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) { fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) { wrap_into_docblock(w, |w| { - w.write_str(&highlight::render_with_highlighting(&t.source, - Some("macro"), - None, - None)) + w.write_str(&highlight::render_with_highlighting(&t.source, Some("macro"), None, None)) }); document(w, cx, it) } @@ -4282,33 +4618,32 @@ fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> { match fqp { Some(path) => { out.push(path.join("::")); - }, + } _ => {} }; - - }, + } clean::Type::Tuple(tys) => { work.extend(tys.into_iter()); - }, + } clean::Type::Slice(ty) => { work.push_back(*ty); } clean::Type::Array(ty, _) => { work.push_back(*ty); - }, + } clean::Type::RawPointer(_, ty) => { work.push_back(*ty); - }, + } clean::Type::BorrowedRef { type_, .. } => { work.push_back(*type_); - }, + } clean::Type::QPath { self_type, trait_, .. } => { work.push_back(*self_type); work.push_back(*trait_); - }, + } _ => {} } - }; + } out } |
