Crate {}
\Version {}
\Back to index
", crate_name, Escape(version), ) } else { String::new() }; let all = self.all.replace(AllTypes::new()); let v = layout::render( &self.shared.layout, &page, sidebar, |buf: &mut Buffer| all.print(buf), &self.shared.style_files, ); self.shared.fs.write(&final_file, v.as_bytes())?; // Generating settings page. page.title = "Rustdoc settings"; page.description = "Settings of Rustdoc"; page.root_path = "./"; let mut style_files = self.shared.style_files.clone(); let sidebar = "Settings
"; style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false }); let v = layout::render( &self.shared.layout, &page, sidebar, settings( self.shared.static_root_path.as_deref().unwrap_or("./"), &self.shared.resource_suffix, ), &style_files, ); self.shared.fs.write(&settings_file, v.as_bytes())?; Ok(()) } fn mod_item_in( &mut self, item: &clean::Item, item_name: &str, cache: &Cache, ) -> Result<(), Error> { // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also // contain items such as publicly re-exported structures. // // External crates will provide links to these structures, so // these modules are recursed into, but not rendered normally // (a flag on the context). if !self.render_redirect_pages { self.render_redirect_pages = item.is_stripped(); } let scx = &self.shared; self.dst.push(item_name); self.current.push(item_name.to_owned()); info!("Recursing into {}", self.dst.display()); let buf = self.render_item(item, false, cache); // buf will be empty if the module is stripped and there is no redirect for it if !buf.is_empty() { self.shared.ensure_dir(&self.dst)?; let joint_dst = self.dst.join("index.html"); scx.fs.write(&joint_dst, buf.as_bytes())?; } // Render sidebar-items.js used throughout this module. if !self.render_redirect_pages { let module = match item.inner { clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m, _ => unreachable!(), }; let items = self.build_sidebar_items(module); let js_dst = self.dst.join("sidebar-items.js"); let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap()); scx.fs.write(&js_dst, &v)?; } Ok(()) } fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> { info!("Recursed; leaving {}", self.dst.display()); // Go back to where we were at self.dst.pop(); self.current.pop(); Ok(()) } fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> { // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also // contain items such as publicly re-exported structures. // // External crates will provide links to these structures, so // these modules are recursed into, but not rendered normally // (a flag on the context). if !self.render_redirect_pages { self.render_redirect_pages = item.is_stripped(); } let buf = self.render_item(&item, true, cache); // buf will be empty if the item is stripped and there is no redirect for it if !buf.is_empty() { let name = item.name.as_ref().unwrap(); let item_type = item.type_(); let file_name = &item_path(item_type, name); self.shared.ensure_dir(&self.dst)?; let joint_dst = self.dst.join(file_name); self.shared.fs.write(&joint_dst, buf.as_bytes())?; if !self.render_redirect_pages { self.all.borrow_mut().append(full_path(self, &item), &item_type); } // If the item is a macro, redirect from the old macro URL (with !) // to the new one (without). if item_type == ItemType::Macro { let redir_name = format!("{}.{}!.html", item_type, name); let redir_dst = self.dst.join(redir_name); let v = layout::redirect(file_name); self.shared.fs.write(&redir_dst, v.as_bytes())?; } } Ok(()) } } fn write_shared( cx: &Context, krate: &clean::Crate, search_index: String, options: &RenderOptions, cache: &Cache, ) -> Result<(), Error> { // Write out the shared files. Note that these are shared among all rustdoc // docs placed in the output directory, so this needs to be a synchronized // operation with respect to all other rustdocs running around. let lock_file = cx.dst.join(".lock"); let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file); // Add all the static files. These may already exist, but we just // overwrite them anyway to make sure that they're fresh and up-to-date. write_minify( &cx.shared.fs, cx.path("rustdoc.css"), static_files::RUSTDOC_CSS, options.enable_minification, )?; write_minify( &cx.shared.fs, cx.path("settings.css"), static_files::SETTINGS_CSS, options.enable_minification, )?; write_minify( &cx.shared.fs, cx.path("noscript.css"), static_files::NOSCRIPT_CSS, options.enable_minification, )?; // To avoid "light.css" to be overwritten, we'll first run over the received themes and only // then we'll run over the "official" styles. let mut themes: FxHashSetStruct {{ .. }}
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(&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_associated())
&& !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, cx, 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, cx, 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)
{
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::