use clean::AttributesExt;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_middle::middle::stability;
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
use std::cell::{RefCell, RefMut};
use std::cmp::Ordering;
use std::fmt;
use std::rc::Rc;
use super::type_layout::document_type_layout;
use super::{
collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
render_impl, render_rightside, render_stability_since_raw,
render_stability_since_raw_with_extra, AssocItemLink, Context, ImplRenderingParameters,
};
use crate::clean;
use crate::config::ModuleSorting;
use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::{
display_fn, join_with_double_colon, print_abi_with_space, print_constness_with_space,
print_where_clause, visibility_print_with_space, Buffer, Ending, PrintWithSpace,
};
use crate::html::layout::Page;
use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
use crate::html::url_parts_builder::UrlPartsBuilder;
use crate::html::{highlight, static_files};
use askama::Template;
use itertools::Itertools;
macro_rules! item_template {
(
$(#[$meta:meta])*
struct $name:ident<'a, 'cx> {
cx: RefCell<&'a mut Context<'cx>>,
it: &'a clean::Item,
$($field_name:ident: $field_ty:ty),*,
},
methods = [$($methods:tt),* $(,)?]
) => {
#[derive(Template)]
$(#[$meta])*
struct $name<'a, 'cx> {
cx: RefCell<&'a mut Context<'cx>>,
it: &'a clean::Item,
$($field_name: $field_ty),*
}
impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for $name<'a, 'cx> {
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>) {
(&self.it, self.cx.borrow_mut())
}
}
impl<'a, 'cx: 'a> $name<'a, 'cx> {
item_template_methods!($($methods)*);
}
};
}
macro_rules! item_template_methods {
() => {};
(document $($rest:tt)*) => {
fn document<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, mut cx) = self.item_and_mut_cx();
let v = document(*cx, item, None, HeadingOffset::H2);
write!(f, "{v}")
})
}
item_template_methods!($($rest)*);
};
(document_type_layout $($rest:tt)*) => {
fn document_type_layout<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, cx) = self.item_and_mut_cx();
let def_id = item.item_id.expect_def_id();
let v = document_type_layout(*cx, def_id);
write!(f, "{v}")
})
}
item_template_methods!($($rest)*);
};
(render_attributes_in_pre $($rest:tt)*) => {
fn render_attributes_in_pre<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, cx) = self.item_and_mut_cx();
let tcx = cx.tcx();
let v = render_attributes_in_pre(item, "", tcx);
write!(f, "{v}")
})
}
item_template_methods!($($rest)*);
};
(render_assoc_items $($rest:tt)*) => {
fn render_assoc_items<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, mut cx) = self.item_and_mut_cx();
let def_id = item.item_id.expect_def_id();
let v = render_assoc_items(*cx, item, def_id, AssocItemRender::All);
write!(f, "{v}")
})
}
item_template_methods!($($rest)*);
};
($method:ident $($rest:tt)*) => {
compile_error!(concat!("unknown method: ", stringify!($method)));
};
($token:tt $($rest:tt)*) => {
compile_error!(concat!("unexpected token: ", stringify!($token)));
};
}
const ITEM_TABLE_OPEN: &str = "<ul class=\"item-table\">";
const ITEM_TABLE_CLOSE: &str = "</ul>";
const ITEM_TABLE_ROW_OPEN: &str = "<li>";
const ITEM_TABLE_ROW_CLOSE: &str = "</li>";
struct PathComponent {
path: String,
name: Symbol,
}
#[derive(Template)]
#[template(path = "print_item.html")]
struct ItemVars<'a> {
static_root_path: &'a str,
clipboard_svg: &'static static_files::StaticFile,
typ: &'a str,
name: &'a str,
item_type: &'a str,
path_components: Vec<PathComponent>,
stability_since_raw: &'a str,
src_href: Option<&'a str>,
}
fn print_where_clause_and_check<'a, 'tcx: 'a>(
buffer: &mut Buffer,
gens: &'a clean::Generics,
cx: &'a Context<'tcx>,
) -> bool {
let len_before = buffer.len();
write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
len_before != buffer.len()
}
pub(super) fn print_item(
cx: &mut Context<'_>,
item: &clean::Item,
buf: &mut Buffer,
page: &Page<'_>,
) {
debug_assert!(!item.is_stripped());
let typ = match *item.kind {
clean::ModuleItem(_) => {
if item.is_crate() {
"Crate "
} else {
"Module "
}
}
clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
clean::TraitItem(..) => "Trait ",
clean::StructItem(..) => "Struct ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypeAliasItem(..) => "Type Alias ",
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 ",
_ => {
unreachable!();
}
};
let mut stability_since_raw = Buffer::new();
render_stability_since_raw(
&mut stability_since_raw,
item.stable_since(cx.tcx()),
item.const_stability(cx.tcx()),
None,
None,
);
let stability_since_raw: String = stability_since_raw.into_inner();
let src_href =
if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
let path_components = if item.is_primitive() || item.is_keyword() {
vec![]
} else {
let cur = &cx.current;
let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
cur.iter()
.enumerate()
.take(amt)
.map(|(i, component)| PathComponent {
path: "../".repeat(cur.len() - i - 1),
name: *component,
})
.collect()
};
let item_vars = ItemVars {
static_root_path: &page.get_static_root_path(),
clipboard_svg: &static_files::STATIC_FILES.clipboard_svg,
typ,
name: item.name.as_ref().unwrap().as_str(),
item_type: &item.type_().to_string(),
path_components,
stability_since_raw: &stability_since_raw,
src_href: src_href.as_deref(),
};
item_vars.render_into(buf).unwrap();
match &*item.kind {
clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
item_function(buf, cx, item, f)
}
clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
clean::StructItem(ref s) => item_struct(buf, cx, item, s),
clean::UnionItem(ref s) => item_union(buf, cx, item, s),
clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
clean::TypeAliasItem(ref t) => item_type_alias(buf, cx, item, t),
clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
clean::KeywordItem => item_keyword(buf, cx, item),
clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
_ => {
unreachable!();
}
}
if !cx.types_with_notable_traits.is_empty() {
write!(
buf,
r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
notable_traits_json(cx.types_with_notable_traits.iter(), cx)
);
cx.types_with_notable_traits.clear();
}
}
fn should_hide_fields(n_fields: usize) -> bool {
n_fields > 12
}
fn toggle_open(mut w: impl fmt::Write, text: impl fmt::Display) {
write!(
w,
"<details class=\"toggle type-contents-toggle\">\
<summary class=\"hideme\">\
<span>Show {text}</span>\
</summary>",
)
.unwrap();
}
fn toggle_close(mut w: impl fmt::Write) {
w.write_str("</details>").unwrap();
}
trait ItemTemplate<'a, 'cx: 'a>: askama::Template + fmt::Display {
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>);
}
fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
write!(w, "{}", document(cx, item, None, HeadingOffset::H2));
let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
fn reorder(ty: ItemType) -> u8 {
match ty {
ItemType::ExternCrate => 0,
ItemType::Import => 1,
ItemType::Primitive => 2,
ItemType::Module => 3,
ItemType::Macro => 4,
ItemType::Struct => 5,
ItemType::Enum => 6,
ItemType::Constant => 7,
ItemType::Static => 8,
ItemType::Trait => 9,
ItemType::Function => 10,
ItemType::TypeAlias => 12,
ItemType::Union => 13,
_ => 14 + ty as u8,
}
}
fn cmp(
i1: &clean::Item,
i2: &clean::Item,
idx1: usize,
idx2: usize,
tcx: TyCtxt<'_>,
) -> Ordering {
let ty1 = i1.type_();
let ty2 = i2.type_();
if item_ty_to_section(ty1) != item_ty_to_section(ty2)
|| (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
{
return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
}
let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
if let (Some(a), Some(b)) = (s1, s2) {
match (a.is_stable(), b.is_stable()) {
(true, true) | (false, false) => {}
(false, true) => return Ordering::Less,
(true, false) => return Ordering::Greater,
}
}
let lhs = i1.name.unwrap_or(kw::Empty);
let rhs = i2.name.unwrap_or(kw::Empty);
compare_names(lhs.as_str(), rhs.as_str())
}
match cx.shared.module_sorting {
ModuleSorting::Alphabetical => {
indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
}
ModuleSorting::DeclarationOrder => {}
}
indices.dedup_by_key(|i| {
(
items[*i].item_id,
if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
items[*i].type_(),
if items[*i].is_import() { *i } else { 0 },
)
});
debug!("{indices:?}");
let mut last_section = None;
for &idx in &indices {
let myitem = &items[idx];
if myitem.is_stripped() {
continue;
}
let my_section = item_ty_to_section(myitem.type_());
if Some(my_section) != last_section {
if last_section.is_some() {
w.write_str(ITEM_TABLE_CLOSE);
}
last_section = Some(my_section);
write!(
w,
"<h2 id=\"{id}\" class=\"small-section-header\">\
<a href=\"#{id}\">{name}</a>\
</h2>{ITEM_TABLE_OPEN}",
id = cx.derive_id(my_section.id()),
name = my_section.name(),
);
}
let tcx = cx.tcx();
match *myitem.kind {
clean::ExternCrateItem { ref src } => {
use crate::html::format::anchor;
w.write_str(ITEM_TABLE_ROW_OPEN);
match *src {
Some(src) => write!(
w,
"<div class=\"item-name\"><code>{}extern crate {} as {};",
visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
anchor(myitem.item_id.expect_def_id(), src, cx),
myitem.name.unwrap(),
),
None => write!(
w,
"<div class=\"item-name\"><code>{}extern crate {};",
visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
),
}
w.write_str("</code></div>");
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
clean::ImportItem(ref import) => {
let stab_tags = if let Some(import_def_id) = import.source.did {
let ast_attrs = tcx.get_attrs_unchecked(import_def_id);
let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs));
let import_item = clean::Item {
item_id: import_def_id.into(),
attrs: import_attrs,
cfg: ast_attrs.cfg(tcx, &cx.cache().hidden_cfg),
..myitem.clone()
};
let stab_tags = Some(extra_info_tags(&import_item, item, tcx).to_string());
stab_tags
} else {
None
};
w.write_str(ITEM_TABLE_ROW_OPEN);
let id = match import.kind {
clean::ImportKind::Simple(s) => {
format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
}
clean::ImportKind::Glob => String::new(),
};
let stab_tags = stab_tags.unwrap_or_default();
let (stab_tags_before, stab_tags_after) = if stab_tags.is_empty() {
("", "")
} else {
("<div class=\"desc docblock-short\">", "</div>")
};
write!(
w,
"<div class=\"item-name\"{id}>\
<code>{vis}{imp}</code>\
</div>\
{stab_tags_before}{stab_tags}{stab_tags_after}",
vis = visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
imp = import.print(cx),
);
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
_ => {
if myitem.name.is_none() {
continue;
}
let unsafety_flag = match *myitem.kind {
clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
if myitem.fn_header(tcx).unwrap().unsafety == hir::Unsafety::Unsafe =>
{
"<sup title=\"unsafe function\">⚠</sup>"
}
_ => "",
};
let visibility_emoji = match myitem.visibility(tcx) {
Some(ty::Visibility::Restricted(_)) => {
"<span title=\"Restricted Visibility\"> 🔒</span> "
}
_ => "",
};
w.write_str(ITEM_TABLE_ROW_OPEN);
let docs =
MarkdownSummaryLine(&myitem.doc_value(), &myitem.links(cx)).into_string();
let (docs_before, docs_after) = if docs.is_empty() {
("", "")
} else {
("<div class=\"desc docblock-short\">", "</div>")
};
write!(
w,
"<div class=\"item-name\">\
<a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
{visibility_emoji}\
{unsafety_flag}\
{stab_tags}\
</div>\
{docs_before}{docs}{docs_after}",
name = myitem.name.unwrap(),
visibility_emoji = visibility_emoji,
stab_tags = extra_info_tags(myitem, item, tcx),
class = myitem.type_(),
unsafety_flag = unsafety_flag,
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
title = [myitem.type_().to_string(), full_path(cx, myitem)]
.iter()
.filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
.collect::<Vec<_>>()
.join(" "),
);
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
}
}
if last_section.is_some() {
w.write_str(ITEM_TABLE_CLOSE);
}
}
fn extra_info_tags<'a, 'tcx: 'a>(
item: &'a clean::Item,
parent: &'a clean::Item,
tcx: TyCtxt<'tcx>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
display_fn(move |f| {
fn tag_html<'a>(
class: &'a str,
title: &'a str,
contents: &'a str,
) -> impl fmt::Display + 'a {
display_fn(move |f| {
write!(
f,
r#"<span class="stab {class}" title="{title}">{contents}</span>"#,
title = Escape(title),
)
})
}
if let Some(depr) = &item.deprecation(tcx) {
let message = if stability::deprecation_in_effect(depr) {
"Deprecated"
} else {
"Deprecation planned"
};
write!(f, "{}", tag_html("deprecated", "", message))?;
}
if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
== Some(true)
{
write!(f, "{}", tag_html("unstable", "", "Experimental"))?;
}
let cfg = match (&item.cfg, parent.cfg.as_ref()) {
(Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
(cfg, _) => cfg.as_deref().cloned(),
};
debug!(
"Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
name = item.name,
cfg = item.cfg,
parent_cfg = parent.cfg
);
if let Some(ref cfg) = cfg {
write!(
f,
"{}",
tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html())
)
} else {
Ok(())
}
})
}
fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
let tcx = cx.tcx();
let header = it.fn_header(tcx).expect("printing a function which isn't a function");
let constness = print_constness_with_space(&header.constness, it.const_stability(tcx));
let unsafety = header.unsafety.print_with_space();
let abi = print_abi_with_space(header.abi).to_string();
let asyncness = header.asyncness.print_with_space();
let visibility = visibility_print_with_space(it.visibility(tcx), it.item_id, cx).to_string();
let name = it.name.unwrap();
let generics_len = format!("{:#}", f.generics.print(cx)).len();
let header_len = "fn ".len()
+ visibility.len()
+ constness.len()
+ asyncness.len()
+ unsafety.len()
+ abi.len()
+ name.as_str().len()
+ generics_len;
let notable_traits = notable_traits_button(&f.decl.output, cx);
wrap_item(w, |w| {
w.reserve(header_len);
write!(
w,
"{attrs}{vis}{constness}{asyncness}{unsafety}{abi}fn \
{name}{generics}{decl}{notable_traits}{where_clause}",
attrs = render_attributes_in_pre(it, "", tcx),
vis = visibility,
constness = constness,
asyncness = asyncness,
unsafety = unsafety,
abi = abi,
name = name,
generics = f.generics.print(cx),
where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
decl = f.decl.full_print(header_len, 0, cx),
notable_traits = notable_traits.unwrap_or_default(),
);
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
}
fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
let tcx = cx.tcx();
let bounds = bounds(&t.bounds, false, cx);
let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
let count_types = required_types.len() + provided_types.len();
let count_consts = required_consts.len() + provided_consts.len();
let count_methods = required_methods.len() + provided_methods.len();
let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();
wrap_item(w, |mut w| {
write!(
w,
"{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}",
attrs = render_attributes_in_pre(it, "", tcx),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
unsafety = t.unsafety(tcx).print_with_space(),
is_auto = if t.is_auto(tcx) { "auto " } else { "" },
name = it.name.unwrap(),
generics = t.generics.print(cx),
);
if !t.generics.where_predicates.is_empty() {
write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
} else {
w.write_str(" ");
}
if t.items.is_empty() {
w.write_str("{ }");
} else {
w.write_str("{\n");
let mut toggle = false;
if should_hide_fields(count_types) {
toggle = true;
toggle_open(
&mut w,
format_args!("{} associated items", count_types + count_consts + count_methods),
);
}
for types in [&required_types, &provided_types] {
for t in types {
render_assoc_item(
w,
t,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
}
}
if !toggle && should_hide_fields(count_types + count_consts) {
toggle = true;
toggle_open(
&mut w,
format_args!(
"{count_consts} associated constant{plural_const} and \
{count_methods} method{plural_method}",
plural_const = pluralize(count_consts),
plural_method = pluralize(count_methods),
),
);
}
if count_types != 0 && (count_consts != 0 || count_methods != 0) {
w.write_str("\n");
}
for consts in [&required_consts, &provided_consts] {
for c in consts {
render_assoc_item(
w,
c,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
}
}
if !toggle && should_hide_fields(count_methods) {
toggle = true;
toggle_open(&mut w, format_args!("{count_methods} methods"));
}
if count_consts != 0 && count_methods != 0 {
w.write_str("\n");
}
if !required_methods.is_empty() {
write!(w, " // Required method{}\n", pluralize(required_methods.len()));
}
for (pos, m) in required_methods.iter().enumerate() {
render_assoc_item(
w,
m,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
if pos < required_methods.len() - 1 {
w.write_str("<span class=\"item-spacer\"></span>");
}
}
if !required_methods.is_empty() && !provided_methods.is_empty() {
w.write_str("\n");
}
if !provided_methods.is_empty() {
write!(w, " // Provided method{}\n", pluralize(provided_methods.len()));
}
for (pos, m) in provided_methods.iter().enumerate() {
render_assoc_item(
w,
m,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(" { ... }\n");
if pos < provided_methods.len() - 1 {
w.write_str("<span class=\"item-spacer\"></span>");
}
}
if toggle {
toggle_close(&mut w);
}
w.write_str("}");
}
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
write!(
w,
"<h2 id=\"{0}\" class=\"small-section-header\">\
{1}<a href=\"#{0}\" class=\"anchor\">§</a>\
</h2>{2}",
id, title, extra_content
)
}
fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
let name = m.name.unwrap();
info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
let item_type = m.type_();
let id = cx.derive_id(format!("{item_type}.{name}"));
let mut content = Buffer::empty_from(w);
write!(&mut content, "{}", document(cx, m, Some(t), HeadingOffset::H5));
let toggled = !content.is_empty();
if toggled {
let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
}
write!(w, "<section id=\"{id}\" class=\"method\">");
render_rightside(w, cx, m, t, RenderMode::Normal);
write!(w, "<h4 class=\"code-header\">");
render_assoc_item(
w,
m,
AssocItemLink::Anchor(Some(&id)),
ItemType::Impl,
cx,
RenderMode::Normal,
);
w.write_str("</h4>");
w.write_str("</section>");
if toggled {
write!(w, "</summary>");
w.push_buffer(content);
write!(w, "</details>");
}
}
if !required_types.is_empty() {
write_small_section_header(
w,
"required-associated-types",
"Required Associated Types",
"<div class=\"methods\">",
);
for t in required_types {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !provided_types.is_empty() {
write_small_section_header(
w,
"provided-associated-types",
"Provided Associated Types",
"<div class=\"methods\">",
);
for t in provided_types {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !required_consts.is_empty() {
write_small_section_header(
w,
"required-associated-consts",
"Required Associated Constants",
"<div class=\"methods\">",
);
for t in required_consts {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !provided_consts.is_empty() {
write_small_section_header(
w,
"provided-associated-consts",
"Provided Associated Constants",
"<div class=\"methods\">",
);
for t in provided_consts {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
write_small_section_header(
w,
"required-methods",
"Required Methods",
"<div class=\"methods\">",
);
if let Some(list) = must_implement_one_of_functions.as_deref() {
write!(
w,
"<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
list.iter().join("`, `")
);
}
for m in required_methods {
trait_item(w, cx, m, it);
}
w.write_str("</div>");
}
if !provided_methods.is_empty() {
write_small_section_header(
w,
"provided-methods",
"Provided Methods",
"<div class=\"methods\">",
);
for m in provided_methods {
trait_item(w, cx, m, it);
}
w.write_str("</div>");
}
write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All));
let cloned_shared = Rc::clone(&cx.shared);
let cache = &cloned_shared.cache;
let mut extern_crates = FxHashSet::default();
if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
for implementor in implementors {
if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
!did.is_local() {
extern_crates.insert(did.krate);
}
match implementor.inner_impl().for_.without_borrowed_ref() {
clean::Type::Path { ref path } if !path.is_assoc_ty() => {
let did = path.def_id();
let &mut (prev_did, ref mut has_duplicates) =
implementor_dups.entry(path.last()).or_insert((did, false));
if prev_did != did {
*has_duplicates = true;
}
}
_ => {}
}
}
let (local, foreign) =
implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
local.iter().partition(|i| i.inner_impl().kind.is_auto());
synthetic.sort_by_cached_key(|i| ImplString::new(i, cx));
concrete.sort_by_cached_key(|i| ImplString::new(i, cx));
if !foreign.is_empty() {
write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
for implementor in foreign {
let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
let assoc_link =
AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
render_impl(
w,
cx,
implementor,
it,
assoc_link,
RenderMode::Normal,
None,
&[],
ImplRenderingParameters {
show_def_docs: false,
show_default_items: false,
show_non_assoc_items: true,
toggle_open_by_default: false,
},
);
}
}
write_small_section_header(
w,
"implementors",
"Implementors",
"<div id=\"implementors-list\">",
);
for implementor in concrete {
render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
}
w.write_str("</div>");
if t.is_auto(tcx) {
write_small_section_header(
w,
"synthetic-implementors",
"Auto implementors",
"<div id=\"synthetic-implementors-list\">",
);
for implementor in synthetic {
render_implementor(
cx,
implementor,
it,
w,
&implementor_dups,
&collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
);
}
w.write_str("</div>");
}
} else {
write_small_section_header(
w,
"implementors",
"Implementors",
"<div id=\"implementors-list\"></div>",
);
if t.is_auto(tcx) {
write_small_section_header(
w,
"synthetic-implementors",
"Auto implementors",
"<div id=\"synthetic-implementors-list\"></div>",
);
}
}
let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
.take(cx.current.len())
.chain(std::iter::once("implementors"))
.collect();
if let Some(did) = it.item_id.as_def_id() &&
let get_extern = { || cache.external_paths.get(&did).map(|s| &s.0) } &&
let Some(fqp) = cache.exact_paths.get(&did).or_else(get_extern) {
js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
} else {
js_src_path.extend(cx.current.iter().copied());
js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
}
let extern_crates = extern_crates
.into_iter()
.map(|cnum| tcx.crate_name(cnum).to_string())
.collect::<Vec<_>>()
.join(",");
let (extern_before, extern_after) =
if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
write!(
w,
"<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
src = js_src_path.finish(),
);
}
fn item_trait_alias(
w: &mut impl fmt::Write,
cx: &mut Context<'_>,
it: &clean::Item,
t: &clean::TraitAlias,
) {
wrap_item(w, |w| {
write!(
w,
"{attrs}trait {name}{generics}{where_b} = {bounds};",
attrs = render_attributes_in_pre(it, "", cx.tcx()),
name = it.name.unwrap(),
generics = t.generics.print(cx),
where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds = bounds(&t.bounds, true, cx),
)
.unwrap();
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All))
.unwrap();
}
fn item_opaque_ty(
w: &mut impl fmt::Write,
cx: &mut Context<'_>,
it: &clean::Item,
t: &clean::OpaqueTy,
) {
wrap_item(w, |w| {
write!(
w,
"{attrs}type {name}{generics}{where_clause} = impl {bounds};",
attrs = render_attributes_in_pre(it, "", cx.tcx()),
name = it.name.unwrap(),
generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds = bounds(&t.bounds, false, cx),
)
.unwrap();
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All))
.unwrap();
}
fn item_type_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TypeAlias) {
fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TypeAlias) {
wrap_item(w, |w| {
write!(
w,
"{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
attrs = render_attributes_in_pre(it, "", cx.tcx()),
vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
name = it.name.unwrap(),
generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
type_ = t.type_.print(cx),
);
});
}
write_content(w, cx, it, t);
write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
if let Some(inner_type) = &t.inner_type {
write!(
w,
"<h2 id=\"aliased-type\" class=\"small-section-header\">\
Aliased Type<a href=\"#aliased-type\" class=\"anchor\">§</a></h2>"
);
match inner_type {
clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive } => {
let variants_iter = || variants.iter().filter(|i| !i.is_stripped());
wrap_item(w, |w| {
let variants_len = variants.len();
let variants_count = variants_iter().count();
let has_stripped_entries = variants_len != variants_count;
write!(w, "enum {}{}", it.name.unwrap(), t.generics.print(cx));
render_enum_fields(
w,
cx,
Some(&t.generics),
variants_iter(),
variants_count,
has_stripped_entries,
*is_non_exhaustive,
)
});
item_variants(w, cx, it, variants_iter());
}
clean::TypeAliasInnerType::Union { fields } => {
wrap_item(w, |w| {
let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
let has_stripped_fields = fields.len() != fields_count;
write!(w, "union {}{}", it.name.unwrap(), t.generics.print(cx));
render_struct_fields(
w,
Some(&t.generics),
None,
fields,
"",
true,
has_stripped_fields,
cx,
);
});
item_fields(w, cx, it, fields, None);
}
clean::TypeAliasInnerType::Struct { ctor_kind, fields } => {
wrap_item(w, |w| {
let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
let has_stripped_fields = fields.len() != fields_count;
write!(w, "struct {}{}", it.name.unwrap(), t.generics.print(cx));
render_struct_fields(
w,
Some(&t.generics),
*ctor_kind,
fields,
"",
true,
has_stripped_fields,
cx,
);
});
item_fields(w, cx, it, fields, None);
}
}
}
let def_id = it.item_id.expect_def_id();
write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
write!(w, "{}", document_type_layout(cx, def_id));
}
fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
item_template!(
#[template(path = "item_union.html")]
struct ItemUnion<'a, 'cx> {
cx: RefCell<&'a mut Context<'cx>>,
it: &'a clean::Item,
s: &'a clean::Union,
},
methods = [document, document_type_layout, render_attributes_in_pre, render_assoc_items]
);
impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
fn render_union<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let cx = self.cx.borrow_mut();
let v = render_union(self.it, Some(&self.s.generics), &self.s.fields, *cx);
write!(f, "{v}")
})
}
fn document_field<'b>(
&'b self,
field: &'a clean::Item,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let mut cx = self.cx.borrow_mut();
let v = document(*cx, field, Some(self.it), HeadingOffset::H3);
write!(f, "{v}")
})
}
fn stability_field(&self, field: &clean::Item) -> Option<String> {
let cx = self.cx.borrow();
field.stability_class(cx.tcx())
}
fn print_ty<'b>(
&'b self,
ty: &'a clean::Type,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let cx = self.cx.borrow();
let v = ty.print(*cx);
write!(f, "{v}")
})
}
fn fields_iter(
&self,
) -> std::iter::Peekable<impl Iterator<Item = (&'a clean::Item, &'a clean::Type)>> {
self.s
.fields
.iter()
.filter_map(|f| match *f.kind {
clean::StructFieldItem(ref ty) => Some((f, ty)),
_ => None,
})
.peekable()
}
}
ItemUnion { cx: RefCell::new(cx), it, s }.render_into(w).unwrap();
}
fn print_tuple_struct_fields<'a, 'cx: 'a>(
cx: &'a Context<'cx>,
s: &'a [clean::Item],
) -> impl fmt::Display + 'a + Captures<'cx> {
display_fn(|f| {
if s.iter()
.all(|field| matches!(*field.kind, clean::StrippedItem(box clean::StructFieldItem(..))))
{
return f.write_str("/* private fields */");
}
for (i, ty) in s.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
match *ty.kind {
clean::StrippedItem(box clean::StructFieldItem(_)) => f.write_str("_")?,
clean::StructFieldItem(ref ty) => write!(f, "{}", ty.print(cx))?,
_ => unreachable!(),
}
}
Ok(())
})
}
fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
let tcx = cx.tcx();
let count_variants = e.variants().count();
wrap_item(w, |w| {
render_attributes_in_code(w, it, tcx);
write!(
w,
"{}enum {}{}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
it.name.unwrap(),
e.generics.print(cx),
);
render_enum_fields(
w,
cx,
Some(&e.generics),
e.variants(),
count_variants,
e.has_stripped_entries(),
it.is_non_exhaustive(),
);
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
if count_variants != 0 {
item_variants(w, cx, it, e.variants());
}
let def_id = it.item_id.expect_def_id();
write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
write!(w, "{}", document_type_layout(cx, def_id));
}
fn render_enum_fields<'a>(
mut w: &mut Buffer,
cx: &mut Context<'_>,
g: Option<&clean::Generics>,
variants: impl Iterator<Item = &'a clean::Item>,
count_variants: usize,
has_stripped_entries: bool,
is_non_exhaustive: bool,
) {
if !g.is_some_and(|g| print_where_clause_and_check(w, g, cx)) {
w.write_str(" ");
}
let variants_stripped = has_stripped_entries;
if count_variants == 0 && !variants_stripped {
w.write_str("{}");
} else {
w.write_str("{\n");
let toggle = should_hide_fields(count_variants);
if toggle {
toggle_open(&mut w, format_args!("{count_variants} variants"));
}
const TAB: &str = " ";
for v in variants {
w.write_str(TAB);
let name = v.name.unwrap();
match *v.kind {
clean::VariantItem(ref var) => match var.kind {
clean::VariantKind::CLike => w.write_str(name.as_str()),
clean::VariantKind::Tuple(ref s) => {
write!(w, "{name}({})", print_tuple_struct_fields(cx, s),);
}
clean::VariantKind::Struct(ref s) => {
render_struct(w, v, None, None, &s.fields, TAB, false, cx);
}
},
_ => unreachable!(),
}
w.write_str(",\n");
}
if variants_stripped && !is_non_exhaustive {
w.write_str(" // some variants omitted\n");
}
if toggle {
toggle_close(&mut w);
}
w.write_str("}");
}
}
fn item_variants<'a>(
w: &mut Buffer,
cx: &mut Context<'_>,
it: &clean::Item,
variants: impl Iterator<Item = &'a clean::Item>,
) {
let tcx = cx.tcx();
write!(
w,
"<h2 id=\"variants\" class=\"variants small-section-header\">\
Variants{}<a href=\"#variants\" class=\"anchor\">§</a>\
</h2>\
{}\
<div class=\"variants\">",
document_non_exhaustive_header(it),
document_non_exhaustive(it)
);
for variant in variants {
let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
write!(
w,
"<section id=\"{id}\" class=\"variant\">\
<a href=\"#{id}\" class=\"anchor\">§</a>",
);
render_stability_since_raw_with_extra(
w,
variant.stable_since(tcx),
variant.const_stability(tcx),
it.stable_since(tcx),
it.const_stable_since(tcx),
" rightside",
);
write!(w, "<h3 class=\"code-header\">{name}", name = variant.name.unwrap());
let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
write!(w, "({})", print_tuple_struct_fields(cx, s));
}
w.write_str("</h3></section>");
let heading_and_fields = match &variant_data.kind {
clean::VariantKind::Struct(s) => Some(("Fields", &s.fields)),
clean::VariantKind::Tuple(fields) => {
if fields.iter().any(|f| !f.doc_value().is_empty()) {
Some(("Tuple Fields", fields))
} else {
None
}
}
clean::VariantKind::CLike => None,
};
if let Some((heading, fields)) = heading_and_fields {
let variant_id =
cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
write!(
w,
"<div class=\"sub-variant\" id=\"{variant_id}\">\
<h4>{heading}</h4>\
{}",
document_non_exhaustive(variant)
);
for field in fields {
match *field.kind {
clean::StrippedItem(box clean::StructFieldItem(_)) => {}
clean::StructFieldItem(ref ty) => {
let id = cx.derive_id(format!(
"variant.{}.field.{}",
variant.name.unwrap(),
field.name.unwrap()
));
write!(
w,
"<div class=\"sub-variant-field\">\
<span id=\"{id}\" class=\"small-section-header\">\
<a href=\"#{id}\" class=\"anchor field\">§</a>\
<code>{f}: {t}</code>\
</span>",
f = field.name.unwrap(),
t = ty.print(cx),
);
write!(
w,
"{}</div>",
document(cx, field, Some(variant), HeadingOffset::H5)
);
}
_ => unreachable!(),
}
}
w.write_str("</div>");
}
write!(w, "{}", document(cx, variant, Some(it), HeadingOffset::H4));
}
write!(w, "</div>");
}
fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
highlight::render_item_decl_with_highlighting(&t.source, w);
write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
}
fn item_proc_macro(
w: &mut impl fmt::Write,
cx: &mut Context<'_>,
it: &clean::Item,
m: &clean::ProcMacro,
) {
wrap_item(w, |buffer| {
let name = it.name.expect("proc-macros always have names");
match m.kind {
MacroKind::Bang => {
write!(buffer, "{name}!() {{ /* proc-macro */ }}").unwrap();
}
MacroKind::Attr => {
write!(buffer, "#[{name}]").unwrap();
}
MacroKind::Derive => {
write!(buffer, "#[derive({name})]").unwrap();
if !m.helpers.is_empty() {
buffer.write_str("\n{\n // Attributes available to this derive:\n").unwrap();
for attr in &m.helpers {
writeln!(buffer, " #[{attr}]").unwrap();
}
buffer.write_str("}\n").unwrap();
}
}
}
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
}
fn item_primitive(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item) {
let def_id = it.item_id.expect_def_id();
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All)).unwrap();
} else {
let shared = Rc::clone(&cx.shared);
let (concrete, synthetic, blanket_impl) = get_filtered_impls_for_reference(&shared, it);
render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
}
}
fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
wrap_item(w, |w| {
let tcx = cx.tcx();
render_attributes_in_code(w, it, tcx);
write!(
w,
"{vis}const {name}{generics}: {typ}{where_clause}",
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
name = it.name.unwrap(),
generics = c.generics.print(cx),
typ = c.type_.print(cx),
where_clause = print_where_clause(&c.generics, cx, 0, Ending::NoNewline),
);
let value = c.value(tcx);
let is_literal = c.is_literal(tcx);
let expr = c.expr(tcx);
if value.is_some() || is_literal {
write!(w, " = {expr};", expr = Escape(&expr));
} else {
w.write_str(";");
}
if !is_literal {
if let Some(value) = &value {
let value_lowercase = value.to_lowercase();
let expr_lowercase = 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(cx, it, None, HeadingOffset::H2))
}
fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
wrap_item(w, |w| {
render_attributes_in_code(w, it, cx.tcx());
render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
item_fields(w, cx, it, &s.fields, s.ctor_kind);
let def_id = it.item_id.expect_def_id();
write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
write!(w, "{}", document_type_layout(cx, def_id));
}
fn item_fields(
w: &mut Buffer,
cx: &mut Context<'_>,
it: &clean::Item,
fields: &Vec<clean::Item>,
ctor_kind: Option<CtorKind>,
) {
let mut fields = fields
.iter()
.filter_map(|f| match *f.kind {
clean::StructFieldItem(ref ty) => Some((f, ty)),
_ => None,
})
.peekable();
if let None | Some(CtorKind::Fn) = ctor_kind {
if fields.peek().is_some() {
write!(
w,
"<h2 id=\"fields\" class=\"fields small-section-header\">\
{}{}<a href=\"#fields\" class=\"anchor\">§</a>\
</h2>\
{}",
if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
document_non_exhaustive_header(it),
document_non_exhaustive(it)
);
for (index, (field, ty)) in fields.enumerate() {
let field_name =
field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField));
write!(
w,
"<span id=\"{id}\" class=\"{item_type} small-section-header\">\
<a href=\"#{id}\" class=\"anchor field\">§</a>\
<code>{field_name}: {ty}</code>\
</span>",
item_type = ItemType::StructField,
ty = ty.print(cx)
);
write!(w, "{}", document(cx, field, Some(it), HeadingOffset::H3));
}
}
}
}
fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
wrap_item(w, |buffer| {
render_attributes_in_code(buffer, it, cx.tcx());
write!(
buffer,
"{vis}static {mutability}{name}: {typ}",
vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
mutability = s.mutability.print_with_space(),
name = it.name.unwrap(),
typ = s.type_.print(cx)
)
.unwrap();
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
}
fn item_foreign_type(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item) {
wrap_item(w, |buffer| {
buffer.write_str("extern {\n").unwrap();
render_attributes_in_code(buffer, it, cx.tcx());
write!(
buffer,
" {}type {};\n}}",
visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
it.name.unwrap(),
)
.unwrap();
});
write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All))
.unwrap();
}
fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
}
pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
let i = s.find(|c: char| c.is_ascii_digit());
let (a, b) = s.split_at(i.unwrap_or(s.len()));
let i = b.find(|c: char| !c.is_ascii_digit());
let (b, c) = b.split_at(i.unwrap_or(b.len()));
*s = c;
(a, b)
}
while !lhs.is_empty() || !rhs.is_empty() {
let (la, lb) = take_parts(&mut lhs);
let (ra, rb) = take_parts(&mut rhs);
match la.cmp(ra) {
Ordering::Equal => (),
x => return x,
}
if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
match ln.cmp(&rn) {
Ordering::Equal => (),
x => return x,
}
}
match lb.cmp(rb) {
Ordering::Equal => (),
x => return x,
}
}
Ordering::Equal
}
pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
let mut s = join_with_double_colon(&cx.current);
s.push_str("::");
s.push_str(item.name.unwrap().as_str());
s
}
pub(super) fn item_path(ty: ItemType, name: &str) -> String {
match ty {
ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
_ => format!("{ty}.{name}.html"),
}
}
fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
let mut bounds = String::new();
if !t_bounds.is_empty() {
if !trait_alias {
bounds.push_str(": ");
}
for (i, p) in t_bounds.iter().enumerate() {
if i > 0 {
bounds.push_str(" + ");
}
bounds.push_str(&p.print(cx).to_string());
}
}
bounds
}
fn wrap_item<W, F>(w: &mut W, f: F)
where
W: fmt::Write,
F: FnOnce(&mut W),
{
write!(w, r#"<pre class="rust item-decl"><code>"#).unwrap();
f(w);
write!(w, "</code></pre>").unwrap();
}
#[derive(PartialEq, Eq)]
struct ImplString(String);
impl ImplString {
fn new(i: &Impl, cx: &Context<'_>) -> ImplString {
ImplString(format!("{}", i.inner_impl().print(false, cx)))
}
}
impl PartialOrd for ImplString {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(Ord::cmp(self, other))
}
}
impl Ord for ImplString {
fn cmp(&self, other: &Self) -> Ordering {
compare_names(&self.0, &other.0)
}
}
fn render_implementor(
cx: &mut Context<'_>,
implementor: &Impl,
trait_: &clean::Item,
w: &mut Buffer,
implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
aliases: &[String],
) {
let use_absolute = match implementor.inner_impl().for_ {
clean::Type::Path { ref path, .. }
| clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
if !path.is_assoc_ty() =>
{
implementor_dups[&path.last()].1
}
_ => false,
};
render_impl(
w,
cx,
implementor,
trait_,
AssocItemLink::Anchor(None),
RenderMode::Normal,
Some(use_absolute),
aliases,
ImplRenderingParameters {
show_def_docs: false,
show_default_items: false,
show_non_assoc_items: false,
toggle_open_by_default: false,
},
);
}
fn render_union<'a, 'cx: 'a>(
it: &'a clean::Item,
g: Option<&'a clean::Generics>,
fields: &'a [clean::Item],
cx: &'a Context<'cx>,
) -> impl fmt::Display + 'a + Captures<'cx> {
display_fn(move |mut f| {
let tcx = cx.tcx();
write!(
f,
"{}union {}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
it.name.unwrap(),
)?;
let where_displayed = g
.map(|g| {
let mut buf = Buffer::html();
write!(buf, "{}", g.print(cx));
let where_displayed = print_where_clause_and_check(&mut buf, g, cx);
write!(f, "{buf}", buf = buf.into_inner()).unwrap();
where_displayed
})
.unwrap_or(false);
if !where_displayed {
f.write_str(" ")?;
}
write!(f, "{{\n")?;
let count_fields =
fields.iter().filter(|field| matches!(*field.kind, clean::StructFieldItem(..))).count();
let toggle = should_hide_fields(count_fields);
if toggle {
toggle_open(&mut f, format_args!("{count_fields} fields"));
}
for field in fields {
if let clean::StructFieldItem(ref ty) = *field.kind {
write!(
f,
" {}{}: {},\n",
visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
field.name.unwrap(),
ty.print(cx)
)?;
}
}
if it.has_stripped_entries().unwrap() {
write!(f, " /* private fields */\n")?;
}
if toggle {
toggle_close(&mut f);
}
f.write_str("}").unwrap();
Ok(())
})
}
fn render_struct(
w: &mut Buffer,
it: &clean::Item,
g: Option<&clean::Generics>,
ty: Option<CtorKind>,
fields: &[clean::Item],
tab: &str,
structhead: bool,
cx: &Context<'_>,
) {
let tcx = cx.tcx();
write!(
w,
"{}{}{}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
if structhead { "struct " } else { "" },
it.name.unwrap()
);
if let Some(g) = g {
write!(w, "{}", g.print(cx))
}
render_struct_fields(
w,
g,
ty,
fields,
tab,
structhead,
it.has_stripped_entries().unwrap_or(false),
cx,
)
}
fn render_struct_fields(
mut w: &mut Buffer,
g: Option<&clean::Generics>,
ty: Option<CtorKind>,
fields: &[clean::Item],
tab: &str,
structhead: bool,
has_stripped_entries: bool,
cx: &Context<'_>,
) {
let tcx = cx.tcx();
match ty {
None => {
let where_displayed =
g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);
if !where_displayed {
w.write_str(" {");
} else {
w.write_str("{");
}
let count_fields =
fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
let has_visible_fields = count_fields > 0;
let toggle = should_hide_fields(count_fields);
if toggle {
toggle_open(&mut w, format_args!("{count_fields} fields"));
}
for field in fields {
if let clean::StructFieldItem(ref ty) = *field.kind {
write!(
w,
"\n{tab} {vis}{name}: {ty},",
vis = visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
name = field.name.unwrap(),
ty = ty.print(cx),
);
}
}
if has_visible_fields {
if has_stripped_entries {
write!(w, "\n{tab} /* private fields */");
}
write!(w, "\n{tab}");
} else if has_stripped_entries {
write!(w, " /* private fields */ ");
}
if toggle {
toggle_close(&mut w);
}
w.write_str("}");
}
Some(CtorKind::Fn) => {
w.write_str("(");
if fields.iter().all(|field| {
matches!(*field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
}) {
write!(w, "/* private fields */");
} else {
for (i, field) in fields.iter().enumerate() {
if i > 0 {
w.write_str(", ");
}
match *field.kind {
clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
clean::StructFieldItem(ref ty) => {
write!(
w,
"{}{}",
visibility_print_with_space(
field.visibility(tcx),
field.item_id,
cx
),
ty.print(cx),
)
}
_ => unreachable!(),
}
}
}
w.write_str(")");
if let Some(g) = g {
write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
}
if structhead {
w.write_str(";");
}
}
Some(CtorKind::Const) => {
if let Some(g) = g {
write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
}
w.write_str(";");
}
}
}
fn document_non_exhaustive_header(item: &clean::Item) -> &str {
if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
}
fn document_non_exhaustive<'a>(item: &'a clean::Item) -> impl fmt::Display + 'a {
display_fn(|f| {
if item.is_non_exhaustive() {
write!(
f,
"<details class=\"toggle non-exhaustive\">\
<summary class=\"hideme\"><span>{}</span></summary>\
<div class=\"docblock\">",
{
if item.is_struct() {
"This struct is marked as non-exhaustive"
} else if item.is_enum() {
"This enum is marked as non-exhaustive"
} else if item.is_variant() {
"This variant is marked as non-exhaustive"
} else {
"This type is marked as non-exhaustive"
}
}
)?;
if item.is_struct() {
f.write_str(
"Non-exhaustive structs could have additional fields added in future. \
Therefore, non-exhaustive structs cannot be constructed in external crates \
using the traditional <code>Struct { .. }</code> syntax; cannot be \
matched against without a wildcard <code>..</code>; and \
struct update syntax will not work.",
)?;
} else if item.is_enum() {
f.write_str(
"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() {
f.write_str(
"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 {
f.write_str(
"This type will require a wildcard arm in any match statements or constructors.",
)?;
}
f.write_str("</div></details>")?;
}
Ok(())
})
}
fn pluralize(count: usize) -> &'static str {
if count > 1 { "s" } else { "" }
}