1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
29 use std::cell::{Cell, RefCell};
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
34 use std::fmt::{self, Formatter, Write as FmtWrite};
36 use std::fs::{self, File};
37 use std::io::prelude::*;
38 use std::io::{self, BufReader};
39 use std::path::{PathBuf, Path, Component};
45 use serialize::json::{ToJson, Json, as_json};
47 use syntax::edition::Edition;
48 use syntax::feature_gate::UnstableFeatures;
49 use syntax::print::pprust;
50 use syntax::source_map::FileName;
51 use syntax::symbol::{Symbol, sym};
52 use syntax_pos::hygiene::MacroKind;
53 use rustc::hir::def_id::DefId;
54 use rustc::middle::privacy::AccessLevels;
55 use rustc::middle::stability;
57 use rustc::util::nodemap::{FxHashMap, FxHashSet};
58 use rustc_data_structures::flock;
60 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
61 use crate::config::RenderOptions;
62 use crate::docfs::{DocFS, ErrorStorage, PathError};
64 use crate::html::escape::Escape;
65 use crate::html::format::{Buffer, PrintWithSpace, print_abi_with_space};
66 use crate::html::format::{print_generic_bounds, WhereClause, href, print_default_space};
67 use crate::html::format::{Function};
68 use crate::html::format::fmt_impl_for_trait_page;
69 use crate::html::item_type::ItemType;
70 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
71 use crate::html::{highlight, layout, static_files};
72 use crate::html::sources;
82 crate use cache::ExternalLocation::{self, *};
84 /// A pair of name and its optional document.
85 pub type NameDoc = (String, Option<String>);
87 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
88 crate::html::format::display_fn(move |f| {
89 if !v.ends_with("/") && !v.is_empty() {
100 pub error: io::Error,
103 impl error::Error for Error {
104 fn description(&self) -> &str {
105 self.error.description()
109 impl std::fmt::Display for Error {
110 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
111 let file = self.file.display().to_string();
113 write!(f, "{}", self.error)
115 write!(f, "\"{}\": {}", self.file.display(), self.error)
120 impl PathError for Error {
121 fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error {
123 file: path.as_ref().to_path_buf(),
129 macro_rules! try_none {
130 ($e:expr, $file:expr) => ({
134 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
140 macro_rules! try_err {
141 ($e:expr, $file:expr) => ({
144 Err(e) => return Err(Error::new(e, $file)),
149 /// Major driving force in all rustdoc rendering. This contains information
150 /// about where in the tree-like hierarchy rendering is occurring and controls
151 /// how the current page is being rendered.
153 /// It is intended that this context is a lightweight object which can be fairly
154 /// easily cloned because it is cloned per work-job (about once per item in the
158 /// Current hierarchy of components leading down to what's currently being
160 pub current: Vec<String>,
161 /// The current destination folder of where HTML artifacts should be placed.
162 /// This changes as the context descends into the module hierarchy.
164 /// A flag, which when `true`, will render pages which redirect to the
165 /// real location of an item. This is used to allow external links to
166 /// publicly reused items to redirect to the right location.
167 pub render_redirect_pages: bool,
168 /// The map used to ensure all generated 'id=' attributes are unique.
169 id_map: Rc<RefCell<IdMap>>,
170 pub shared: Arc<SharedContext>,
171 pub cache: Arc<Cache>,
174 crate struct SharedContext {
175 /// The path to the crate root source minus the file name.
176 /// Used for simplifying paths to the highlighted source code files.
177 pub src_root: PathBuf,
178 /// This describes the layout of each page, and is not modified after
179 /// creation of the context (contains info like the favicon and added html).
180 pub layout: layout::Layout,
181 /// This flag indicates whether `[src]` links should be generated or not. If
182 /// the source files are present in the html rendering, then this will be
184 pub include_sources: bool,
185 /// The local file sources we've emitted and their respective url-paths.
186 pub local_sources: FxHashMap<PathBuf, String>,
187 /// Whether the collapsed pass ran
189 /// The base-URL of the issue tracker for when an item has been tagged with
191 pub issue_tracker_base_url: Option<String>,
192 /// The directories that have already been created in this doc run. Used to reduce the number
193 /// of spurious `create_dir_all` calls.
194 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
195 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
196 /// should be ordered alphabetically or in order of appearance (in the source code).
197 pub sort_modules_alphabetically: bool,
198 /// Additional themes to be added to the generated docs.
199 pub themes: Vec<PathBuf>,
200 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
202 pub resource_suffix: String,
203 /// Optional path string to be used to load static files on output pages. If not set, uses
204 /// combinations of `../` to reach the documentation root.
205 pub static_root_path: Option<String>,
206 /// Option disabled by default to generate files used by RLS and some other tools.
207 pub generate_redirect_pages: bool,
208 /// The fs handle we are working with.
210 /// The default edition used to parse doctests.
211 pub edition: Edition,
212 pub codes: ErrorCodes,
213 playground: Option<markdown::Playground>,
217 fn path(&self, filename: &str) -> PathBuf {
218 // We use splitn vs Path::extension here because we might get a filename
219 // like `style.min.css` and we want to process that into
220 // `style-suffix.min.css`. Path::extension would just return `css`
221 // which would result in `style.min-suffix.css` which isn't what we
223 let mut iter = filename.splitn(2, '.');
224 let base = iter.next().unwrap();
225 let ext = iter.next().unwrap();
226 let filename = format!(
229 self.shared.resource_suffix,
232 self.dst.join(&filename)
237 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
238 let mut dirs = self.created_dirs.borrow_mut();
239 if !dirs.contains(dst) {
240 try_err!(self.fs.create_dir_all(dst), dst);
241 dirs.insert(dst.to_path_buf());
247 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
248 /// `collapsed_doc_value` of the given item.
249 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
251 item.collapsed_doc_value().map(|s| s.into())
253 item.doc_value().map(|s| s.into())
258 /// Metadata about implementations for a type or trait.
259 #[derive(Clone, Debug)]
261 pub impl_item: clean::Item,
265 fn inner_impl(&self) -> &clean::Impl {
266 match self.impl_item.inner {
267 clean::ImplItem(ref impl_) => impl_,
268 _ => panic!("non-impl item found in impl")
272 fn trait_did(&self) -> Option<DefId> {
273 self.inner_impl().trait_.def_id()
277 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
278 /// Later on moved into `CACHE_KEY`.
280 pub struct RenderInfo {
281 pub inlined: FxHashSet<DefId>,
282 pub external_paths: crate::core::ExternalPaths,
283 pub exact_paths: FxHashMap<DefId, Vec<String>>,
284 pub access_levels: AccessLevels<DefId>,
285 pub deref_trait_did: Option<DefId>,
286 pub deref_mut_trait_did: Option<DefId>,
287 pub owned_box_did: Option<DefId>,
290 // Helper structs for rendering items/sidebars and carrying along contextual
293 /// Struct representing one entry in the JS search index. These are all emitted
294 /// by hand to a large JS file at the end of cache-creation.
301 parent: Option<DefId>,
302 parent_idx: Option<usize>,
303 search_type: Option<IndexItemFunctionType>,
306 impl ToJson for IndexItem {
307 fn to_json(&self) -> Json {
308 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
310 let mut data = Vec::with_capacity(6);
311 data.push((self.ty as usize).to_json());
312 data.push(self.name.to_json());
313 data.push(self.path.to_json());
314 data.push(self.desc.to_json());
315 data.push(self.parent_idx.to_json());
316 data.push(self.search_type.to_json());
322 /// A type used for the search index.
325 name: Option<String>,
326 generics: Option<Vec<String>>,
329 impl ToJson for Type {
330 fn to_json(&self) -> Json {
333 let mut data = Vec::with_capacity(2);
334 data.push(name.to_json());
335 if let Some(ref generics) = self.generics {
336 data.push(generics.to_json());
345 /// Full type of functions/methods in the search index.
347 struct IndexItemFunctionType {
349 output: Option<Vec<Type>>,
352 impl ToJson for IndexItemFunctionType {
353 fn to_json(&self) -> Json {
354 // If we couldn't figure out a type, just write `null`.
355 let mut iter = self.inputs.iter();
356 if match self.output {
357 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
358 None => iter.any(|ref i| i.name.is_none()),
362 let mut data = Vec::with_capacity(2);
363 data.push(self.inputs.to_json());
364 if let Some(ref output) = self.output {
365 if output.len() > 1 {
366 data.push(output.to_json());
368 data.push(output[0].to_json());
376 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
377 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
379 pub fn initial_ids() -> Vec<String> {
391 "synthetic-implementors",
393 "synthetic-implementors-list",
397 ].iter().map(|id| (String::from(*id))).collect()
400 /// Generates the documentation for `crate` into the directory `dst`
401 pub fn run(mut krate: clean::Crate,
402 options: RenderOptions,
403 renderinfo: RenderInfo,
404 diag: &errors::Handler,
405 edition: Edition) -> Result<(), Error> {
406 // need to save a copy of the options for rendering the index page
407 let md_opts = options.clone();
413 sort_modules_alphabetically,
416 extern_html_root_urls,
419 generate_search_filter,
420 generate_redirect_pages,
424 let src_root = match krate.src {
425 FileName::Real(ref p) => match p.parent() {
426 Some(p) => p.to_path_buf(),
427 None => PathBuf::new(),
431 let mut errors = Arc::new(ErrorStorage::new());
432 // If user passed in `--playground-url` arg, we fill in crate name here
433 let mut playground = None;
434 if let Some(url) = playground_url {
435 playground = Some(markdown::Playground {
436 crate_name: Some(krate.name.clone()),
440 let mut layout = layout::Layout {
442 favicon: String::new(),
444 krate: krate.name.clone(),
445 css_file_extension: extension_css,
446 generate_search_filter,
448 let mut issue_tracker_base_url = None;
449 let mut include_sources = true;
451 // Crawl the crate attributes looking for attributes which control how we're
452 // going to emit HTML
453 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
454 for attr in attrs.lists(sym::doc) {
455 match (attr.name_or_empty(), attr.value_str()) {
456 (sym::html_favicon_url, Some(s)) => {
457 layout.favicon = s.to_string();
459 (sym::html_logo_url, Some(s)) => {
460 layout.logo = s.to_string();
462 (sym::html_playground_url, Some(s)) => {
463 playground = Some(markdown::Playground {
464 crate_name: Some(krate.name.clone()),
468 (sym::issue_tracker_base_url, Some(s)) => {
469 issue_tracker_base_url = Some(s.to_string());
471 (sym::html_no_source, None) if attr.is_word() => {
472 include_sources = false;
478 let mut scx = SharedContext {
479 collapsed: krate.collapsed,
482 local_sources: Default::default(),
483 issue_tracker_base_url,
485 created_dirs: Default::default(),
486 sort_modules_alphabetically,
490 generate_redirect_pages,
491 fs: DocFS::new(&errors),
493 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
498 scx.ensure_dir(&dst)?;
499 krate = sources::render(&dst, &mut scx, krate)?;
500 let (new_crate, index, cache) = Cache::from_krate(
502 &extern_html_root_urls,
507 let cache = Arc::new(cache);
508 let mut cx = Context {
511 render_redirect_pages: false,
512 id_map: Rc::new(RefCell::new(id_map)),
513 shared: Arc::new(scx),
514 cache: cache.clone(),
517 // Freeze the cache now that the index has been built. Put an Arc into TLS
518 // for future parallelization opportunities
519 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
520 CURRENT_DEPTH.with(|s| s.set(0));
522 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
523 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
524 write_shared(&cx, &krate, index, &md_opts, diag)?;
525 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
527 // And finally render the whole crate's documentation
528 let ret = cx.krate(krate);
529 let nb_errors = Arc::get_mut(&mut errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
532 } else if nb_errors > 0 {
533 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
541 krate: &clean::Crate,
542 search_index: String,
543 options: &RenderOptions,
544 diag: &errors::Handler,
545 ) -> Result<(), Error> {
546 // Write out the shared files. Note that these are shared among all rustdoc
547 // docs placed in the output directory, so this needs to be a synchronized
548 // operation with respect to all other rustdocs running around.
549 let lock_file = cx.dst.join(".lock");
550 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
552 // Add all the static files. These may already exist, but we just
553 // overwrite them anyway to make sure that they're fresh and up-to-date.
555 write_minify(&cx.shared.fs, cx.path("rustdoc.css"),
556 static_files::RUSTDOC_CSS,
557 options.enable_minification)?;
558 write_minify(&cx.shared.fs, cx.path("settings.css"),
559 static_files::SETTINGS_CSS,
560 options.enable_minification)?;
561 write_minify(&cx.shared.fs, cx.path("noscript.css"),
562 static_files::NOSCRIPT_CSS,
563 options.enable_minification)?;
565 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
566 // then we'll run over the "official" styles.
567 let mut themes: FxHashSet<String> = FxHashSet::default();
569 for entry in &cx.shared.themes {
570 let content = try_err!(fs::read(&entry), &entry);
571 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
572 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
573 cx.shared.fs.write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
574 themes.insert(theme.to_owned());
577 let write = |p, c| { cx.shared.fs.write(p, c) };
578 if (*cx.shared).layout.logo.is_empty() {
579 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
581 if (*cx.shared).layout.favicon.is_empty() {
582 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
584 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
585 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
586 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
587 write_minify(&cx.shared.fs,
588 cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification)?;
589 themes.insert("light".to_owned());
590 write_minify(&cx.shared.fs,
591 cx.path("dark.css"), static_files::themes::DARK, options.enable_minification)?;
592 themes.insert("dark".to_owned());
594 let mut themes: Vec<&String> = themes.iter().collect();
596 // To avoid theme switch latencies as much as possible, we put everything theme related
597 // at the beginning of the html files into another js file.
598 let theme_js = format!(
599 r#"var themes = document.getElementById("theme-choices");
600 var themePicker = document.getElementById("theme-picker");
602 function showThemeButtonState() {{
603 themes.style.display = "block";
604 themePicker.style.borderBottomRightRadius = "0";
605 themePicker.style.borderBottomLeftRadius = "0";
608 function hideThemeButtonState() {{
609 themes.style.display = "none";
610 themePicker.style.borderBottomRightRadius = "3px";
611 themePicker.style.borderBottomLeftRadius = "3px";
614 function switchThemeButtonState() {{
615 if (themes.style.display === "block") {{
616 hideThemeButtonState();
618 showThemeButtonState();
622 function handleThemeButtonsBlur(e) {{
623 var active = document.activeElement;
624 var related = e.relatedTarget;
626 if (active.id !== "themePicker" &&
627 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
629 (related.id !== "themePicker" &&
630 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
631 hideThemeButtonState();
635 themePicker.onclick = switchThemeButtonState;
636 themePicker.onblur = handleThemeButtonsBlur;
637 {}.forEach(function(item) {{
638 var but = document.createElement('button');
639 but.textContent = item;
640 but.onclick = function(el) {{
641 switchTheme(currentTheme, mainTheme, item, true);
643 but.onblur = handleThemeButtonsBlur;
644 themes.appendChild(but);
647 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
651 write_minify(&cx.shared.fs, cx.path("main.js"),
652 static_files::MAIN_JS,
653 options.enable_minification)?;
654 write_minify(&cx.shared.fs, cx.path("settings.js"),
655 static_files::SETTINGS_JS,
656 options.enable_minification)?;
657 if cx.shared.include_sources {
660 cx.path("source-script.js"),
661 static_files::sidebar::SOURCE_SCRIPT,
662 options.enable_minification)?;
668 cx.path("storage.js"),
669 &format!("var resourcesSuffix = \"{}\";{}",
670 cx.shared.resource_suffix,
671 static_files::STORAGE_JS),
672 options.enable_minification)?;
675 if let Some(ref css) = cx.shared.layout.css_file_extension {
676 let out = cx.path("theme.css");
677 let buffer = try_err!(fs::read_to_string(css), css);
678 if !options.enable_minification {
679 cx.shared.fs.write(&out, &buffer)?;
681 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
684 write_minify(&cx.shared.fs, cx.path("normalize.css"),
685 static_files::NORMALIZE_CSS,
686 options.enable_minification)?;
687 write(cx.dst.join("FiraSans-Regular.woff"),
688 static_files::fira_sans::REGULAR)?;
689 write(cx.dst.join("FiraSans-Medium.woff"),
690 static_files::fira_sans::MEDIUM)?;
691 write(cx.dst.join("FiraSans-LICENSE.txt"),
692 static_files::fira_sans::LICENSE)?;
693 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
694 static_files::source_serif_pro::REGULAR)?;
695 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
696 static_files::source_serif_pro::BOLD)?;
697 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
698 static_files::source_serif_pro::ITALIC)?;
699 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
700 static_files::source_serif_pro::LICENSE)?;
701 write(cx.dst.join("SourceCodePro-Regular.woff"),
702 static_files::source_code_pro::REGULAR)?;
703 write(cx.dst.join("SourceCodePro-Semibold.woff"),
704 static_files::source_code_pro::SEMIBOLD)?;
705 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
706 static_files::source_code_pro::LICENSE)?;
707 write(cx.dst.join("LICENSE-MIT.txt"),
708 static_files::LICENSE_MIT)?;
709 write(cx.dst.join("LICENSE-APACHE.txt"),
710 static_files::LICENSE_APACHE)?;
711 write(cx.dst.join("COPYRIGHT.txt"),
712 static_files::COPYRIGHT)?;
718 for_search_index: bool,
719 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
720 let mut ret = Vec::new();
721 let mut krates = Vec::new();
722 let mut variables = Vec::new();
725 for line in BufReader::new(File::open(path)?).lines() {
727 if for_search_index && line.starts_with("var R") {
728 variables.push(line.clone());
731 if !line.starts_with(key) {
734 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
737 ret.push(line.to_string());
738 krates.push(line[key.len() + 2..].split('"')
740 .map(|s| s.to_owned())
741 .unwrap_or_else(|| String::new()));
744 Ok((ret, krates, variables))
747 fn show_item(item: &IndexItem, krate: &str) -> String {
748 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
749 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
750 if let Some(p) = item.parent_idx {
751 format!(",'parent':{}", p)
757 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
759 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
760 let mut output = String::with_capacity(100);
761 for (alias, items) in &cx.cache.aliases {
762 if items.is_empty() {
765 output.push_str(&format!("\"{}\":[{}],",
768 .map(|v| show_item(v, &krate.name))
772 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
774 let mut v = Buffer::html();
775 writeln!(&mut v, "var ALIASES = {{}};");
776 for aliases in &all_aliases {
777 writeln!(&mut v, "{}", aliases);
779 cx.shared.fs.write(&dst, v.into_inner().into_bytes())?;
782 use std::ffi::OsString;
787 children: FxHashMap<OsString, Hierarchy>,
788 elems: FxHashSet<OsString>,
792 fn new(elem: OsString) -> Hierarchy {
795 children: FxHashMap::default(),
796 elems: FxHashSet::default(),
800 fn to_json_string(&self) -> String {
801 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
802 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
803 let mut files = self.elems.iter()
804 .map(|s| format!("\"{}\"",
806 .expect("invalid osstring conversion")))
807 .collect::<Vec<_>>();
808 files.sort_unstable_by(|a, b| a.cmp(b));
809 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
810 let dirs = if subs.is_empty() {
813 format!(",\"dirs\":[{}]", subs)
815 let files = files.join(",");
816 let files = if files.is_empty() {
819 format!(",\"files\":[{}]", files)
821 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
822 name=self.elem.to_str().expect("invalid osstring conversion"),
828 if cx.shared.include_sources {
829 let mut hierarchy = Hierarchy::new(OsString::new());
830 for source in cx.shared.local_sources.iter()
831 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
833 let mut h = &mut hierarchy;
834 let mut elems = source.components()
837 Component::Normal(s) => Some(s.to_owned()),
843 let cur_elem = elems.next().expect("empty file path");
844 if elems.peek().is_none() {
845 h.elems.insert(cur_elem);
848 let e = cur_elem.clone();
849 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
850 h = h.children.get_mut(&cur_elem).expect("not found child");
855 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
856 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
859 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
861 hierarchy.to_json_string()));
863 let v = format!("var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
864 all_sources.join("\n"));
865 cx.shared.fs.write(&dst, v.as_bytes())?;
868 // Update the search index
869 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
870 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
874 all_indexes.push(search_index);
876 // Sort the indexes by crate so the file will be generated identically even
877 // with rustdoc running in parallel.
880 let mut v = String::from("var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={};\n");
881 v.push_str(&minify_replacer(
882 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
883 options.enable_minification));
884 // "addSearchOptions" has to be called first so the crate filtering can be set before the
885 // search might start (if it's set into the URL for example).
886 v.push_str("addSearchOptions(searchIndex);initSearch(searchIndex);");
887 cx.shared.fs.write(&dst, &v)?;
889 if options.enable_index_page {
890 if let Some(index_page) = options.index_page.clone() {
891 let mut md_opts = options.clone();
892 md_opts.output = cx.dst.clone();
893 md_opts.external_html = (*cx.shared).layout.external_html.clone();
895 crate::markdown::render(index_page, md_opts, diag, cx.shared.edition);
897 let dst = cx.dst.join("index.html");
898 let page = layout::Page {
899 title: "Index of crates",
902 static_root_path: cx.shared.static_root_path.as_deref(),
903 description: "List of crates",
904 keywords: BASIC_KEYWORDS,
905 resource_suffix: &cx.shared.resource_suffix,
907 static_extra_scripts: &[],
909 krates.push(krate.name.clone());
913 let content = format!(
915 <span class='in-band'>List of all crates</span>\
916 </h1><ul class='mod'>{}</ul>",
920 format!("<li><a href=\"{}index.html\">{}</li>",
921 ensure_trailing_slash(s), s)
923 .collect::<String>());
924 let v = layout::render(&cx.shared.layout,
927 cx.shared.fs.write(&dst, v.as_bytes())?;
931 // Update the list of all implementors for traits
932 let dst = cx.dst.join("implementors");
933 for (&did, imps) in &cx.cache.implementors {
934 // Private modules can leak through to this phase of rustdoc, which
935 // could contain implementations for otherwise private types. In some
936 // rare cases we could find an implementation for an item which wasn't
937 // indexed, so we just skip this step in that case.
939 // FIXME: this is a vague explanation for why this can't be a `get`, in
940 // theory it should be...
941 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
943 None => match cx.cache.external_paths.get(&did) {
949 let mut have_impls = false;
950 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
952 // If the trait and implementation are in the same crate, then
953 // there's no need to emit information about it (there's inlining
954 // going on). If they're in different crates then the crate defining
955 // the trait will be interested in our implementation.
956 if imp.impl_item.def_id.krate == did.krate { continue }
957 // If the implementation is from another crate then that crate
959 if !imp.impl_item.def_id.is_local() { continue }
961 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
962 as_json(&imp.inner_impl().print().to_string()),
963 imp.inner_impl().synthetic,
964 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
966 implementors.push_str("];");
968 // Only create a js file if we have impls to add to it. If the trait is
969 // documented locally though we always create the file to avoid dead
971 if !have_impls && !cx.cache.paths.contains_key(&did) {
975 let mut mydst = dst.clone();
976 for part in &remote_path[..remote_path.len() - 1] {
979 cx.shared.ensure_dir(&mydst)?;
980 mydst.push(&format!("{}.{}.js",
982 remote_path[remote_path.len() - 1]));
984 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
987 all_implementors.push(implementors);
988 // Sort the implementors by crate so the file will be generated
989 // identically even with rustdoc running in parallel.
990 all_implementors.sort();
992 let mut v = String::from("(function() {var implementors = {};\n");
993 for implementor in &all_implementors {
994 writeln!(v, "{}", *implementor).unwrap();
997 if (window.register_implementors) {
998 window.register_implementors(implementors);
1000 window.pending_implementors = implementors;
1004 cx.shared.fs.write(&mydst, &v)?;
1009 fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool
1010 ) -> Result<(), Error> {
1011 if enable_minification {
1012 if dst.extension() == Some(&OsStr::new("css")) {
1013 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1014 fs.write(dst, res.as_bytes())
1016 fs.write(dst, minifier::js::minify(contents).as_bytes())
1019 fs.write(dst, contents.as_bytes())
1025 enable_minification: bool,
1027 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1029 if enable_minification {
1030 let tokens: Tokens<'_> = simple_minify(contents)
1032 .filter(|(f, next)| {
1033 // We keep backlines.
1034 minifier::js::clean_token_except(f, next, &|c: &Token<'_>| {
1035 c.get_char() != Some(ReservedChar::Backline)
1039 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1041 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1042 Token::String(s) => {
1043 let s = &s[1..s.len() -1]; // The quotes are included
1045 Some(Token::Other("E"))
1046 } else if s == "t" {
1047 Some(Token::Other("T"))
1048 } else if s == "u" {
1049 Some(Token::Other("U"))
1058 .collect::<Vec<_>>()
1060 let o = tokens.apply(|f| {
1061 // We add a backline after the newly created variables.
1062 minifier::js::aggregate_strings_into_array_with_separation_filter(
1065 Token::Char(ReservedChar::Backline),
1066 // This closure prevents crates' names from being aggregated.
1068 // The point here is to check if the string is preceded by '[' and
1069 // "searchIndex". If so, it means this is a crate name and that it
1070 // shouldn't be aggregated.
1073 !tokens[pos - 1].eq_char(ReservedChar::OpenBracket) ||
1074 tokens[pos - 2].get_other() != Some("searchIndex")
1081 format!("{}\n", contents)
1085 #[derive(Debug, Eq, PartialEq, Hash)]
1092 fn new(mut url: String, name: String) -> ItemEntry {
1093 while url.starts_with('/') {
1104 crate fn print(&self) -> impl fmt::Display + '_ {
1105 crate::html::format::display_fn(move |f| {
1106 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1111 impl PartialOrd for ItemEntry {
1112 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1113 Some(self.cmp(other))
1117 impl Ord for ItemEntry {
1118 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1119 self.name.cmp(&other.name)
1125 structs: FxHashSet<ItemEntry>,
1126 enums: FxHashSet<ItemEntry>,
1127 unions: FxHashSet<ItemEntry>,
1128 primitives: FxHashSet<ItemEntry>,
1129 traits: FxHashSet<ItemEntry>,
1130 macros: FxHashSet<ItemEntry>,
1131 functions: FxHashSet<ItemEntry>,
1132 typedefs: FxHashSet<ItemEntry>,
1133 opaque_tys: FxHashSet<ItemEntry>,
1134 statics: FxHashSet<ItemEntry>,
1135 constants: FxHashSet<ItemEntry>,
1136 keywords: FxHashSet<ItemEntry>,
1137 attributes: FxHashSet<ItemEntry>,
1138 derives: FxHashSet<ItemEntry>,
1139 trait_aliases: FxHashSet<ItemEntry>,
1143 fn new() -> AllTypes {
1144 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1146 structs: new_set(100),
1147 enums: new_set(100),
1148 unions: new_set(100),
1149 primitives: new_set(26),
1150 traits: new_set(100),
1151 macros: new_set(100),
1152 functions: new_set(100),
1153 typedefs: new_set(100),
1154 opaque_tys: new_set(100),
1155 statics: new_set(100),
1156 constants: new_set(100),
1157 keywords: new_set(100),
1158 attributes: new_set(100),
1159 derives: new_set(100),
1160 trait_aliases: new_set(100),
1164 fn append(&mut self, item_name: String, item_type: &ItemType) {
1165 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1166 if let Some(name) = url.pop() {
1167 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1169 let name = url.join("::");
1171 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1172 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1173 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1174 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1175 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1176 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1177 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1178 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1179 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1180 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1181 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1182 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1183 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1184 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1191 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1193 let mut e: Vec<&ItemEntry> = e.iter().collect();
1195 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1199 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>());
1204 fn print(self, f: &mut Buffer) {
1207 <span class='out-of-band'>\
1208 <span id='render-detail'>\
1209 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1210 [<span class='inner'>−</span>]\
1214 <span class='in-band'>List of all items</span>\
1216 print_entries(f, &self.structs, "Structs", "structs");
1217 print_entries(f, &self.enums, "Enums", "enums");
1218 print_entries(f, &self.unions, "Unions", "unions");
1219 print_entries(f, &self.primitives, "Primitives", "primitives");
1220 print_entries(f, &self.traits, "Traits", "traits");
1221 print_entries(f, &self.macros, "Macros", "macros");
1222 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1223 print_entries(f, &self.derives, "Derive Macros", "derives");
1224 print_entries(f, &self.functions, "Functions", "functions");
1225 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1226 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1227 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1228 print_entries(f, &self.statics, "Statics", "statics");
1229 print_entries(f, &self.constants, "Constants", "constants")
1236 description: &'static str,
1237 sub_settings: Vec<Setting>,
1240 js_data_name: &'static str,
1241 description: &'static str,
1242 default_value: bool,
1247 fn display(&self) -> String {
1249 Setting::Section { ref description, ref sub_settings } => {
1251 "<div class='setting-line'>\
1252 <div class='title'>{}</div>\
1253 <div class='sub-settings'>{}</div>
1256 sub_settings.iter().map(|s| s.display()).collect::<String>()
1259 Setting::Entry { ref js_data_name, ref description, ref default_value } => {
1261 "<div class='setting-line'>\
1262 <label class='toggle'>\
1263 <input type='checkbox' id='{}' {}>\
1264 <span class='slider'></span>\
1269 if *default_value { " checked" } else { "" },
1277 impl From<(&'static str, &'static str, bool)> for Setting {
1278 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1280 js_data_name: values.0,
1281 description: values.1,
1282 default_value: values.2,
1287 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1288 fn from(values: (&'static str, Vec<T>)) -> Setting {
1290 description: values.0,
1291 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1296 fn settings(root_path: &str, suffix: &str) -> String {
1297 // (id, explanation, default value)
1298 let settings: &[Setting] = &[
1299 ("Auto-hide item declarations", vec![
1300 ("auto-hide-struct", "Auto-hide structs declaration", true),
1301 ("auto-hide-enum", "Auto-hide enums declaration", false),
1302 ("auto-hide-union", "Auto-hide unions declaration", true),
1303 ("auto-hide-trait", "Auto-hide traits declaration", true),
1304 ("auto-hide-macro", "Auto-hide macros declaration", false),
1306 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1307 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1308 ("auto-hide-trait-implementations", "Auto-hide trait implementations documentation",
1310 ("go-to-only-result", "Directly go to item in search if there is only one result",
1312 ("line-numbers", "Show line numbers on code examples", false).into(),
1313 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1317 <span class='in-band'>Rustdoc settings</span>\
1319 <div class='settings'>{}</div>\
1320 <script src='{}settings{}.js'></script>",
1321 settings.iter().map(|s| s.display()).collect::<String>(),
1327 fn derive_id(&self, id: String) -> String {
1328 let mut map = self.id_map.borrow_mut();
1332 /// String representation of how to get back to the root path of the 'doc/'
1333 /// folder in terms of a relative URL.
1334 fn root_path(&self) -> String {
1335 "../".repeat(self.current.len())
1338 /// Main method for rendering a crate.
1340 /// This currently isn't parallelized, but it'd be pretty easy to add
1341 /// parallelization to this function.
1342 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1343 let mut item = match krate.module.take() {
1345 None => return Ok(()),
1347 let final_file = self.dst.join(&krate.name)
1349 let settings_file = self.dst.join("settings.html");
1351 let crate_name = krate.name.clone();
1352 item.name = Some(krate.name);
1354 let mut all = AllTypes::new();
1357 // Render the crate documentation
1358 let mut work = vec![(self.clone(), item)];
1360 while let Some((mut cx, item)) = work.pop() {
1361 cx.item(item, &mut all, |cx, item| {
1362 work.push((cx.clone(), item))
1367 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1368 if !root_path.ends_with('/') {
1369 root_path.push('/');
1371 let mut page = layout::Page {
1372 title: "List of all items in this crate",
1375 static_root_path: self.shared.static_root_path.as_deref(),
1376 description: "List of all items in this crate",
1377 keywords: BASIC_KEYWORDS,
1378 resource_suffix: &self.shared.resource_suffix,
1380 static_extra_scripts: &[],
1382 let sidebar = if let Some(ref version) = self.cache.crate_version {
1383 format!("<p class='location'>Crate {}</p>\
1384 <div class='block version'>\
1387 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1388 crate_name, version)
1392 let v = layout::render(&self.shared.layout,
1393 &page, sidebar, |buf: &mut Buffer| all.print(buf),
1394 &self.shared.themes);
1395 self.shared.fs.write(&final_file, v.as_bytes())?;
1397 // Generating settings page.
1398 page.title = "Rustdoc settings";
1399 page.description = "Settings of Rustdoc";
1400 page.root_path = "./";
1402 let mut themes = self.shared.themes.clone();
1403 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1404 themes.push(PathBuf::from("settings.css"));
1405 let v = layout::render(
1406 &self.shared.layout,
1407 &page, sidebar, settings(
1408 self.shared.static_root_path.as_deref().unwrap_or("./"),
1409 &self.shared.resource_suffix
1412 self.shared.fs.write(&settings_file, v.as_bytes())?;
1417 fn render_item(&self,
1419 pushname: bool) -> String {
1420 // A little unfortunate that this is done like this, but it sure
1421 // does make formatting *a lot* nicer.
1422 CURRENT_DEPTH.with(|slot| {
1423 slot.set(self.current.len());
1426 let mut title = if it.is_primitive() || it.is_keyword() {
1427 // No need to include the namespace for primitive types and keywords
1430 self.current.join("::")
1433 if !title.is_empty() {
1434 title.push_str("::");
1436 title.push_str(it.name.as_ref().unwrap());
1438 title.push_str(" - Rust");
1439 let tyname = it.type_();
1440 let desc = if it.is_crate() {
1441 format!("API documentation for the Rust `{}` crate.",
1442 self.shared.layout.krate)
1444 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1445 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1447 let keywords = make_item_keywords(it);
1448 let page = layout::Page {
1449 css_class: tyname.as_str(),
1450 root_path: &self.root_path(),
1451 static_root_path: self.shared.static_root_path.as_deref(),
1454 keywords: &keywords,
1455 resource_suffix: &self.shared.resource_suffix,
1457 static_extra_scripts: &[],
1461 self.id_map.borrow_mut().reset();
1462 self.id_map.borrow_mut().populate(initial_ids());
1465 if !self.render_redirect_pages {
1466 layout::render(&self.shared.layout, &page,
1467 |buf: &mut _| print_sidebar(self, it, buf),
1468 |buf: &mut _| print_item(self, it, buf),
1469 &self.shared.themes)
1471 let mut url = self.root_path();
1472 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1473 for name in &names[..names.len() - 1] {
1477 url.push_str(&item_path(ty, names.last().unwrap()));
1478 layout::redirect(&url)
1485 /// Non-parallelized version of rendering an item. This will take the input
1486 /// item, render its contents, and then invoke the specified closure with
1487 /// all sub-items which need to be rendered.
1489 /// The rendering driver uses this closure to queue up more work.
1490 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1491 where F: FnMut(&mut Context, clean::Item),
1493 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
1494 // if they contain impls for public types. These modules can also
1495 // contain items such as publicly re-exported structures.
1497 // External crates will provide links to these structures, so
1498 // these modules are recursed into, but not rendered normally
1499 // (a flag on the context).
1500 if !self.render_redirect_pages {
1501 self.render_redirect_pages = item.is_stripped();
1505 // modules are special because they add a namespace. We also need to
1506 // recurse into the items of the module as well.
1507 let name = item.name.as_ref().unwrap().to_string();
1508 let scx = &self.shared;
1509 if name.is_empty() {
1510 panic!("Unexpected empty destination: {:?}", self.current);
1512 let prev = self.dst.clone();
1513 self.dst.push(&name);
1514 self.current.push(name);
1516 info!("Recursing into {}", self.dst.display());
1518 let buf = self.render_item(&item, false);
1519 // buf will be empty if the module is stripped and there is no redirect for it
1520 if !buf.is_empty() {
1521 self.shared.ensure_dir(&self.dst)?;
1522 let joint_dst = self.dst.join("index.html");
1523 scx.fs.write(&joint_dst, buf.as_bytes())?;
1526 let m = match item.inner {
1527 clean::StrippedItem(box clean::ModuleItem(m)) |
1528 clean::ModuleItem(m) => m,
1532 // Render sidebar-items.js used throughout this module.
1533 if !self.render_redirect_pages {
1534 let items = self.build_sidebar_items(&m);
1535 let js_dst = self.dst.join("sidebar-items.js");
1536 let v = format!("initSidebarItems({});", as_json(&items));
1537 scx.fs.write(&js_dst, &v)?;
1540 for item in m.items {
1544 info!("Recursed; leaving {}", self.dst.display());
1546 // Go back to where we were at
1548 self.current.pop().unwrap();
1549 } else if item.name.is_some() {
1550 let buf = self.render_item(&item, true);
1551 // buf will be empty if the item is stripped and there is no redirect for it
1552 if !buf.is_empty() {
1553 let name = item.name.as_ref().unwrap();
1554 let item_type = item.type_();
1555 let file_name = &item_path(item_type, name);
1556 self.shared.ensure_dir(&self.dst)?;
1557 let joint_dst = self.dst.join(file_name);
1558 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
1560 if !self.render_redirect_pages {
1561 all.append(full_path(self, &item), &item_type);
1563 if self.shared.generate_redirect_pages {
1564 // Redirect from a sane URL using the namespace to Rustdoc's
1565 // URL for the page.
1566 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1567 let redir_dst = self.dst.join(redir_name);
1568 let v = layout::redirect(file_name);
1569 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1571 // If the item is a macro, redirect from the old macro URL (with !)
1572 // to the new one (without).
1573 if item_type == ItemType::Macro {
1574 let redir_name = format!("{}.{}!.html", item_type, name);
1575 let redir_dst = self.dst.join(redir_name);
1576 let v = layout::redirect(file_name);
1577 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1584 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1585 // BTreeMap instead of HashMap to get a sorted output
1586 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1587 for item in &m.items {
1588 if item.is_stripped() { continue }
1590 let short = item.type_();
1591 let myname = match item.name {
1593 Some(ref s) => s.to_string(),
1595 let short = short.to_string();
1596 map.entry(short).or_default()
1597 .push((myname, Some(plain_summary_line(item.doc_value()))));
1600 if self.shared.sort_modules_alphabetically {
1601 for (_, items) in &mut map {
1610 /// Generates a url appropriate for an `href` attribute back to the source of
1613 /// The url generated, when clicked, will redirect the browser back to the
1614 /// original source code.
1616 /// If `None` is returned, then a source link couldn't be generated. This
1617 /// may happen, for example, with externally inlined items where the source
1618 /// of their crate documentation isn't known.
1619 fn src_href(&self, item: &clean::Item) -> Option<String> {
1620 let mut root = self.root_path();
1622 let mut path = String::new();
1624 // We can safely ignore macros from other libraries
1625 let file = match item.source.filename {
1626 FileName::Real(ref path) => path,
1630 let (krate, path) = if item.def_id.is_local() {
1631 if let Some(path) = self.shared.local_sources.get(file) {
1632 (&self.shared.layout.krate, path)
1637 let (krate, src_root) = match *self.cache.extern_locations.get(&item.def_id.krate)? {
1638 (ref name, ref src, Local) => (name, src),
1639 (ref name, ref src, Remote(ref s)) => {
1640 root = s.to_string();
1643 (_, _, Unknown) => return None,
1646 sources::clean_path(&src_root, file, false, |component| {
1647 path.push_str(&component.to_string_lossy());
1650 let mut fname = file.file_name().expect("source has no filename")
1652 fname.push(".html");
1653 path.push_str(&fname.to_string_lossy());
1657 let lines = if item.source.loline == item.source.hiline {
1658 item.source.loline.to_string()
1660 format!("{}-{}", item.source.loline, item.source.hiline)
1662 Some(format!("{root}src/{krate}/{path}#{lines}",
1663 root = Escape(&root),
1670 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1671 where F: FnOnce(&mut Buffer)
1673 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1678 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) {
1679 debug_assert!(!item.is_stripped());
1680 // Write the breadcrumb trail header for the top
1681 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1682 if let Some(version) = item.stable_since() {
1683 write!(buf, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1687 "<span id='render-detail'>\
1688 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1689 title=\"collapse all docs\">\
1690 [<span class='inner'>−</span>]\
1696 // When this item is part of a `pub use` in a downstream crate, the
1697 // [src] link in the downstream documentation will actually come back to
1698 // this page, and this link will be auto-clicked. The `id` attribute is
1699 // used to find the link to auto-click.
1700 if cx.shared.include_sources && !item.is_primitive() {
1701 if let Some(l) = cx.src_href(item) {
1702 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1703 l, "goto source code");
1707 write!(buf, "</span>"); // out-of-band
1708 write!(buf, "<span class='in-band'>");
1709 let name = match item.inner {
1710 clean::ModuleItem(ref m) => if m.is_crate {
1715 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1716 clean::TraitItem(..) => "Trait ",
1717 clean::StructItem(..) => "Struct ",
1718 clean::UnionItem(..) => "Union ",
1719 clean::EnumItem(..) => "Enum ",
1720 clean::TypedefItem(..) => "Type Definition ",
1721 clean::MacroItem(..) => "Macro ",
1722 clean::ProcMacroItem(ref mac) => match mac.kind {
1723 MacroKind::Bang => "Macro ",
1724 MacroKind::Attr => "Attribute Macro ",
1725 MacroKind::Derive => "Derive Macro ",
1727 clean::PrimitiveItem(..) => "Primitive Type ",
1728 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1729 clean::ConstantItem(..) => "Constant ",
1730 clean::ForeignTypeItem => "Foreign Type ",
1731 clean::KeywordItem(..) => "Keyword ",
1732 clean::OpaqueTyItem(..) => "Opaque Type ",
1733 clean::TraitAliasItem(..) => "Trait Alias ",
1735 // We don't generate pages for any other type.
1739 buf.write_str(name);
1740 if !item.is_primitive() && !item.is_keyword() {
1741 let cur = &cx.current;
1742 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1743 for (i, component) in cur.iter().enumerate().take(amt) {
1744 write!(buf, "<a href='{}index.html'>{}</a>::<wbr>",
1745 "../".repeat(cur.len() - i - 1),
1749 write!(buf, "<a class=\"{}\" href=''>{}</a>",
1750 item.type_(), item.name.as_ref().unwrap());
1752 write!(buf, "</span></h1>"); // in-band
1755 clean::ModuleItem(ref m) =>
1756 item_module(buf, cx, item, &m.items),
1757 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1758 item_function(buf, cx, item, f),
1759 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1760 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1761 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1762 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1763 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1764 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1765 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1766 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1767 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1768 item_static(buf, cx, item, i),
1769 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1770 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1771 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1772 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e),
1773 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1775 // We don't generate pages for any other type.
1781 fn item_path(ty: ItemType, name: &str) -> String {
1783 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1784 _ => format!("{}.{}.html", ty, name),
1788 fn full_path(cx: &Context, item: &clean::Item) -> String {
1789 let mut s = cx.current.join("::");
1791 s.push_str(item.name.as_ref().unwrap());
1796 fn plain_summary_line(s: Option<&str>) -> String {
1797 let s = s.unwrap_or("");
1798 // This essentially gets the first paragraph of text in one line.
1799 let mut line = s.lines()
1800 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1801 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1802 .fold(String::new(), |mut acc, line| {
1807 // remove final whitespace
1809 markdown::plain_summary_line(&line[..])
1812 fn shorten(s: String) -> String {
1813 if s.chars().count() > 60 {
1815 let mut ret = s.split_whitespace()
1817 // + 1 for the added character after the word.
1818 len += p.chars().count() + 1;
1821 .collect::<Vec<_>>()
1830 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1831 if let Some(ref name) = item.name {
1832 info!("Documenting {}", name);
1834 document_stability(w, cx, item, false);
1835 document_full(w, item, cx, "", false);
1838 /// Render md_text as markdown.
1843 links: Vec<(String, String)>,
1847 let mut ids = cx.id_map.borrow_mut();
1848 write!(w, "<div class='docblock{}'>{}{}</div>",
1849 if is_hidden { " hidden" } else { "" },
1851 Markdown(md_text, &links, &mut ids,
1852 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string())
1859 link: AssocItemLink<'_>,
1863 if let Some(s) = item.doc_value() {
1864 let markdown = if s.contains('\n') {
1865 format!("{} [Read more]({})",
1866 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1868 plain_summary_line(Some(s))
1870 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1871 } else if !prefix.is_empty() {
1872 write!(w, "<div class='docblock{}'>{}</div>",
1873 if is_hidden { " hidden" } else { "" },
1878 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1879 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1880 debug!("Doc block: =====\n{}\n=====", s);
1881 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1882 } else if !prefix.is_empty() {
1883 write!(w, "<div class='docblock{}'>{}</div>",
1884 if is_hidden { " hidden" } else { "" },
1889 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1890 let stabilities = short_stability(item, cx);
1891 if !stabilities.is_empty() {
1892 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1893 for stability in stabilities {
1894 write!(w, "{}", stability);
1896 write!(w, "</div>");
1900 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1901 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1904 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1905 if item.is_non_exhaustive() {
1906 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1907 if item.is_struct() {
1909 } else if item.is_enum() {
1911 } else if item.is_variant() {
1918 if item.is_struct() {
1919 write!(w, "Non-exhaustive structs could have additional fields added in future. \
1920 Therefore, non-exhaustive structs cannot be constructed in external crates \
1921 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1922 matched against without a wildcard <code>..</code>; and \
1923 struct update syntax will not work.");
1924 } else if item.is_enum() {
1925 write!(w, "Non-exhaustive enums could have additional variants added in future. \
1926 Therefore, when matching against variants of non-exhaustive enums, an \
1927 extra wildcard arm must be added to account for any future variants.");
1928 } else if item.is_variant() {
1929 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
1930 Therefore, non-exhaustive enum variants cannot be constructed in external \
1931 crates and cannot be matched against.");
1933 write!(w, "This type will require a wildcard arm in any match statements or \
1937 write!(w, "</div>");
1941 fn name_key(name: &str) -> (&str, u64, usize) {
1942 let end = name.bytes()
1943 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1945 // find number at end
1946 let split = name[0..end].bytes()
1947 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
1949 // count leading zeroes
1951 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1953 // sort leading zeroes last
1954 let num_zeroes = after_zeroes - split;
1956 match name[split..end].parse() {
1957 Ok(n) => (&name[..split], n, num_zeroes),
1958 Err(_) => (name, 0, num_zeroes),
1962 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1963 document(w, cx, item);
1965 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1967 // the order of item types in the listing
1968 fn reorder(ty: ItemType) -> u8 {
1970 ItemType::ExternCrate => 0,
1971 ItemType::Import => 1,
1972 ItemType::Primitive => 2,
1973 ItemType::Module => 3,
1974 ItemType::Macro => 4,
1975 ItemType::Struct => 5,
1976 ItemType::Enum => 6,
1977 ItemType::Constant => 7,
1978 ItemType::Static => 8,
1979 ItemType::Trait => 9,
1980 ItemType::Function => 10,
1981 ItemType::Typedef => 12,
1982 ItemType::Union => 13,
1987 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1988 let ty1 = i1.type_();
1989 let ty2 = i2.type_();
1991 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1993 let s1 = i1.stability.as_ref().map(|s| s.level);
1994 let s2 = i2.stability.as_ref().map(|s| s.level);
1996 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1997 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2000 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2001 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2002 name_key(lhs).cmp(&name_key(rhs))
2005 if cx.shared.sort_modules_alphabetically {
2006 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2008 // This call is to remove re-export duplicates in cases such as:
2013 // pub trait Double { fn foo(); }
2017 // pub use foo::bar::*;
2021 // `Double` will appear twice in the generated docs.
2023 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2024 // can be identical even if the elements are different (mostly in imports).
2025 // So in case this is an import, we keep everything by adding a "unique id"
2026 // (which is the position in the vector).
2027 indices.dedup_by_key(|i| (items[*i].def_id,
2028 if items[*i].name.as_ref().is_some() {
2029 Some(full_path(cx, &items[*i]))
2034 if items[*i].is_import() {
2040 debug!("{:?}", indices);
2041 let mut curty = None;
2042 for &idx in &indices {
2043 let myitem = &items[idx];
2044 if myitem.is_stripped() {
2048 let myty = Some(myitem.type_());
2049 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2050 // Put `extern crate` and `use` re-exports in the same section.
2052 } else if myty != curty {
2053 if curty.is_some() {
2054 write!(w, "</table>");
2057 let (short, name) = item_ty_to_strs(&myty.unwrap());
2058 write!(w, "<h2 id='{id}' class='section-header'>\
2059 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2060 id = cx.derive_id(short.to_owned()), name = name);
2063 match myitem.inner {
2064 clean::ExternCrateItem(ref name, ref src) => {
2065 use crate::html::format::anchor;
2069 write!(w, "<tr><td><code>{}extern crate {} as {};",
2070 myitem.visibility.print_with_space(),
2071 anchor(myitem.def_id, src),
2075 write!(w, "<tr><td><code>{}extern crate {};",
2076 myitem.visibility.print_with_space(),
2077 anchor(myitem.def_id, name))
2080 write!(w, "</code></td></tr>");
2083 clean::ImportItem(ref import) => {
2084 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2085 myitem.visibility.print_with_space(), import.print());
2089 if myitem.name.is_none() { continue }
2091 let unsafety_flag = match myitem.inner {
2092 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2093 if func.header.unsafety == hir::Unsafety::Unsafe => {
2094 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2099 let stab = myitem.stability_class();
2100 let add = if stab.is_some() {
2106 let doc_value = myitem.doc_value().unwrap_or("");
2108 <tr class='{stab}{add}module-item'>\
2109 <td><a class=\"{class}\" href=\"{href}\" \
2110 title='{title}'>{name}</a>{unsafety_flag}</td>\
2111 <td class='docblock-short'>{stab_tags}{docs}</td>\
2113 name = *myitem.name.as_ref().unwrap(),
2114 stab_tags = stability_tags(myitem),
2115 docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(),
2116 class = myitem.type_(),
2118 stab = stab.unwrap_or_else(|| String::new()),
2119 unsafety_flag = unsafety_flag,
2120 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2121 title = [full_path(cx, myitem), myitem.type_().to_string()]
2123 .filter_map(|s| if !s.is_empty() {
2128 .collect::<Vec<_>>()
2135 if curty.is_some() {
2136 write!(w, "</table>");
2140 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2142 fn stability_tags(item: &clean::Item) -> String {
2143 let mut tags = String::new();
2145 fn tag_html(class: &str, contents: &str) -> String {
2146 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2149 // The trailing space after each tag is to space it properly against the rest of the docs.
2150 if item.deprecation().is_some() {
2151 let mut message = "Deprecated";
2152 if let Some(ref stab) = item.stability {
2153 if let Some(ref depr) = stab.deprecation {
2154 if let Some(ref since) = depr.since {
2155 if !stability::deprecation_in_effect(&since) {
2156 message = "Deprecation planned";
2161 tags += &tag_html("deprecated", message);
2164 if let Some(stab) = item
2167 .filter(|s| s.level == stability::Unstable)
2169 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2170 tags += &tag_html("internal", "Internal");
2172 tags += &tag_html("unstable", "Experimental");
2176 if let Some(ref cfg) = item.attrs.cfg {
2177 tags += &tag_html("portability", &cfg.render_short_html());
2183 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2185 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2186 let mut stability = vec![];
2187 let error_codes = cx.shared.codes;
2189 if let Some(Deprecation { note, since }) = &item.deprecation() {
2190 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2191 // but only display the future-deprecation messages for #[rustc_deprecated].
2192 let mut message = if let Some(since) = since {
2193 format!("Deprecated since {}", Escape(since))
2195 String::from("Deprecated")
2197 if let Some(ref stab) = item.stability {
2198 if let Some(ref depr) = stab.deprecation {
2199 if let Some(ref since) = depr.since {
2200 if !stability::deprecation_in_effect(&since) {
2201 message = format!("Deprecating in {}", Escape(&since));
2207 if let Some(note) = note {
2208 let mut ids = cx.id_map.borrow_mut();
2209 let html = MarkdownHtml(
2210 ¬e, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground);
2211 message.push_str(&format!(": {}", html.to_string()));
2213 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2216 if let Some(stab) = item
2219 .filter(|stab| stab.level == stability::Unstable)
2221 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2223 let mut message = if is_rustc_private {
2224 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2226 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2230 if let Some(feature) = stab.feature.as_ref() {
2231 let mut feature = format!("<code>{}</code>", Escape(&feature));
2232 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2233 feature.push_str(&format!(
2234 " <a href=\"{url}{issue}\">#{issue}</a>",
2240 message.push_str(&format!(" ({})", feature));
2243 if let Some(unstable_reason) = &stab.unstable_reason {
2244 // Provide a more informative message than the compiler help.
2245 let unstable_reason = if is_rustc_private {
2246 "This crate is being loaded from the sysroot, a permanently unstable location \
2247 for private compiler dependencies. It is not intended for general use. Prefer \
2248 using a public version of this crate from \
2249 [crates.io](https://crates.io) via [`Cargo.toml`]\
2250 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2255 let mut ids = cx.id_map.borrow_mut();
2257 "<details><summary>{}</summary>{}</details>",
2264 &cx.shared.playground,
2269 let class = if is_rustc_private {
2274 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2277 if let Some(ref cfg) = item.attrs.cfg {
2278 stability.push(format!(
2279 "<div class='stab portability'>{}</div>",
2280 cfg.render_long_html()
2287 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2288 write!(w, "<pre class='rust const'>");
2289 render_attributes(w, it, false);
2290 write!(w, "{vis}const \
2291 {name}: {typ}</pre>",
2292 vis = it.visibility.print_with_space(),
2293 name = it.name.as_ref().unwrap(),
2294 typ = c.type_.print());
2298 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2299 write!(w, "<pre class='rust static'>");
2300 render_attributes(w, it, false);
2301 write!(w, "{vis}static {mutability}\
2302 {name}: {typ}</pre>",
2303 vis = it.visibility.print_with_space(),
2304 mutability = s.mutability.print_with_space(),
2305 name = it.name.as_ref().unwrap(),
2306 typ = s.type_.print());
2310 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2311 let header_len = format!(
2312 "{}{}{}{}{:#}fn {}{:#}",
2313 it.visibility.print_with_space(),
2314 f.header.constness.print_with_space(),
2315 f.header.unsafety.print_with_space(),
2316 f.header.asyncness.print_with_space(),
2317 print_abi_with_space(f.header.abi),
2318 it.name.as_ref().unwrap(),
2321 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it));
2322 render_attributes(w, it, false);
2324 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2325 {name}{generics}{decl}{where_clause}</pre>",
2326 vis = it.visibility.print_with_space(),
2327 constness = f.header.constness.print_with_space(),
2328 unsafety = f.header.unsafety.print_with_space(),
2329 asyncness = f.header.asyncness.print_with_space(),
2330 abi = print_abi_with_space(f.header.abi),
2331 name = it.name.as_ref().unwrap(),
2332 generics = f.generics.print(),
2333 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2338 asyncness: f.header.asyncness,
2343 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer,
2344 implementor_dups: &FxHashMap<&str, (DefId, bool)>) {
2345 // If there's already another implementor that has the same abbridged name, use the
2346 // full path, for example in `std::iter::ExactSizeIterator`
2347 let use_absolute = match implementor.inner_impl().for_ {
2348 clean::ResolvedPath { ref path, is_generic: false, .. } |
2349 clean::BorrowedRef {
2350 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2352 } => implementor_dups[path.last_name()].1,
2355 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2356 implementor.impl_item.stable_since(), false, Some(use_absolute), false, false);
2359 fn render_impls(cx: &Context, w: &mut Buffer,
2361 containing_item: &clean::Item) {
2363 let did = i.trait_did().unwrap();
2364 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2365 render_impl(w, cx, i, assoc_link,
2366 RenderMode::Normal, containing_item.stable_since(), true, None, false, true);
2370 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2371 let mut bounds = String::new();
2372 if !t_bounds.is_empty() {
2374 bounds.push_str(": ");
2376 for (i, p) in t_bounds.iter().enumerate() {
2378 bounds.push_str(" + ");
2380 bounds.push_str(&p.print().to_string());
2386 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2387 let lhs = format!("{}", lhs.inner_impl().print());
2388 let rhs = format!("{}", rhs.inner_impl().print());
2390 // lhs and rhs are formatted as HTML, which may be unnecessary
2391 name_key(&lhs).cmp(&name_key(&rhs))
2400 let bounds = bounds(&t.bounds, false);
2401 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2402 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2403 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2404 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2406 // Output the trait definition
2407 wrap_into_docblock(w, |w| {
2408 write!(w, "<pre class='rust trait'>");
2409 render_attributes(w, it, true);
2410 write!(w, "{}{}{}trait {}{}{}",
2411 it.visibility.print_with_space(),
2412 t.unsafety.print_with_space(),
2413 if t.is_auto { "auto " } else { "" },
2414 it.name.as_ref().unwrap(),
2418 if !t.generics.where_predicates.is_empty() {
2419 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2424 if t.items.is_empty() {
2427 // FIXME: we should be using a derived_id for the Anchors here
2430 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2433 if !types.is_empty() && !consts.is_empty() {
2437 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2440 if !consts.is_empty() && !required.is_empty() {
2443 for (pos, m) in required.iter().enumerate() {
2444 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2447 if pos < required.len() - 1 {
2448 write!(w, "<div class='item-spacer'></div>");
2451 if !required.is_empty() && !provided.is_empty() {
2454 for (pos, m) in provided.iter().enumerate() {
2455 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2457 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2458 write!(w, ",\n {{ ... }}\n");
2461 write!(w, " {{ ... }}\n");
2464 if pos < provided.len() - 1 {
2465 write!(w, "<div class='item-spacer'></div>");
2473 // Trait documentation
2474 document(w, cx, it);
2476 fn write_small_section_header(
2480 extra_content: &str,
2483 <h2 id='{0}' class='small-section-header'>\
2484 {1}<a href='#{0}' class='anchor'></a>\
2485 </h2>{2}", id, title, extra_content)
2488 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2489 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2492 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2493 let name = m.name.as_ref().unwrap();
2494 let item_type = m.type_();
2495 let id = cx.derive_id(format!("{}.{}", item_type, name));
2496 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
2497 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
2498 extra = render_spotlight_traits(m),
2501 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2502 write!(w, "</code>");
2503 render_stability_since(w, m, t);
2508 if !types.is_empty() {
2509 write_small_section_header(w, "associated-types", "Associated Types",
2510 "<div class='methods'>");
2512 trait_item(w, cx, *t, it);
2514 write_loading_content(w, "</div>");
2517 if !consts.is_empty() {
2518 write_small_section_header(w, "associated-const", "Associated Constants",
2519 "<div class='methods'>");
2521 trait_item(w, cx, *t, it);
2523 write_loading_content(w, "</div>");
2526 // Output the documentation for each function individually
2527 if !required.is_empty() {
2528 write_small_section_header(w, "required-methods", "Required methods",
2529 "<div class='methods'>");
2530 for m in &required {
2531 trait_item(w, cx, *m, it);
2533 write_loading_content(w, "</div>");
2535 if !provided.is_empty() {
2536 write_small_section_header(w, "provided-methods", "Provided methods",
2537 "<div class='methods'>");
2538 for m in &provided {
2539 trait_item(w, cx, *m, it);
2541 write_loading_content(w, "</div>");
2544 // If there are methods directly on this trait object, render them here.
2545 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2547 let mut synthetic_types = Vec::new();
2549 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2550 // The DefId is for the first Type found with that name. The bool is
2551 // if any Types with the same name but different DefId have been found.
2552 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2553 for implementor in implementors {
2554 match implementor.inner_impl().for_ {
2555 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2556 clean::BorrowedRef {
2557 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2560 let &mut (prev_did, ref mut has_duplicates) =
2561 implementor_dups.entry(path.last_name()).or_insert((did, false));
2562 if prev_did != did {
2563 *has_duplicates = true;
2570 let (local, foreign) = implementors.iter()
2571 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2572 .map_or(true, |d| cx.cache.paths.contains_key(&d)));
2575 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
2576 .partition(|i| i.inner_impl().synthetic);
2578 synthetic.sort_by(compare_impl);
2579 concrete.sort_by(compare_impl);
2581 if !foreign.is_empty() {
2582 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2584 for implementor in foreign {
2585 let assoc_link = AssocItemLink::GotoSource(
2586 implementor.impl_item.def_id,
2587 &implementor.inner_impl().provided_trait_methods
2589 render_impl(w, cx, &implementor, assoc_link,
2590 RenderMode::Normal, implementor.impl_item.stable_since(), false,
2593 write_loading_content(w, "");
2596 write_small_section_header(w, "implementors", "Implementors",
2597 "<div class='item-list' id='implementors-list'>");
2598 for implementor in concrete {
2599 render_implementor(cx, implementor, w, &implementor_dups);
2601 write_loading_content(w, "</div>");
2604 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2605 "<div class='item-list' id='synthetic-implementors-list'>");
2606 for implementor in synthetic {
2607 synthetic_types.extend(
2608 collect_paths_for_type(implementor.inner_impl().for_.clone())
2610 render_implementor(cx, implementor, w, &implementor_dups);
2612 write_loading_content(w, "</div>");
2615 // even without any implementations to write in, we still want the heading and list, so the
2616 // implementors javascript file pulled in below has somewhere to write the impls into
2617 write_small_section_header(w, "implementors", "Implementors",
2618 "<div class='item-list' id='implementors-list'>");
2619 write_loading_content(w, "</div>");
2622 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2623 "<div class='item-list' id='synthetic-implementors-list'>");
2624 write_loading_content(w, "</div>");
2627 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2628 as_json(&synthetic_types));
2630 write!(w, r#"<script type="text/javascript" async
2631 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2633 root_path = vec![".."; cx.current.len()].join("/"),
2634 path = if it.def_id.is_local() {
2635 cx.current.join("/")
2637 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2638 path[..path.len() - 1].join("/")
2641 name = *it.name.as_ref().unwrap());
2644 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2645 use crate::html::item_type::ItemType::*;
2647 let name = it.name.as_ref().unwrap();
2648 let ty = match it.type_() {
2649 Typedef | AssocType => AssocType,
2653 let anchor = format!("#{}.{}", ty, name);
2655 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2656 AssocItemLink::Anchor(None) => anchor,
2657 AssocItemLink::GotoSource(did, _) => {
2658 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2663 fn assoc_const(w: &mut Buffer,
2666 _default: Option<&String>,
2667 link: AssocItemLink<'_>,
2669 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2671 it.visibility.print_with_space(),
2672 naive_assoc_href(it, link),
2673 it.name.as_ref().unwrap(),
2677 fn assoc_type(w: &mut Buffer, it: &clean::Item,
2678 bounds: &[clean::GenericBound],
2679 default: Option<&clean::Type>,
2680 link: AssocItemLink<'_>,
2682 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
2684 naive_assoc_href(it, link),
2685 it.name.as_ref().unwrap());
2686 if !bounds.is_empty() {
2687 write!(w, ": {}", print_generic_bounds(bounds))
2689 if let Some(default) = default {
2690 write!(w, " = {}", default.print())
2694 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2695 if let Some(v) = ver {
2696 if containing_ver != ver && v.len() > 0 {
2697 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2702 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2703 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2706 fn render_assoc_item(w: &mut Buffer,
2708 link: AssocItemLink<'_>,
2710 fn method(w: &mut Buffer,
2712 header: hir::FnHeader,
2713 g: &clean::Generics,
2715 link: AssocItemLink<'_>,
2717 let name = meth.name.as_ref().unwrap();
2718 let anchor = format!("#{}.{}", meth.type_(), name);
2719 let href = match link {
2720 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2721 AssocItemLink::Anchor(None) => anchor,
2722 AssocItemLink::GotoSource(did, provided_methods) => {
2723 // We're creating a link from an impl-item to the corresponding
2724 // trait-item and need to map the anchored type accordingly.
2725 let ty = if provided_methods.contains(name) {
2731 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2734 let mut header_len = format!(
2735 "{}{}{}{}{}{:#}fn {}{:#}",
2736 meth.visibility.print_with_space(),
2737 header.constness.print_with_space(),
2738 header.unsafety.print_with_space(),
2739 header.asyncness.print_with_space(),
2740 print_default_space(meth.is_default()),
2741 print_abi_with_space(header.abi),
2745 let (indent, end_newline) = if parent == ItemType::Trait {
2751 render_attributes(w, meth, false);
2752 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2753 {generics}{decl}{where_clause}",
2754 if parent == ItemType::Trait { " " } else { "" },
2755 meth.visibility.print_with_space(),
2756 header.constness.print_with_space(),
2757 header.unsafety.print_with_space(),
2758 header.asyncness.print_with_space(),
2759 print_default_space(meth.is_default()),
2760 print_abi_with_space(header.abi),
2763 generics = g.print(),
2768 asyncness: header.asyncness,
2770 where_clause = WhereClause {
2777 clean::StrippedItem(..) => {},
2778 clean::TyMethodItem(ref m) => {
2779 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2781 clean::MethodItem(ref m) => {
2782 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2784 clean::AssocConstItem(ref ty, ref default) => {
2785 assoc_const(w, item, ty, default.as_ref(), link,
2786 if parent == ItemType::Trait { " " } else { "" })
2788 clean::AssocTypeItem(ref bounds, ref default) => {
2789 assoc_type(w, item, bounds, default.as_ref(), link,
2790 if parent == ItemType::Trait { " " } else { "" })
2792 _ => panic!("render_assoc_item called on non-associated-item")
2796 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct) {
2797 wrap_into_docblock(w, |w| {
2798 write!(w, "<pre class='rust struct'>");
2799 render_attributes(w, it, true);
2810 document(w, cx, it);
2811 let mut fields = s.fields.iter().filter_map(|f| {
2813 clean::StructFieldItem(ref ty) => Some((f, ty)),
2817 if let doctree::Plain = s.struct_type {
2818 if fields.peek().is_some() {
2819 write!(w, "<h2 id='fields' class='fields small-section-header'>
2820 Fields{}<a href='#fields' class='anchor'></a></h2>",
2821 document_non_exhaustive_header(it));
2822 document_non_exhaustive(w, it);
2823 for (field, ty) in fields {
2824 let id = cx.derive_id(format!("{}.{}",
2825 ItemType::StructField,
2826 field.name.as_ref().unwrap()));
2827 let ns_id = cx.derive_id(format!("{}.{}",
2828 field.name.as_ref().unwrap(),
2829 ItemType::StructField.name_space()));
2830 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2831 <a href=\"#{id}\" class=\"anchor field\"></a>\
2832 <code id=\"{ns_id}\">{name}: {ty}</code>\
2834 item_type = ItemType::StructField,
2837 name = field.name.as_ref().unwrap(),
2839 document(w, cx, field);
2843 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2846 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) {
2847 wrap_into_docblock(w, |w| {
2848 write!(w, "<pre class='rust union'>");
2849 render_attributes(w, it, true);
2859 document(w, cx, it);
2860 let mut fields = s.fields.iter().filter_map(|f| {
2862 clean::StructFieldItem(ref ty) => Some((f, ty)),
2866 if fields.peek().is_some() {
2867 write!(w, "<h2 id='fields' class='fields small-section-header'>
2868 Fields<a href='#fields' class='anchor'></a></h2>");
2869 for (field, ty) in fields {
2870 let name = field.name.as_ref().expect("union field name");
2871 let id = format!("{}.{}", ItemType::StructField, name);
2872 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2873 <a href=\"#{id}\" class=\"anchor field\"></a>\
2874 <code>{name}: {ty}</code>\
2878 shortty = ItemType::StructField,
2880 if let Some(stability_class) = field.stability_class() {
2881 write!(w, "<span class='stab {stab}'></span>",
2882 stab = stability_class);
2884 document(w, cx, field);
2887 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2890 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
2891 wrap_into_docblock(w, |w| {
2892 write!(w, "<pre class='rust enum'>");
2893 render_attributes(w, it, true);
2894 write!(w, "{}enum {}{}{}",
2895 it.visibility.print_with_space(),
2896 it.name.as_ref().unwrap(),
2898 WhereClause { gens: &e.generics, indent: 0, end_newline: true });
2899 if e.variants.is_empty() && !e.variants_stripped {
2903 for v in &e.variants {
2905 let name = v.name.as_ref().unwrap();
2907 clean::VariantItem(ref var) => {
2909 clean::VariantKind::CLike => write!(w, "{}", name),
2910 clean::VariantKind::Tuple(ref tys) => {
2911 write!(w, "{}(", name);
2912 for (i, ty) in tys.iter().enumerate() {
2914 write!(w, ", ")
2916 write!(w, "{}", ty.print());
2920 clean::VariantKind::Struct(ref s) => {
2936 if e.variants_stripped {
2937 write!(w, " // some variants omitted\n");
2944 document(w, cx, it);
2945 if !e.variants.is_empty() {
2946 write!(w, "<h2 id='variants' class='variants small-section-header'>
2947 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
2948 document_non_exhaustive_header(it));
2949 document_non_exhaustive(w, it);
2950 for variant in &e.variants {
2951 let id = cx.derive_id(format!("{}.{}",
2953 variant.name.as_ref().unwrap()));
2954 let ns_id = cx.derive_id(format!("{}.{}",
2955 variant.name.as_ref().unwrap(),
2956 ItemType::Variant.name_space()));
2957 write!(w, "<div id=\"{id}\" class=\"variant small-section-header\">\
2958 <a href=\"#{id}\" class=\"anchor field\"></a>\
2959 <code id='{ns_id}'>{name}",
2962 name = variant.name.as_ref().unwrap());
2963 if let clean::VariantItem(ref var) = variant.inner {
2964 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2966 for (i, ty) in tys.iter().enumerate() {
2968 write!(w, ", ");
2970 write!(w, "{}", ty.print());
2975 write!(w, "</code></div>");
2976 document(w, cx, variant);
2977 document_non_exhaustive(w, variant);
2979 use crate::clean::{Variant, VariantKind};
2980 if let clean::VariantItem(Variant {
2981 kind: VariantKind::Struct(ref s)
2982 }) = variant.inner {
2983 let variant_id = cx.derive_id(format!("{}.{}.fields",
2985 variant.name.as_ref().unwrap()));
2986 write!(w, "<div class='autohide sub-variant' id='{id}'>",
2988 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
2989 name = variant.name.as_ref().unwrap());
2990 for field in &s.fields {
2991 use crate::clean::StructFieldItem;
2992 if let StructFieldItem(ref ty) = field.inner {
2993 let id = cx.derive_id(format!("variant.{}.field.{}",
2994 variant.name.as_ref().unwrap(),
2995 field.name.as_ref().unwrap()));
2996 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
2997 variant.name.as_ref().unwrap(),
2998 ItemType::Variant.name_space(),
2999 field.name.as_ref().unwrap(),
3000 ItemType::StructField.name_space()));
3001 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3002 <a href=\"#{id}\" class=\"anchor field\"></a>\
3003 <code id='{ns_id}'>{f}: {t}\
3007 f = field.name.as_ref().unwrap(),
3009 document(w, cx, field);
3012 write!(w, "</div></div>");
3014 render_stability_since(w, variant, it);
3017 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3020 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3021 let path = pprust::path_to_string(&attr.path);
3025 } else if let Some(v) = attr.value_str() {
3026 Some(format!("{} = {:?}", path, v))
3027 } else if let Some(values) = attr.meta_item_list() {
3028 let display: Vec<_> = values.iter().filter_map(|attr| {
3029 attr.meta_item().and_then(|mi| render_attribute(mi))
3032 if display.len() > 0 {
3033 Some(format!("{}({})", path, display.join(", ")))
3042 const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
3052 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3053 // left padding. For example:
3055 // #[foo] <----- "top" attribute
3057 // #[bar] <---- not "top" attribute
3060 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3061 let mut attrs = String::new();
3063 for attr in &it.attrs.other_attrs {
3064 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
3067 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3068 attrs.push_str(&format!("#[{}]\n", s));
3071 if attrs.len() > 0 {
3072 write!(w, "<span class=\"docblock attributes{}\">{}</span>",
3073 if top { " top-attr" } else { "" }, &attrs);
3077 fn render_struct(w: &mut Buffer, it: &clean::Item,
3078 g: Option<&clean::Generics>,
3079 ty: doctree::StructType,
3080 fields: &[clean::Item],
3084 it.visibility.print_with_space(),
3085 if structhead {"struct "} else {""},
3086 it.name.as_ref().unwrap());
3087 if let Some(g) = g {
3088 write!(w, "{}", g.print())
3092 if let Some(g) = g {
3093 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3095 let mut has_visible_fields = false;
3097 for field in fields {
3098 if let clean::StructFieldItem(ref ty) = field.inner {
3099 write!(w, "\n{} {}{}: {},",
3101 field.visibility.print_with_space(),
3102 field.name.as_ref().unwrap(),
3104 has_visible_fields = true;
3108 if has_visible_fields {
3109 if it.has_stripped_fields().unwrap() {
3110 write!(w, "\n{} // some fields omitted", tab);
3112 write!(w, "\n{}", tab);
3113 } else if it.has_stripped_fields().unwrap() {
3114 // If there are no visible fields we can just display
3115 // `{ /* fields omitted */ }` to save space.
3116 write!(w, " /* fields omitted */ ");
3122 for (i, field) in fields.iter().enumerate() {
3127 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3130 clean::StructFieldItem(ref ty) => {
3131 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3137 if let Some(g) = g {
3138 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3143 // Needed for PhantomData.
3144 if let Some(g) = g {
3145 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3152 fn render_union(w: &mut Buffer, it: &clean::Item,
3153 g: Option<&clean::Generics>,
3154 fields: &[clean::Item],
3158 it.visibility.print_with_space(),
3159 if structhead {"union "} else {""},
3160 it.name.as_ref().unwrap());
3161 if let Some(g) = g {
3162 write!(w, "{}", g.print());
3163 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3166 write!(w, " {{\n{}", tab);
3167 for field in fields {
3168 if let clean::StructFieldItem(ref ty) = field.inner {
3169 write!(w, " {}{}: {},\n{}",
3170 field.visibility.print_with_space(),
3171 field.name.as_ref().unwrap(),
3177 if it.has_stripped_fields().unwrap() {
3178 write!(w, " // some fields omitted\n{}", tab);
3183 #[derive(Copy, Clone)]
3184 enum AssocItemLink<'a> {
3185 Anchor(Option<&'a str>),
3186 GotoSource(DefId, &'a FxHashSet<String>),
3189 impl<'a> AssocItemLink<'a> {
3190 fn anchor(&self, id: &'a String) -> Self {
3192 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3193 ref other => *other,
3198 enum AssocItemRender<'a> {
3200 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3203 #[derive(Copy, Clone, PartialEq)]
3206 ForDeref { mut_: bool },
3209 fn render_assoc_items(w: &mut Buffer,
3211 containing_item: &clean::Item,
3213 what: AssocItemRender<'_>) {
3215 let v = match c.impls.get(&it) {
3219 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3220 i.inner_impl().trait_.is_none()
3222 if !non_trait.is_empty() {
3223 let render_mode = match what {
3224 AssocItemRender::All => {
3226 <h2 id='methods' class='small-section-header'>\
3227 Methods<a href='#methods' class='anchor'></a>\
3232 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3234 <h2 id='deref-methods' class='small-section-header'>\
3235 Methods from {}<Target = {}>\
3236 <a href='#deref-methods' class='anchor'></a>\
3238 ", trait_.print(), type_.print());
3239 RenderMode::ForDeref { mut_: deref_mut_ }
3242 for i in &non_trait {
3243 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3244 containing_item.stable_since(), true, None, false, true);
3247 if let AssocItemRender::DerefFor { .. } = what {
3250 if !traits.is_empty() {
3251 let deref_impl = traits.iter().find(|t| {
3252 t.inner_impl().trait_.def_id() == c.deref_trait_did
3254 if let Some(impl_) = deref_impl {
3255 let has_deref_mut = traits.iter().find(|t| {
3256 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3258 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3261 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3263 .partition(|t| t.inner_impl().synthetic);
3264 let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete
3266 .partition(|t| t.inner_impl().blanket_impl.is_some());
3268 let mut impls = Buffer::empty_from(&w);
3269 render_impls(cx, &mut impls, &concrete, containing_item);
3270 let impls = impls.into_inner();
3271 if !impls.is_empty() {
3273 <h2 id='implementations' class='small-section-header'>\
3274 Trait Implementations<a href='#implementations' class='anchor'></a>\
3276 <div id='implementations-list'>{}</div>", impls);
3279 if !synthetic.is_empty() {
3281 <h2 id='synthetic-implementations' class='small-section-header'>\
3282 Auto Trait Implementations\
3283 <a href='#synthetic-implementations' class='anchor'></a>\
3285 <div id='synthetic-implementations-list'>\
3287 render_impls(cx, w, &synthetic, containing_item);
3288 write!(w, "</div>");
3291 if !blanket_impl.is_empty() {
3293 <h2 id='blanket-implementations' class='small-section-header'>\
3294 Blanket Implementations\
3295 <a href='#blanket-implementations' class='anchor'></a>\
3297 <div id='blanket-implementations-list'>\
3299 render_impls(cx, w, &blanket_impl, containing_item);
3300 write!(w, "</div>");
3305 fn render_deref_methods(w: &mut Buffer, cx: &Context, impl_: &Impl,
3306 container_item: &clean::Item, deref_mut: bool) {
3307 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3308 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3310 clean::TypedefItem(ref t, true) => Some(&t.type_),
3313 }).next().expect("Expected associated type binding");
3314 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3315 deref_mut_: deref_mut };
3316 if let Some(did) = target.def_id() {
3317 render_assoc_items(w, cx, container_item, did, what)
3319 if let Some(prim) = target.primitive_type() {
3320 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3321 render_assoc_items(w, cx, container_item, did, what);
3327 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3328 let self_type_opt = match item.inner {
3329 clean::MethodItem(ref method) => method.decl.self_type(),
3330 clean::TyMethodItem(ref method) => method.decl.self_type(),
3334 if let Some(self_ty) = self_type_opt {
3335 let (by_mut_ref, by_box, by_value) = match self_ty {
3336 SelfTy::SelfBorrowed(_, mutability) |
3337 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3338 (mutability == Mutability::Mutable, false, false)
3340 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3341 (false, Some(did) == cache().owned_box_did, false)
3343 SelfTy::SelfValue => (false, false, true),
3344 _ => (false, false, false),
3347 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3353 fn render_spotlight_traits(item: &clean::Item) -> String {
3355 clean::FunctionItem(clean::Function { ref decl, .. }) |
3356 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3357 clean::MethodItem(clean::Method { ref decl, .. }) |
3358 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3359 spotlight_decl(decl)
3365 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3366 let mut out = Buffer::html();
3367 let mut trait_ = String::new();
3369 if let Some(did) = decl.output.def_id() {
3371 if let Some(impls) = c.impls.get(&did) {
3373 let impl_ = i.inner_impl();
3374 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3377 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3378 <code class=\"content\">",
3379 impl_.for_.print()));
3380 trait_.push_str(&impl_.for_.print().to_string());
3383 //use the "where" class here to make it small
3385 &format!("<span class=\"where fmt-newline\">{}</span>", impl_.print()));
3386 let t_did = impl_.trait_.def_id().unwrap();
3387 for it in &impl_.items {
3388 if let clean::TypedefItem(ref tydef, _) = it.inner {
3389 out.push_str("<span class=\"where fmt-newline\"> ");
3390 assoc_type(&mut out, it, &[],
3392 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3394 out.push_str(";</span>");
3402 if !out.is_empty() {
3403 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3404 <span class='tooltiptext'>Important traits for {}</span></div>\
3405 <div class=\"content hidden\">",
3407 out.push_str("</code></div></div>");
3413 fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
3414 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
3415 use_absolute: Option<bool>, is_on_foreign_type: bool,
3416 show_default_items: bool) {
3417 if render_mode == RenderMode::Normal {
3418 let id = cx.derive_id(match i.inner_impl().trait_ {
3419 Some(ref t) => if is_on_foreign_type {
3420 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3422 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3424 None => "impl".to_string(),
3426 if let Some(use_absolute) = use_absolute {
3427 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id);
3428 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3430 for it in &i.inner_impl().items {
3431 if let clean::TypedefItem(ref tydef, _) = it.inner {
3432 write!(w, "<span class=\"where fmt-newline\"> ");
3433 assoc_type(w, it, &vec![], Some(&tydef.type_),
3434 AssocItemLink::Anchor(None),
3436 write!(w, ";</span>");
3440 write!(w, "</code>");
3442 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
3443 id, i.inner_impl().print()
3446 write!(w, "<a href='#{}' class='anchor'></a>", id);
3447 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3448 render_stability_since_raw(w, since, outer_version);
3449 if let Some(l) = cx.src_href(&i.impl_item) {
3450 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3451 l, "goto source code");
3454 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3455 let mut ids = cx.id_map.borrow_mut();
3456 write!(w, "<div class='docblock'>{}</div>",
3457 Markdown(&*dox, &i.impl_item.links(), &mut ids,
3458 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string());
3462 fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item,
3463 link: AssocItemLink<'_>, render_mode: RenderMode,
3464 is_default_item: bool, outer_version: Option<&str>,
3465 trait_: Option<&clean::Trait>, show_def_docs: bool) {
3466 let item_type = item.type_();
3467 let name = item.name.as_ref().unwrap();
3469 let render_method_item = match render_mode {
3470 RenderMode::Normal => true,
3471 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3474 let (is_hidden, extra_class) = if (trait_.is_none() ||
3475 item.doc_value().is_some() ||
3476 item.inner.is_associated()) &&
3483 clean::MethodItem(clean::Method { ref decl, .. }) |
3484 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
3485 // Only render when the method is not static or we allow static methods
3486 if render_method_item {
3487 let id = cx.derive_id(format!("{}.{}", item_type, name));
3488 let ns_id = cx.derive_id(format!("{}.{}",
3489 name, item_type.name_space()));
3490 write!(w, "<h4 id='{}' class=\"{}{}\">",
3491 id, item_type, extra_class);
3492 write!(w, "{}", spotlight_decl(decl));
3493 write!(w, "<code id='{}'>", ns_id);
3494 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3495 write!(w, "</code>");
3496 render_stability_since_raw(w, item.stable_since(), outer_version);
3497 if let Some(l) = cx.src_href(item) {
3498 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3499 l, "goto source code");
3504 clean::TypedefItem(ref tydef, _) => {
3505 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3506 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3507 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3508 write!(w, "<code id='{}'>", ns_id);
3509 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3510 write!(w, "</code></h4>");
3512 clean::AssocConstItem(ref ty, ref default) => {
3513 let id = cx.derive_id(format!("{}.{}", item_type, name));
3514 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3515 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3516 write!(w, "<code id='{}'>", ns_id);
3517 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3518 write!(w, "</code>");
3519 render_stability_since_raw(w, item.stable_since(), outer_version);
3520 if let Some(l) = cx.src_href(item) {
3521 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3522 l, "goto source code");
3526 clean::AssocTypeItem(ref bounds, ref default) => {
3527 let id = cx.derive_id(format!("{}.{}", item_type, name));
3528 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3529 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3530 write!(w, "<code id='{}'>", ns_id);
3531 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3532 write!(w, "</code></h4>");
3534 clean::StrippedItem(..) => return,
3535 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3538 if render_method_item {
3539 if !is_default_item {
3540 if let Some(t) = trait_ {
3541 // The trait item may have been stripped so we might not
3542 // find any documentation or stability for it.
3543 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3544 // We need the stability of the item from the trait
3545 // because impls can't have a stability.
3546 document_stability(w, cx, it, is_hidden);
3547 if item.doc_value().is_some() {
3548 document_full(w, item, cx, "", is_hidden);
3549 } else if show_def_docs {
3550 // In case the item isn't documented,
3551 // provide short documentation from the trait.
3552 document_short(w, cx, it, link, "", is_hidden);
3556 document_stability(w, cx, item, is_hidden);
3558 document_full(w, item, cx, "", is_hidden);
3562 document_stability(w, cx, item, is_hidden);
3564 document_short(w, cx, item, link, "", is_hidden);
3570 let traits = &cx.cache.traits;
3571 let trait_ = i.trait_did().map(|did| &traits[&did]);
3573 write!(w, "<div class='impl-items'>");
3574 for trait_item in &i.inner_impl().items {
3575 doc_impl_item(w, cx, trait_item, link, render_mode,
3576 false, outer_version, trait_, show_def_docs);
3579 fn render_default_items(w: &mut Buffer,
3583 render_mode: RenderMode,
3584 outer_version: Option<&str>,
3585 show_def_docs: bool) {
3586 for trait_item in &t.items {
3587 let n = trait_item.name.clone();
3588 if i.items.iter().find(|m| m.name == n).is_some() {
3591 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3592 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3594 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3595 outer_version, None, show_def_docs);
3599 // If we've implemented a trait, then also emit documentation for all
3600 // default items which weren't overridden in the implementation block.
3601 // We don't emit documentation for default items if they appear in the
3602 // Implementations on Foreign Types or Implementors sections.
3603 if show_default_items {
3604 if let Some(t) = trait_ {
3605 render_default_items(w, cx, t, &i.inner_impl(),
3606 render_mode, outer_version, show_def_docs);
3609 write!(w, "</div>");
3616 t: &clean::OpaqueTy,
3618 write!(w, "<pre class='rust opaque'>");
3619 render_attributes(w, it, false);
3620 write!(w, "type {}{}{where_clause} = impl {bounds};</pre>",
3621 it.name.as_ref().unwrap(),
3623 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3624 bounds = bounds(&t.bounds, false));
3626 document(w, cx, it);
3628 // Render any items associated directly to this alias, as otherwise they
3629 // won't be visible anywhere in the docs. It would be nice to also show
3630 // associated items from the aliased type (see discussion in #32077), but
3631 // we need #14072 to make sense of the generics.
3632 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3635 fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item,
3636 t: &clean::TraitAlias) {
3637 write!(w, "<pre class='rust trait-alias'>");
3638 render_attributes(w, it, false);
3639 write!(w, "trait {}{}{} = {};</pre>",
3640 it.name.as_ref().unwrap(),
3642 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3643 bounds(&t.bounds, true));
3645 document(w, cx, it);
3647 // Render any items associated directly to this alias, as otherwise they
3648 // won't be visible anywhere in the docs. It would be nice to also show
3649 // associated items from the aliased type (see discussion in #32077), but
3650 // we need #14072 to make sense of the generics.
3651 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3654 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) {
3655 write!(w, "<pre class='rust typedef'>");
3656 render_attributes(w, it, false);
3657 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3658 it.name.as_ref().unwrap(),
3660 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3661 type_ = t.type_.print());
3663 document(w, cx, it);
3665 // Render any items associated directly to this alias, as otherwise they
3666 // won't be visible anywhere in the docs. It would be nice to also show
3667 // associated items from the aliased type (see discussion in #32077), but
3668 // we need #14072 to make sense of the generics.
3669 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3672 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) {
3673 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3674 render_attributes(w, it, false);
3677 " {}type {};\n}}</pre>",
3678 it.visibility.print_with_space(),
3679 it.name.as_ref().unwrap(),
3682 document(w, cx, it);
3684 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3687 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) {
3688 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3690 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3691 || it.is_enum() || it.is_mod() || it.is_typedef() {
3692 write!(buffer, "<p class='location'>{}{}</p>",
3694 clean::StructItem(..) => "Struct ",
3695 clean::TraitItem(..) => "Trait ",
3696 clean::PrimitiveItem(..) => "Primitive Type ",
3697 clean::UnionItem(..) => "Union ",
3698 clean::EnumItem(..) => "Enum ",
3699 clean::TypedefItem(..) => "Type Definition ",
3700 clean::ForeignTypeItem => "Foreign Type ",
3701 clean::ModuleItem(..) => if it.is_crate() {
3708 it.name.as_ref().unwrap());
3712 if let Some(ref version) = cx.cache.crate_version {
3714 "<div class='block version'>\
3721 write!(buffer, "<div class=\"sidebar-elems\">");
3723 write!(buffer, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3724 it.name.as_ref().expect("crates always have a name"));
3727 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3728 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3729 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3730 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3731 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3732 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3733 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3734 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3738 // The sidebar is designed to display sibling functions, modules and
3739 // other miscellaneous information. since there are lots of sibling
3740 // items (and that causes quadratic growth in large modules),
3741 // we refactor common parts into a shared JavaScript file per module.
3742 // still, we don't move everything into JS because we want to preserve
3743 // as much HTML as possible in order to allow non-JS-enabled browsers
3744 // to navigate the documentation (though slightly inefficiently).
3746 write!(buffer, "<p class='location'>");
3747 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3749 write!(buffer, "::<wbr>");
3751 write!(buffer, "<a href='{}index.html'>{}</a>",
3752 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3755 write!(buffer, "</p>");
3757 // Sidebar refers to the enclosing module, not this module.
3758 let relpath = if it.is_mod() { "../" } else { "" };
3760 "<script>window.sidebarCurrent = {{\
3765 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3769 // There is no sidebar-items.js beyond the crate root path
3770 // FIXME maybe dynamic crate loading can be merged here
3772 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>",
3775 // Closes sidebar-elems div.
3776 write!(buffer, "</div>");
3779 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3780 if used_links.insert(url.clone()) {
3784 while used_links.insert(format!("{}-{}", url, add)) == false {
3787 format!("{}-{}", url, add)
3793 used_links: &mut FxHashSet<String>,
3796 i.items.iter().filter_map(|item| {
3798 Some(ref name) if !name.is_empty() && item.is_method() => {
3799 if !for_deref || should_render_item(item, deref_mut) {
3800 Some(format!("<a href=\"#{}\">{}</a>",
3801 get_next_url(used_links, format!("method.{}", name)),
3809 }).collect::<Vec<_>>()
3812 // The point is to url encode any potential character from a type with genericity.
3813 fn small_url_encode(s: &str) -> String {
3814 s.replace("<", "%3C")
3815 .replace(">", "%3E")
3816 .replace(" ", "%20")
3817 .replace("?", "%3F")
3818 .replace("'", "%27")
3819 .replace("&", "%26")
3820 .replace(",", "%2C")
3821 .replace(":", "%3A")
3822 .replace(";", "%3B")
3823 .replace("[", "%5B")
3824 .replace("]", "%5D")
3825 .replace("\"", "%22")
3828 fn sidebar_assoc_items(it: &clean::Item) -> String {
3829 let mut out = String::new();
3831 if let Some(v) = c.impls.get(&it.def_id) {
3832 let mut used_links = FxHashSet::default();
3835 let used_links_bor = &mut used_links;
3836 let mut ret = v.iter()
3837 .filter(|i| i.inner_impl().trait_.is_none())
3838 .flat_map(move |i| get_methods(i.inner_impl(),
3840 used_links_bor, false))
3841 .collect::<Vec<_>>();
3842 // We want links' order to be reproducible so we don't use unstable sort.
3844 if !ret.is_empty() {
3845 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3846 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
3850 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3851 if let Some(impl_) = v.iter()
3852 .filter(|i| i.inner_impl().trait_.is_some())
3853 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3854 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3856 clean::TypedefItem(ref t, true) => Some(&t.type_),
3860 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3861 c.primitive_locations.get(&prim).cloned()
3862 })).and_then(|did| c.impls.get(&did));
3863 if let Some(impls) = inner_impl {
3864 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3865 out.push_str(&format!("Methods from {}<Target={}>",
3867 "{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print()
3869 Escape(&format!("{:#}", target.print()))));
3870 out.push_str("</a>");
3871 let mut ret = impls.iter()
3872 .filter(|i| i.inner_impl().trait_.is_none())
3873 .flat_map(|i| get_methods(i.inner_impl(),
3877 .collect::<Vec<_>>();
3878 // We want links' order to be reproducible so we don't use unstable sort.
3880 if !ret.is_empty() {
3881 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
3887 let format_impls = |impls: Vec<&Impl>| {
3888 let mut links = FxHashSet::default();
3890 let mut ret = impls.iter()
3892 let is_negative_impl = is_negative_impl(i.inner_impl());
3893 if let Some(ref i) = i.inner_impl().trait_ {
3894 let i_display = format!("{:#}", i.print());
3895 let out = Escape(&i_display);
3896 let encoded = small_url_encode(&format!("{:#}", i.print()));
3897 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3899 if is_negative_impl { "!" } else { "" },
3901 if links.insert(generated.clone()) {
3910 .collect::<Vec<String>>();
3915 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
3917 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3918 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
3920 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
3922 let concrete_format = format_impls(concrete);
3923 let synthetic_format = format_impls(synthetic);
3924 let blanket_format = format_impls(blanket_impl);
3926 if !concrete_format.is_empty() {
3927 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3928 Trait Implementations</a>");
3929 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3932 if !synthetic_format.is_empty() {
3933 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3934 Auto Trait Implementations</a>");
3935 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3938 if !blanket_format.is_empty() {
3939 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
3940 Blanket Implementations</a>");
3941 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
3949 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
3950 let mut sidebar = String::new();
3951 let fields = get_struct_fields_name(&s.fields);
3953 if !fields.is_empty() {
3954 if let doctree::Plain = s.struct_type {
3955 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3956 <div class=\"sidebar-links\">{}</div>", fields));
3960 sidebar.push_str(&sidebar_assoc_items(it));
3962 if !sidebar.is_empty() {
3963 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
3967 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
3968 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
3971 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3973 clean::ItemEnum::ImplItem(ref i) => {
3974 if let Some(ref trait_) = i.trait_ {
3976 format!("{:#}", i.for_.print()),
3977 get_id_for_impl_on_foreign_type(&i.for_, trait_),
3987 fn is_negative_impl(i: &clean::Impl) -> bool {
3988 i.polarity == Some(clean::ImplPolarity::Negative)
3991 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
3992 let mut sidebar = String::new();
3998 Some(ref name) if m.is_associated_type() => {
3999 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4005 .collect::<String>();
4006 let consts = t.items
4010 Some(ref name) if m.is_associated_const() => {
4011 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4017 .collect::<String>();
4018 let mut required = t.items
4022 Some(ref name) if m.is_ty_method() => {
4023 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4029 .collect::<Vec<String>>();
4030 let mut provided = t.items
4034 Some(ref name) if m.is_method() => {
4035 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4040 .collect::<Vec<String>>();
4042 if !types.is_empty() {
4043 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4044 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4047 if !consts.is_empty() {
4048 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4049 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4052 if !required.is_empty() {
4054 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4055 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4056 required.join("")));
4058 if !provided.is_empty() {
4060 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4061 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4062 provided.join("")));
4067 if let Some(implementors) = c.implementors.get(&it.def_id) {
4068 let mut res = implementors.iter()
4069 .filter(|i| i.inner_impl().for_.def_id()
4070 .map_or(false, |d| !c.paths.contains_key(&d)))
4072 match extract_for_impl_name(&i.impl_item) {
4073 Some((ref name, ref id)) => {
4074 Some(format!("<a href=\"#{}\">{}</a>",
4081 .collect::<Vec<String>>();
4082 if !res.is_empty() {
4084 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4085 Implementations on Foreign Types</a><div \
4086 class=\"sidebar-links\">{}</div>",
4091 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4093 sidebar.push_str("<a class=\"sidebar-title\" \
4094 href=\"#synthetic-implementors\">Auto Implementors</a>");
4097 sidebar.push_str(&sidebar_assoc_items(it));
4099 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4102 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4103 let sidebar = sidebar_assoc_items(it);
4105 if !sidebar.is_empty() {
4106 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4110 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4111 let sidebar = sidebar_assoc_items(it);
4113 if !sidebar.is_empty() {
4114 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4118 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4120 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4125 .filter_map(|f| match f.name {
4126 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4127 {name}</a>", name=name)),
4133 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4134 let mut sidebar = String::new();
4135 let fields = get_struct_fields_name(&u.fields);
4137 if !fields.is_empty() {
4138 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4139 <div class=\"sidebar-links\">{}</div>", fields));
4142 sidebar.push_str(&sidebar_assoc_items(it));
4144 if !sidebar.is_empty() {
4145 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4149 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4150 let mut sidebar = String::new();
4152 let variants = e.variants.iter()
4153 .filter_map(|v| match v.name {
4154 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4155 </a>", name = name)),
4158 .collect::<String>();
4159 if !variants.is_empty() {
4160 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4161 <div class=\"sidebar-links\">{}</div>", variants));
4164 sidebar.push_str(&sidebar_assoc_items(it));
4166 if !sidebar.is_empty() {
4167 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4171 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4173 ItemType::ExternCrate |
4174 ItemType::Import => ("reexports", "Re-exports"),
4175 ItemType::Module => ("modules", "Modules"),
4176 ItemType::Struct => ("structs", "Structs"),
4177 ItemType::Union => ("unions", "Unions"),
4178 ItemType::Enum => ("enums", "Enums"),
4179 ItemType::Function => ("functions", "Functions"),
4180 ItemType::Typedef => ("types", "Type Definitions"),
4181 ItemType::Static => ("statics", "Statics"),
4182 ItemType::Constant => ("constants", "Constants"),
4183 ItemType::Trait => ("traits", "Traits"),
4184 ItemType::Impl => ("impls", "Implementations"),
4185 ItemType::TyMethod => ("tymethods", "Type Methods"),
4186 ItemType::Method => ("methods", "Methods"),
4187 ItemType::StructField => ("fields", "Struct Fields"),
4188 ItemType::Variant => ("variants", "Variants"),
4189 ItemType::Macro => ("macros", "Macros"),
4190 ItemType::Primitive => ("primitives", "Primitive Types"),
4191 ItemType::AssocType => ("associated-types", "Associated Types"),
4192 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4193 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4194 ItemType::Keyword => ("keywords", "Keywords"),
4195 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4196 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4197 ItemType::ProcDerive => ("derives", "Derive Macros"),
4198 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4202 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4203 let mut sidebar = String::new();
4205 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4206 it.type_() == ItemType::Import) {
4207 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4209 name = "Re-exports"));
4212 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4213 // to print its headings
4214 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4215 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4216 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4217 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4218 ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType,
4219 ItemType::Keyword] {
4220 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4221 let (short, name) = item_ty_to_strs(&myty);
4222 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4228 if !sidebar.is_empty() {
4229 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4233 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4234 let sidebar = sidebar_assoc_items(it);
4235 if !sidebar.is_empty() {
4236 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4240 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4241 wrap_into_docblock(w, |w| {
4242 w.write_str(&highlight::render_with_highlighting(&t.source,
4250 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4251 let name = it.name.as_ref().expect("proc-macros always have names");
4253 MacroKind::Bang => {
4254 write!(w, "<pre class='rust macro'>");
4255 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4256 write!(w, "</pre>");
4258 MacroKind::Attr => {
4259 write!(w, "<pre class='rust attr'>");
4260 write!(w, "#[{}]", name);
4261 write!(w, "</pre>");
4263 MacroKind::Derive => {
4264 write!(w, "<pre class='rust derive'>");
4265 write!(w, "#[derive({})]", name);
4266 if !m.helpers.is_empty() {
4267 writeln!(w, "\n{{");
4268 writeln!(w, " // Attributes available to this derive:");
4269 for attr in &m.helpers {
4270 writeln!(w, " #[{}]", attr);
4274 write!(w, "</pre>");
4280 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4281 document(w, cx, it);
4282 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4285 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4289 crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4291 fn make_item_keywords(it: &clean::Item) -> String {
4292 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4295 /// Returns a list of all paths used in the type.
4296 /// This is used to help deduplicate imported impls
4297 /// for reexported types. If any of the contained
4298 /// types are re-exported, we don't use the corresponding
4299 /// entry from the js file, as inlining will have already
4300 /// picked up the impl
4301 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4302 let mut out = Vec::new();
4303 let mut visited = FxHashSet::default();
4304 let mut work = VecDeque::new();
4305 let cache = cache();
4307 work.push_back(first_ty);
4309 while let Some(ty) = work.pop_front() {
4310 if !visited.insert(ty.clone()) {
4315 clean::Type::ResolvedPath { did, .. } => {
4316 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4317 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4321 out.push(path.join("::"));
4327 clean::Type::Tuple(tys) => {
4328 work.extend(tys.into_iter());
4330 clean::Type::Slice(ty) => {
4331 work.push_back(*ty);
4333 clean::Type::Array(ty, _) => {
4334 work.push_back(*ty);
4336 clean::Type::RawPointer(_, ty) => {
4337 work.push_back(*ty);
4339 clean::Type::BorrowedRef { type_, .. } => {
4340 work.push_back(*type_);
4342 clean::Type::QPath { self_type, trait_, .. } => {
4343 work.push_back(*self_type);
4344 work.push_back(*trait_);
4352 crate fn cache() -> Arc<Cache> {
4353 CACHE_KEY.with(|c| c.borrow().clone())