// ignore-tidy-filelength
//! Rustdoc's HTML rendering module.
//!
//! This modules contains the bulk of the logic necessary for rendering a
//! rustdoc `clean::Crate` instance to a set of static HTML pages. This
//! rendering process is largely driven by the `format!` syntax extension to
//! perform all I/O into files and streams.
//!
//! The rendering process is largely driven by the `Context` and `Cache`
//! structures. The cache is pre-populated by crawling the crate in question,
//! and then it is shared among the various rendering threads. The cache is meant
//! to be a fairly large structure not implementing `Clone` (because it's shared
//! among threads). The context, however, should be a lightweight structure. This
//! is cloned per-thread and contains information about what is currently being
//! rendered.
//!
//! In order to speed up rendering (mostly because of markdown rendering), the
//! rendering process has been parallelized. This parallelization is only
//! exposed through the `crate` method on the context, and then also from the
//! fact that the shared cache is stored in TLS (and must be accessed as such).
//!
//! In addition to rendering the crate itself, this module is also responsible
//! for creating the corresponding search index and source file renderings.
//! These threads are not parallelized (they haven't been a bottleneck yet), and
//! both occur before the crate is rendered.
pub mod cache;
#[cfg(test)]
mod tests;
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};
use std::default::Default;
use std::ffi::OsStr;
use std::fmt::{self, Write};
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::path::{Component, Path, PathBuf};
use std::rc::Rc;
use std::str;
use std::string::ToString;
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use itertools::Itertools;
use rustc_ast_pretty::pprust;
use rustc_data_structures::flock;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_feature::UnstableFeatures;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::Mutability;
use rustc_middle::middle::stability;
use rustc_span::edition::Edition;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::FileName;
use rustc_span::symbol::{sym, Symbol};
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
use crate::config::{RenderInfo, RenderOptions};
use crate::docfs::{DocFS, PathError};
use crate::doctree;
use crate::error::Error;
use crate::formats::cache::{cache, Cache};
use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::fmt_impl_for_trait_page;
use crate::html::format::Function;
use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
use crate::html::sources;
use crate::html::{highlight, layout, static_files};
use cache::{build_index, ExternalLocation};
/// A pair of name and its optional document.
pub type NameDoc = (String, Option Crate {} Version {} Back to index Settings(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result\
List of all crates\
\
{}
",
krates
.iter()
.map(|s| {
format!(
"{}
{}
",
title,
Escape(title),
class,
e.iter().map(|s| format!("\
\
\
\
[−]\
\
List of all items\
"
);
print_entries(f, &self.structs, "Structs", "structs");
print_entries(f, &self.enums, "Enums", "enums");
print_entries(f, &self.unions, "Unions", "unions");
print_entries(f, &self.primitives, "Primitives", "primitives");
print_entries(f, &self.traits, "Traits", "traits");
print_entries(f, &self.macros, "Macros", "macros");
print_entries(f, &self.attributes, "Attribute Macros", "attributes");
print_entries(f, &self.derives, "Derive Macros", "derives");
print_entries(f, &self.functions, "Functions", "functions");
print_entries(f, &self.typedefs, "Typedefs", "typedefs");
print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
print_entries(f, &self.statics, "Statics", "statics");
print_entries(f, &self.constants, "Constants", "constants")
}
}
#[derive(Debug)]
enum Setting {
Section { description: &'static str, sub_settings: Vec\
Rustdoc settings\
\
");
if let Some(version) = item.stable_since() {
write!(
buf,
"{0}",
version
);
}
write!(
buf,
"\
\
[−]\
\
"
);
// Write `src` tag
//
// When this item is part of a `pub use` in a downstream crate, the
// [src] link in the downstream documentation will actually come back to
// this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click.
if cx.shared.include_sources && !item.is_primitive() {
if let Some(l) = cx.src_href(item, cache) {
write!(buf, "[src]", l, "goto source code");
}
}
write!(buf, ""); // out-of-band
write!(buf, "");
let name = match item.inner {
clean::ModuleItem(ref m) => {
if m.is_crate {
"Crate "
} else {
"Module "
}
}
clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
clean::TraitItem(..) => "Trait ",
clean::StructItem(..) => "Struct ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypedefItem(..) => "Type Definition ",
clean::MacroItem(..) => "Macro ",
clean::ProcMacroItem(ref mac) => match mac.kind {
MacroKind::Bang => "Macro ",
MacroKind::Attr => "Attribute Macro ",
MacroKind::Derive => "Derive Macro ",
},
clean::PrimitiveItem(..) => "Primitive Type ",
clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
clean::ConstantItem(..) => "Constant ",
clean::ForeignTypeItem => "Foreign Type ",
clean::KeywordItem(..) => "Keyword ",
clean::OpaqueTyItem(..) => "Opaque Type ",
clean::TraitAliasItem(..) => "Trait Alias ",
_ => {
// We don't generate pages for any other type.
unreachable!();
}
};
buf.write_str(name);
if !item.is_primitive() && !item.is_keyword() {
let cur = &cx.current;
let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
write!(
buf,
"{}::
"); // in-band
match item.inner {
clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
item_function(buf, cx, item, f)
}
clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
clean::KeywordItem(_) => item_keyword(buf, cx, item),
clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
_ => {
// We don't generate pages for any other type.
unreachable!();
}
}
}
fn item_path(ty: ItemType, name: &str) -> String {
match ty {
ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
_ => format!("{}.{}.html", ty, name),
}
}
fn full_path(cx: &Context, item: &clean::Item) -> String {
let mut s = cx.current.join("::");
s.push_str("::");
s.push_str(item.name.as_ref().unwrap());
s
}
/// Renders the first paragraph of the given markdown as plain text, making it suitable for
/// contexts like alt-text or the search index.
///
/// If no markdown is supplied, the empty string is returned.
///
/// See [`markdown::plain_text_summary`] for further details.
#[inline]
crate fn plain_text_summary(s: Option<&str>) -> String {
s.map(markdown::plain_text_summary).unwrap_or_default()
}
crate fn shorten(s: String) -> String {
if s.chars().count() > 60 {
let mut len = 0;
let mut ret = s
.split_whitespace()
.take_while(|p| {
// + 1 for the added character after the word.
len += p.chars().count() + 1;
len < 60
})
.collect::
Struct {{ .. }}
syntax; cannot be \
matched against without a wildcard ..
; and \
struct update syntax will not work."
);
} else if item.is_enum() {
write!(
w,
"Non-exhaustive enums could have additional variants added in future. \
Therefore, when matching against variants of non-exhaustive enums, an \
extra wildcard arm must be added to account for any future variants."
);
} else if item.is_variant() {
write!(
w,
"Non-exhaustive enum variants could have additional fields added in future. \
Therefore, non-exhaustive enum variants cannot be constructed in external \
crates and cannot be matched against."
);
} else {
write!(
w,
"This type will require a wildcard arm in any match statements or constructors."
);
}
write!(w, "{}extern crate {} as {};",
myitem.visibility.print_with_space(),
anchor(myitem.def_id, src),
name
),
None => write!(
w,
" |
{}
", Escape(&stab.feature));
if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
feature.push_str(&format!(
" #{issue}",
url = url,
issue = issue
));
}
message.push_str(&format!(" ({})", feature));
if let Some(unstable_reason) = &stab.unstable_reason {
let mut ids = cx.id_map.borrow_mut();
message = format!(
""); render_attributes(w, it, false); write!( w, "{vis}const {name}: {typ}", vis = it.visibility.print_with_space(), name = it.name.as_ref().unwrap(), typ = c.type_.print(), ); if c.value.is_some() || c.is_literal { write!(w, " = {expr};", expr = Escape(&c.expr)); } else { write!(w, ";"); } if let Some(value) = &c.value { if !c.is_literal { let value_lowercase = value.to_lowercase(); let expr_lowercase = c.expr.to_lowercase(); if value_lowercase != expr_lowercase && value_lowercase.trim_end_matches("i32") != expr_lowercase { write!(w, " // {value}", value = Escape(value)); } } } write!(w, ""); document(w, cx, it) } fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) { write!(w, "
"); render_attributes(w, it, false); write!( w, "{vis}static {mutability} {name}: {typ}", vis = it.visibility.print_with_space(), mutability = s.mutability.print_with_space(), name = it.name.as_ref().unwrap(), typ = s.type_.print() ); document(w, cx, it) } fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) { let header_len = format!( "{}{}{}{}{:#}fn {}{:#}", it.visibility.print_with_space(), f.header.constness.print_with_space(), f.header.asyncness.print_with_space(), f.header.unsafety.print_with_space(), print_abi_with_space(f.header.abi), it.name.as_ref().unwrap(), f.generics.print() ) .len(); write!(w, "
"); render_attributes(w, it, false); write!( w, "{vis}{constness}{asyncness}{unsafety}{abi}fn \ {name}{generics}{decl}{spotlight}{where_clause}", vis = it.visibility.print_with_space(), constness = f.header.constness.print_with_space(), asyncness = f.header.asyncness.print_with_space(), unsafety = f.header.unsafety.print_with_space(), abi = print_abi_with_space(f.header.abi), name = it.name.as_ref().unwrap(), generics = f.generics.print(), where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true }, decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness } .print(), spotlight = spotlight_decl(&f.decl), ); document(w, cx, it) } fn render_implementor( cx: &Context, implementor: &Impl, w: &mut Buffer, implementor_dups: &FxHashMap<&str, (DefId, bool)>, aliases: &[String], cache: &Cache, ) { // If there's already another implementor that has the same abbridged name, use the // full path, for example in `std::iter::ExactSizeIterator` let use_absolute = match implementor.inner_impl().for_ { clean::ResolvedPath { ref path, is_generic: false, .. } | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, is_generic: false, .. }, .. } => implementor_dups[path.last_name()].1, _ => false, }; render_impl( w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal, implementor.impl_item.stable_since(), false, Some(use_absolute), false, false, aliases, cache, ); } fn render_impls( cx: &Context, w: &mut Buffer, traits: &[&&Impl], containing_item: &clean::Item, cache: &Cache, ) { let mut impls = traits .iter() .map(|i| { let did = i.trait_did().unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods); let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() }; render_impl( &mut buffer, cx, i, assoc_link, RenderMode::Normal, containing_item.stable_since(), true, None, false, true, &[], cache, ); buffer.into_inner() }) .collect::
"); render_attributes(w, it, true); write!( w, "{}{}{}trait {}{}{}", it.visibility.print_with_space(), t.unsafety.print_with_space(), if t.is_auto { "auto " } else { "" }, it.name.as_ref().unwrap(), t.generics.print(), bounds ); if !t.generics.where_predicates.is_empty() { write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true }); } else { write!(w, " "); } if t.items.is_empty() { write!(w, "{{ }}"); } else { // FIXME: we should be using a derived_id for the Anchors here write!(w, "{{\n"); for t in &types { render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait); write!(w, ";\n"); } if !types.is_empty() && !consts.is_empty() { w.write_str("\n"); } for t in &consts { render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait); write!(w, ";\n"); } if !consts.is_empty() && !required.is_empty() { w.write_str("\n"); } for (pos, m) in required.iter().enumerate() { render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait); write!(w, ";\n"); if pos < required.len() - 1 { write!(w, ""); } } if !required.is_empty() && !provided.is_empty() { w.write_str("\n"); } for (pos, m) in provided.iter().enumerate() { render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait); match m.inner { clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => { write!(w, ",\n {{ ... }}\n"); } _ => { write!(w, " {{ ... }}\n"); } } if pos < provided.len() - 1 { write!(w, ""); } } write!(w, "}}"); } write!(w, "") }); // Trait documentation document(w, cx, it); fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) { write!( w, "
", id = id,);
render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
write!(w, "
");
render_stability_since(w, m, t);
write!(w, ""); render_attributes(w, it, true); render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true); write!(w, "") }); document(w, cx, it); let mut fields = s .fields .iter() .filter_map(|f| match f.inner { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, }) .peekable(); if let doctree::Plain = s.struct_type { if fields.peek().is_some() { write!( w, "
{name}: {ty}
\
",
item_type = ItemType::StructField,
id = id,
name = field.name.as_ref().unwrap(),
ty = ty.print()
);
document(w, cx, field);
}
}
}
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
wrap_into_docblock(w, |w| {
write!(w, ""); render_attributes(w, it, true); render_union(w, it, Some(&s.generics), &s.fields, "", true); write!(w, "") }); document(w, cx, it); let mut fields = s .fields .iter() .filter_map(|f| match f.inner { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, }) .peekable(); if fields.peek().is_some() { write!( w, "
{name}: {ty}
\
",
id = id,
name = name,
shortty = ItemType::StructField,
ty = ty.print()
);
if let Some(stability_class) = field.stability_class() {
write!(w, "", stab = stability_class);
}
document(w, cx, field);
}
}
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
wrap_into_docblock(w, |w| {
write!(w, ""); render_attributes(w, it, true); write!( w, "{}enum {}{}{}", it.visibility.print_with_space(), it.name.as_ref().unwrap(), e.generics.print(), WhereClause { gens: &e.generics, indent: 0, end_newline: true } ); if e.variants.is_empty() && !e.variants_stripped { write!(w, " {{}}"); } else { write!(w, " {{\n"); for v in &e.variants { write!(w, " "); let name = v.name.as_ref().unwrap(); match v.inner { clean::VariantItem(ref var) => match var.kind { clean::VariantKind::CLike => write!(w, "{}", name), clean::VariantKind::Tuple(ref tys) => { write!(w, "{}(", name); for (i, ty) in tys.iter().enumerate() { if i > 0 { write!(w, ", ") } write!(w, "{}", ty.print()); } write!(w, ")"); } clean::VariantKind::Struct(ref s) => { render_struct(w, v, None, s.struct_type, &s.fields, " ", false); } }, _ => unreachable!(), } write!(w, ",\n"); } if e.variants_stripped { write!(w, " // some variants omitted\n"); } write!(w, "}}"); } write!(w, "") }); document(w, cx, it); if !e.variants.is_empty() { write!( w, "
{name}",
id = id,
name = variant.name.as_ref().unwrap()
);
if let clean::VariantItem(ref var) = variant.inner {
if let clean::VariantKind::Tuple(ref tys) = var.kind {
write!(w, "(");
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
write!(w, ", ");
}
write!(w, "{}", ty.print());
}
write!(w, ")");
}
}
write!(w, "
{f}: {t}
\
",
id = id,
f = field.name.as_ref().unwrap(),
t = ty.print()
);
document(w, cx, field);
}
}
write!(w, "",
impl_.for_.print()
));
trait_.push_str(&impl_.for_.print().to_string());
}
//use the "where" class here to make it small
out.push_str(&format!(
"{}",
impl_.print()
));
let t_did = impl_.trait_.def_id().unwrap();
for it in &impl_.items {
if let clean::TypedefItem(ref tydef, _) = it.inner {
out.push_str(" ");
assoc_type(
&mut out,
it,
&[],
Some(&tydef.type_),
AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
"",
);
out.push_str(";");
}
}
}
}
}
}
if !out.is_empty() {
out.insert_str(
0,
"ⓘ"
);
out.push_str("");
}
out.into_inner()
}
fn render_impl(
w: &mut Buffer,
cx: &Context,
i: &Impl,
link: AssocItemLink<'_>,
render_mode: RenderMode,
outer_version: Option<&str>,
show_def_docs: bool,
use_absolute: Option,
is_on_foreign_type: bool,
show_default_items: bool,
// This argument is used to reference same type with different paths to avoid duplication
// in documentation pages for trait with automatic implementations like "Send" and "Sync".
aliases: &[String],
cache: &Cache,
) {
if render_mode == RenderMode::Normal {
let id = cx.derive_id(match i.inner_impl().trait_ {
Some(ref t) => {
if is_on_foreign_type {
get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
} else {
format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
}
}
None => "impl".to_string(),
});
let aliases = if aliases.is_empty() {
String::new()
} else {
format!(" aliases=\"{}\"", aliases.join(","))
};
if let Some(use_absolute) = use_absolute {
write!(w, "", id, aliases);
fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
if show_def_docs {
for it in &i.inner_impl().items {
if let clean::TypedefItem(ref tydef, _) = it.inner {
write!(w, " ");
assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
write!(w, ";");
}
}
}
write!(w, "
");
} else {
write!(
w,
"{}
",
id,
aliases,
i.inner_impl().print()
);
}
write!(w, "", id);
let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
render_stability_since_raw(w, since, outer_version);
if let Some(l) = cx.src_href(&i.impl_item, cache) {
write!(w, "[src]", l, "goto source code");
}
write!(w, "
");
if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
let mut ids = cx.id_map.borrow_mut();
write!(
w,
"{}",
Markdown(
&*dox,
&i.impl_item.links(),
&mut ids,
cx.shared.codes,
cx.shared.edition,
&cx.shared.playground
)
.into_string()
);
}
}
fn doc_impl_item(
w: &mut Buffer,
cx: &Context,
item: &clean::Item,
link: AssocItemLink<'_>,
render_mode: RenderMode,
is_default_item: bool,
outer_version: Option<&str>,
trait_: Option<&clean::Trait>,
show_def_docs: bool,
cache: &Cache,
) {
let item_type = item.type_();
let name = item.name.as_ref().unwrap();
let render_method_item = match render_mode {
RenderMode::Normal => true,
RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
};
let (is_hidden, extra_class) =
if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_type_alias())
&& !is_default_item
{
(false, "")
} else {
(true, " hidden")
};
match item.inner {
clean::MethodItem(clean::Method { .. })
| clean::TyMethodItem(clean::TyMethod { .. }) => {
// Only render when the method is not static or we allow static methods
if render_method_item {
let id = cx.derive_id(format!("{}.{}", item_type, name));
write!(w, "", id, item_type, extra_class);
write!(w, "");
render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
write!(w, "
");
render_stability_since_raw(w, item.stable_since(), outer_version);
if let Some(l) = cx.src_href(item, cache) {
write!(
w,
"[src]",
l, "goto source code"
);
}
write!(w, "
");
}
}
clean::TypedefItem(ref tydef, _) => {
let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
write!(w, "", id, item_type, extra_class);
assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
write!(w, "
");
}
clean::AssocConstItem(ref ty, ref default) => {
let id = cx.derive_id(format!("{}.{}", item_type, name));
write!(w, "", id, item_type, extra_class);
assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
write!(w, "
");
render_stability_since_raw(w, item.stable_since(), outer_version);
if let Some(l) = cx.src_href(item, cache) {
write!(
w,
"[src]",
l, "goto source code"
);
}
write!(w, "
");
}
clean::AssocTypeItem(ref bounds, ref default) => {
let id = cx.derive_id(format!("{}.{}", item_type, name));
write!(w, "", id, item_type, extra_class);
assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
write!(w, "
");
}
clean::StrippedItem(..) => return,
_ => panic!("can't make docs for trait item with name {:?}", item.name),
}
if render_method_item {
if !is_default_item {
if let Some(t) = trait_ {
// The trait item may have been stripped so we might not
// find any documentation or stability for it.
if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
// We need the stability of the item from the trait
// because impls can't have a stability.
document_stability(w, cx, it, is_hidden);
if item.doc_value().is_some() {
document_full(w, item, cx, "", is_hidden);
} else if show_def_docs {
// In case the item isn't documented,
// provide short documentation from the trait.
document_short(w, it, link, "", is_hidden);
}
}
} else {
document_stability(w, cx, item, is_hidden);
if show_def_docs {
document_full(w, item, cx, "", is_hidden);
}
}
} else {
document_stability(w, cx, item, is_hidden);
if show_def_docs {
document_short(w, item, link, "", is_hidden);
}
}
}
}
let traits = &cache.traits;
let trait_ = i.trait_did().map(|did| &traits[&did]);
write!(w, "");
for trait_item in &i.inner_impl().items {
doc_impl_item(
w,
cx,
trait_item,
link,
render_mode,
false,
outer_version,
trait_,
show_def_docs,
cache,
);
}
fn render_default_items(
w: &mut Buffer,
cx: &Context,
t: &clean::Trait,
i: &clean::Impl,
render_mode: RenderMode,
outer_version: Option<&str>,
show_def_docs: bool,
cache: &Cache,
) {
for trait_item in &t.items {
let n = trait_item.name.clone();
if i.items.iter().any(|m| m.name == n) {
continue;
}
let did = i.trait_.as_ref().unwrap().def_id().unwrap();
let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
doc_impl_item(
w,
cx,
trait_item,
assoc_link,
render_mode,
true,
outer_version,
None,
show_def_docs,
cache,
);
}
}
// If we've implemented a trait, then also emit documentation for all
// default items which weren't overridden in the implementation block.
// We don't emit documentation for default items if they appear in the
// Implementations on Foreign Types or Implementors sections.
if show_default_items {
if let Some(t) = trait_ {
render_default_items(
w,
cx,
t,
&i.inner_impl(),
render_mode,
outer_version,
show_def_docs,
cache,
);
}
}
write!(w, "");
}
fn item_opaque_ty(
w: &mut Buffer,
cx: &Context,
it: &clean::Item,
t: &clean::OpaqueTy,
cache: &Cache,
) {
write!(w, "");
render_attributes(w, it, false);
write!(
w,
"type {}{}{where_clause} = impl {bounds};
",
it.name.as_ref().unwrap(),
t.generics.print(),
where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
bounds = bounds(&t.bounds, false)
);
document(w, cx, it);
// Render any items associated directly to this alias, as otherwise they
// won't be visible anywhere in the docs. It would be nice to also show
// associated items from the aliased type (see discussion in #32077), but
// we need #14072 to make sense of the generics.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_trait_alias(
w: &mut Buffer,
cx: &Context,
it: &clean::Item,
t: &clean::TraitAlias,
cache: &Cache,
) {
write!(w, "");
render_attributes(w, it, false);
write!(
w,
"trait {}{}{} = {};
",
it.name.as_ref().unwrap(),
t.generics.print(),
WhereClause { gens: &t.generics, indent: 0, end_newline: true },
bounds(&t.bounds, true)
);
document(w, cx, it);
// Render any items associated directly to this alias, as otherwise they
// won't be visible anywhere in the docs. It would be nice to also show
// associated items from the aliased type (see discussion in #32077), but
// we need #14072 to make sense of the generics.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
write!(w, "");
render_attributes(w, it, false);
write!(
w,
"type {}{}{where_clause} = {type_};
",
it.name.as_ref().unwrap(),
t.generics.print(),
where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
type_ = t.type_.print()
);
document(w, cx, it);
// Render any items associated directly to this alias, as otherwise they
// won't be visible anywhere in the docs. It would be nice to also show
// associated items from the aliased type (see discussion in #32077), but
// we need #14072 to make sense of the generics.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
writeln!(w, "extern {{");
render_attributes(w, it, false);
write!(
w,
" {}type {};\n}}
",
it.visibility.print_with_space(),
it.name.as_ref().unwrap(),
);
document(w, cx, it);
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
if it.is_struct()
|| it.is_trait()
|| it.is_primitive()
|| it.is_union()
|| it.is_enum()
|| it.is_mod()
|| it.is_typedef()
{
write!(
buffer,
"
{}{}
",
match it.inner {
clean::StructItem(..) => "Struct ",
clean::TraitItem(..) => "Trait ",
clean::PrimitiveItem(..) => "Primitive Type ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypedefItem(..) => "Type Definition ",
clean::ForeignTypeItem => "Foreign Type ",
clean::ModuleItem(..) =>
if it.is_crate() {
"Crate "
} else {
"Module "
},
_ => "",
},
it.name.as_ref().unwrap()
);
}
if it.is_crate() {
if let Some(ref version) = cache.crate_version {
write!(
buffer,
"\
Version {}
\
",
Escape(version)
);
}
}
write!(buffer, " ");
}
fn get_next_url(used_links: &mut FxHashSet, url: String) -> String {
if used_links.insert(url.clone()) {
return url;
}
let mut add = 1;
while !used_links.insert(format!("{}-{}", url, add)) {
add += 1;
}
format!("{}-{}", url, add)
}
fn get_methods(
i: &clean::Impl,
for_deref: bool,
used_links: &mut FxHashSet,
deref_mut: bool,
) -> Vec {
i.items
.iter()
.filter_map(|item| match item.name {
Some(ref name) if !name.is_empty() && item.is_method() => {
if !for_deref || should_render_item(item, deref_mut) {
Some(format!(
"{}",
get_next_url(used_links, format!("method.{}", name)),
name
))
} else {
None
}
}
_ => None,
})
.collect::>()
}
// The point is to url encode any potential character from a type with genericity.
fn small_url_encode(s: &str) -> String {
s.replace("<", "%3C")
.replace(">", "%3E")
.replace(" ", "%20")
.replace("?", "%3F")
.replace("'", "%27")
.replace("&", "%26")
.replace(",", "%2C")
.replace(":", "%3A")
.replace(";", "%3B")
.replace("[", "%5B")
.replace("]", "%5D")
.replace("\"", "%22")
}
fn sidebar_assoc_items(it: &clean::Item) -> String {
let mut out = String::new();
let c = cache();
if let Some(v) = c.impls.get(&it.def_id) {
let mut used_links = FxHashSet::default();
{
let used_links_bor = &mut used_links;
let mut ret = v
.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
.collect::>();
if !ret.is_empty() {
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
out.push_str(&format!(
"Methods\
>();
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
if !ret.is_empty() {
out.push_str(&format!(
">();
ret.sort();
ret.join("")
};
let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
v.iter().partition::, _>(|i| i.inner_impl().synthetic);
let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
.into_iter()
.partition::, _>(|i| i.inner_impl().blanket_impl.is_some());
let concrete_format = format_impls(concrete);
let synthetic_format = format_impls(synthetic);
let blanket_format = format_impls(blanket_impl);
if !concrete_format.is_empty() {
out.push_str(
"\
Trait Implementations",
);
out.push_str(&format!("{}", sidebar);
}
}
fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
}
fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
match item.inner {
clean::ItemEnum::ImplItem(ref i) => {
if let Some(ref trait_) = i.trait_ {
Some((
format!("{:#}", i.for_.print()),
get_id_for_impl_on_foreign_type(&i.for_, trait_),
))
} else {
None
}
}
_ => None,
}
}
fn is_negative_impl(i: &clean::Impl) -> bool {
i.polarity == Some(clean::ImplPolarity::Negative)
}
fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
let mut sidebar = String::new();
let mut types = t
.items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if m.is_associated_type() => {
Some(format!("{name}", name = name))
}
_ => None,
})
.collect::>();
let mut consts = t
.items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if m.is_associated_const() => {
Some(format!("{name}", name = name))
}
_ => None,
})
.collect::>();
let mut required = t
.items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if m.is_ty_method() => {
Some(format!("{name}", name = name))
}
_ => None,
})
.collect::>();
let mut provided = t
.items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if m.is_method() => {
Some(format!("{0}", name))
}
_ => None,
})
.collect::>();
if !types.is_empty() {
types.sort();
sidebar.push_str(&format!(
"\
Associated Types>();
if !res.is_empty() {
res.sort();
sidebar.push_str(&format!(
"\
Implementations on Foreign Types\
>()
.join("")
));
}
}
sidebar.push_str(&sidebar_assoc_items(it));
sidebar.push_str("Implementors");
if t.auto {
sidebar.push_str(
"Auto Implementors",
);
}
write!(buf, "{}", sidebar)
}
fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn get_struct_fields_name(fields: &[clean::Item]) -> String {
let mut fields = fields
.iter()
.filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
.filter_map(|f| match f.name {
Some(ref name) => {
Some(format!("{name}", name = name))
}
_ => None,
})
.collect::>();
fields.sort();
fields.join("")
}
fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
let mut sidebar = String::new();
let fields = get_struct_fields_name(&u.fields);
if !fields.is_empty() {
sidebar.push_str(&format!(
"Fields\
{}", sidebar);
}
}
fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
let mut sidebar = String::new();
let mut variants = e
.variants
.iter()
.filter_map(|v| match v.name {
Some(ref name) => Some(format!("{name}", name = name)),
_ => None,
})
.collect::>();
if !variants.is_empty() {
variants.sort_unstable();
sidebar.push_str(&format!(
"Variants\
{}", sidebar);
}
}
fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
match *ty {
ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
ItemType::Module => ("modules", "Modules"),
ItemType::Struct => ("structs", "Structs"),
ItemType::Union => ("unions", "Unions"),
ItemType::Enum => ("enums", "Enums"),
ItemType::Function => ("functions", "Functions"),
ItemType::Typedef => ("types", "Type Definitions"),
ItemType::Static => ("statics", "Statics"),
ItemType::Constant => ("constants", "Constants"),
ItemType::Trait => ("traits", "Traits"),
ItemType::Impl => ("impls", "Implementations"),
ItemType::TyMethod => ("tymethods", "Type Methods"),
ItemType::Method => ("methods", "Methods"),
ItemType::StructField => ("fields", "Struct Fields"),
ItemType::Variant => ("variants", "Variants"),
ItemType::Macro => ("macros", "Macros"),
ItemType::Primitive => ("primitives", "Primitive Types"),
ItemType::AssocType => ("associated-types", "Associated Types"),
ItemType::AssocConst => ("associated-consts", "Associated Constants"),
ItemType::ForeignType => ("foreign-types", "Foreign Types"),
ItemType::Keyword => ("keywords", "Keywords"),
ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
ItemType::ProcDerive => ("derives", "Derive Macros"),
ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
}
}
fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
let mut sidebar = String::new();
if items.iter().any(|it| {
it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
}) {
sidebar.push_str(&format!(
"{name} ",
id = "reexports",
name = "Re-exports"
));
}
// ordering taken from item_module, reorder, where it prioritized elements in a certain order
// to print its headings
for &myty in &[
ItemType::Primitive,
ItemType::Module,
ItemType::Macro,
ItemType::Struct,
ItemType::Enum,
ItemType::Constant,
ItemType::Static,
ItemType::Trait,
ItemType::Function,
ItemType::Typedef,
ItemType::Union,
ItemType::Impl,
ItemType::TyMethod,
ItemType::Method,
ItemType::StructField,
ItemType::Variant,
ItemType::AssocType,
ItemType::AssocConst,
ItemType::ForeignType,
ItemType::Keyword,
] {
if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
let (short, name) = item_ty_to_strs(&myty);
sidebar.push_str(&format!(
"{name} ",
id = short,
name = name
));
}
}
if !sidebar.is_empty() {
write!(buf, "{}
", sidebar);
}
}
fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
wrap_into_docblock(w, |w| {
w.write_str(&highlight::render_with_highlighting(
t.source.clone(),
Some("macro"),
None,
None,
))
});
document(w, cx, it)
}
fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
let name = it.name.as_ref().expect("proc-macros always have names");
match m.kind {
MacroKind::Bang => {
write!(w, "");
write!(w, "{}!() {{ /* proc-macro */ }}", name);
write!(w, "
");
}
MacroKind::Attr => {
write!(w, "");
write!(w, "#[{}]", name);
write!(w, "
");
}
MacroKind::Derive => {
write!(w, "");
write!(w, "#[derive({})]", name);
if !m.helpers.is_empty() {
writeln!(w, "\n{{");
writeln!(w, " // Attributes available to this derive:");
for attr in &m.helpers {
writeln!(w, " #[{}]", attr);
}
write!(w, "}}");
}
write!(w, "
");
}
}
document(w, cx, it)
}
fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
document(w, cx, it);
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
}
fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
document(w, cx, it)
}
crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
fn make_item_keywords(it: &clean::Item) -> String {
format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
}
/// Returns a list of all paths used in the type.
/// This is used to help deduplicate imported impls
/// for reexported types. If any of the contained
/// types are re-exported, we don't use the corresponding
/// entry from the js file, as inlining will have already
/// picked up the impl
fn collect_paths_for_type(first_ty: clean::Type) -> Vec {
let mut out = Vec::new();
let mut visited = FxHashSet::default();
let mut work = VecDeque::new();
let cache = cache();
work.push_back(first_ty);
while let Some(ty) = work.pop_front() {
if !visited.insert(ty.clone()) {
continue;
}
match ty {
clean::Type::ResolvedPath { did, .. } => {
let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
if let Some(path) = fqp {
out.push(path.join("::"));
}
}
clean::Type::Tuple(tys) => {
work.extend(tys.into_iter());
}
clean::Type::Slice(ty) => {
work.push_back(*ty);
}
clean::Type::Array(ty, _) => {
work.push_back(*ty);
}
clean::Type::RawPointer(_, ty) => {
work.push_back(*ty);
}
clean::Type::BorrowedRef { type_, .. } => {
work.push_back(*type_);
}
clean::Type::QPath { self_type, trait_, .. } => {
work.push_back(*self_type);
work.push_back(*trait_);
}
_ => {}
}
}
out
}
",
variants.join(""),
));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(buf, " ",
fields
));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(buf, " ",
res.into_iter()
.map(|(name, id)| format!("{}", id, Escape(&name)))
.collect:: ",
types.join("")
));
}
if !consts.is_empty() {
consts.sort();
sidebar.push_str(&format!(
"\
Associated Constants ",
consts.join("")
));
}
if !required.is_empty() {
required.sort();
sidebar.push_str(&format!(
"\
Required Methods ",
required.join("")
));
}
if !provided.is_empty() {
provided.sort();
sidebar.push_str(&format!(
"\
Provided Methods ",
provided.join("")
));
}
let c = cache();
if let Some(implementors) = c.implementors.get(&it.def_id) {
let mut res = implementors
.iter()
.filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
.filter_map(|i| extract_for_impl_name(&i.impl_item))
.collect:: ", concrete_format));
}
if !synthetic_format.is_empty() {
out.push_str(
"\
Auto Trait Implementations",
);
out.push_str(&format!(" ", synthetic_format));
}
if !blanket_format.is_empty() {
out.push_str(
"\
Blanket Implementations",
);
out.push_str(&format!(" ", blanket_format));
}
}
}
out
}
fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
let mut sidebar = String::new();
let fields = get_struct_fields_name(&s.fields);
if !fields.is_empty() {
if let doctree::Plain = s.struct_type {
sidebar.push_str(&format!(
"Fields\
",
fields
));
}
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(buf, " ",
ret.join("")
));
}
}
}
}
let format_impls = |impls: Vec<&Impl>| {
let mut links = FxHashSet::default();
let mut ret = impls
.iter()
.filter_map(|i| {
let is_negative_impl = is_negative_impl(i.inner_impl());
if let Some(ref i) = i.inner_impl().trait_ {
let i_display = format!("{:#}", i.print());
let out = Escape(&i_display);
let encoded = small_url_encode(&format!("{:#}", i.print()));
let generated = format!(
"{}{}",
encoded,
if is_negative_impl { "!" } else { "" },
out
);
if links.insert(generated.clone()) { Some(generated) } else { None }
} else {
None
}
})
.collect:: ",
ret.join("")
));
}
}
if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
if let Some(impl_) = v
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
{
if let Some((target, real_target)) =
impl_.inner_impl().items.iter().find_map(|item| match item.inner {
clean::TypedefItem(ref t, true) => Some(match *t {
clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
_ => (&t.type_, &t.type_),
}),
_ => None,
})
{
let deref_mut = v
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
let inner_impl = target
.def_id()
.or(target
.primitive_type()
.and_then(|prim| c.primitive_locations.get(&prim).cloned()))
.and_then(|did| c.impls.get(&did));
if let Some(impls) = inner_impl {
out.push_str("");
out.push_str(&format!(
"Methods from {}<Target={}>",
Escape(&format!(
"{:#}",
impl_.inner_impl().trait_.as_ref().unwrap().print()
)),
Escape(&format!("{:#}", real_target.print()))
));
out.push_str("");
let mut ret = impls
.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(|i| {
get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
})
.collect::