Crate {}
\Version {}
\Back to index
", crate_name, version) } else { String::new() }; let v = layout::render(&self.shared.layout, &page, sidebar, |buf: &mut Buffer| all.print(buf), &self.shared.themes); self.shared.fs.write(&final_file, v.as_bytes())?; // Generating settings page. page.title = "Rustdoc settings"; page.description = "Settings of Rustdoc"; page.root_path = "./"; let mut themes = self.shared.themes.clone(); let sidebar = "Settings
"; themes.push(PathBuf::from("settings.css")); let v = layout::render( &self.shared.layout, &page, sidebar, settings( self.shared.static_root_path.as_deref().unwrap_or("./"), &self.shared.resource_suffix ), &themes); self.shared.fs.write(&settings_file, v.as_bytes())?; Ok(()) } fn render_item(&self, it: &clean::Item, pushname: bool) -> String { // A little unfortunate that this is done like this, but it sure // does make formatting *a lot* nicer. CURRENT_DEPTH.with(|slot| { slot.set(self.current.len()); }); let mut title = if it.is_primitive() || it.is_keyword() { // No need to include the namespace for primitive types and keywords String::new() } else { self.current.join("::") }; if pushname { if !title.is_empty() { title.push_str("::"); } title.push_str(it.name.as_ref().unwrap()); } title.push_str(" - Rust"); let tyname = it.type_(); let desc = if it.is_crate() { format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) } else { format!("API documentation for the Rust `{}` {} in crate `{}`.", it.name.as_ref().unwrap(), tyname, self.shared.layout.krate) }; let keywords = make_item_keywords(it); let page = layout::Page { css_class: tyname.as_str(), root_path: &self.root_path(), static_root_path: self.shared.static_root_path.as_deref(), title: &title, description: &desc, keywords: &keywords, resource_suffix: &self.shared.resource_suffix, extra_scripts: &[], static_extra_scripts: &[], }; { self.id_map.borrow_mut().reset(); self.id_map.borrow_mut().populate(initial_ids()); } if !self.render_redirect_pages { layout::render(&self.shared.layout, &page, |buf: &mut _| print_sidebar(self, it, buf), |buf: &mut _| print_item(self, it, buf), &self.shared.themes) } else { let mut url = self.root_path(); if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) { for name in &names[..names.len() - 1] { url.push_str(name); url.push_str("/"); } url.push_str(&item_path(ty, names.last().unwrap())); layout::redirect(&url) } else { String::new() } } } /// Non-parallelized version of rendering an item. This will take the input /// item, render its contents, and then invoke the specified closure with /// all sub-items which need to be rendered. /// /// The rendering driver uses this closure to queue up more work. fn itemStruct {{ .. }}
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 {};",
VisSpace(&myitem.visibility),
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 {
// Provide a more informative message than the compiler help.
let unstable_reason = if is_rustc_private {
"This crate is being loaded from the sysroot, a permanently unstable location \
for private compiler dependencies. It is not intended for general use. Prefer \
using a public version of this crate from \
[crates.io](https://crates.io) via [`Cargo.toml`]\
(https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
} else {
unstable_reason
};
let mut ids = cx.id_map.borrow_mut();
message = format!(
""); render_attributes(w, it, false); write!(w, "{vis}const \ {name}: {typ}", vis = VisSpace(&it.visibility), name = it.name.as_ref().unwrap(), typ = c.type_.print()); document(w, cx, it) } fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) { write!(w, "
"); render_attributes(w, it, false); write!(w, "{vis}static {mutability}\ {name}: {typ}", vis = VisSpace(&it.visibility), mutability = MutableSpace(s.mutability), 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 {}{:#}", VisSpace(&it.visibility), ConstnessSpace(f.header.constness), UnsafetySpace(f.header.unsafety), AsyncSpace(f.header.asyncness), AbiSpace(f.header.abi), it.name.as_ref().unwrap(), f.generics.print() ).len(); write!(w, "{}
", render_spotlight_traits(it)); render_attributes(w, it, false); write!(w, "{vis}{constness}{unsafety}{asyncness}{abi}fn \ {name}{generics}{decl}{where_clause}", vis = VisSpace(&it.visibility), constness = ConstnessSpace(f.header.constness), unsafety = UnsafetySpace(f.header.unsafety), asyncness = AsyncSpace(f.header.asyncness), abi = AbiSpace(f.header.abi), name = it.name.as_ref().unwrap(), generics = f.generics.print(), where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true }, decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness, }.print()); document(w, cx, it) } fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer, implementor_dups: &FxHashMap<&str, (DefId, bool)>) { // 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); } fn render_impls(cx: &Context, w: &mut Buffer, traits: &[&&Impl], containing_item: &clean::Item) { for i in traits { let did = i.trait_did().unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods); render_impl(w, cx, i, assoc_link, RenderMode::Normal, containing_item.stable_since(), true, None, false, true); } } fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> 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().to_string()); } } bounds } fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering { let lhs = format!("{}", lhs.inner_impl().print()); let rhs = format!("{}", rhs.inner_impl().print()); // lhs and rhs are formatted as HTML, which may be unnecessary name_key(&lhs).cmp(&name_key(&rhs)) } fn item_trait( w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, ) { let bounds = bounds(&t.bounds, false); let types = t.items.iter().filter(|m| m.is_associated_type()).collect::
"); render_attributes(w, it, true); write!(w, "{}{}{}trait {}{}{}", VisSpace(&it.visibility), UnsafetySpace(t.unsafety), 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, "
",
extra = render_spotlight_traits(m),
id = id,
ns_id = ns_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,
ns_id = ns_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)
}
fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) {
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)
}
fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
wrap_into_docblock(w, |w| {
write!(w, ""); render_attributes(w, it, true); write!(w, "{}enum {}{}{}", VisSpace(&it.visibility), 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,
ns_id = ns_id,
name = variant.name.as_ref().unwrap());
if let clean::VariantItem(ref var) = variant.inner {
if let clean::VariantKind::Tuple(ref tys) = var.kind {
write!(w, "(");
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
write!(w, ", ");
}
write!(w, "{}", ty.print());
}
write!(w, ")");
}
}
write!(w, "
{f}: {t}\
",
id = id,
ns_id = ns_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, &format!("ⓘ\
Important traits for {}\
",
trait_));
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) {
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(),
});
if let Some(use_absolute) = use_absolute {
write!(w, "", id);
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, &vec![], Some(&tydef.type_),
AssocItemLink::Anchor(None),
"");
write!(w, ";");
}
}
}
write!(w, "
");
} else {
write!(w, "{}
",
id, 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) {
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.codes, cx.edition, &cx.playground).to_string());
}
}
fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item,
link: AssocItemLink<'_>, render_mode: RenderMode,
is_default_item: bool, outer_version: Option<&str>,
trait_: Option<&clean::Trait>, show_def_docs: bool) {
let item_type = item.type_();
let name = item.name.as_ref().unwrap();
let render_method_item: bool = 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 { ref decl, .. }) |
clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
// Only render when the method is not static or we allow static methods
if render_method_item {
let id = cx.derive_id(format!("{}.{}", item_type, name));
let ns_id = cx.derive_id(format!("{}.{}",
name, item_type.name_space()));
write!(w, "",
id, item_type, extra_class);
write!(w, "{}", spotlight_decl(decl));
write!(w, "", ns_id);
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) {
write!(w, "[src]",
l, "goto source code");
}
write!(w, "
");
}
}
clean::TypedefItem(ref tydef, _) => {
let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "", id, item_type, extra_class);
write!(w, "", ns_id);
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));
let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "", id, item_type, extra_class);
write!(w, "", ns_id);
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) {
write!(w, "[src]",
l, "goto source code");
}
write!(w, "
");
}
clean::AssocTypeItem(ref bounds, ref default) => {
let id = cx.derive_id(format!("{}.{}", item_type, name));
let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "", id, item_type, extra_class);
write!(w, "", ns_id);
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 || render_mode == RenderMode::Normal {
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);
}
fn render_default_items(w: &mut Buffer,
cx: &Context,
t: &clean::Trait,
i: &clean::Impl,
render_mode: RenderMode,
outer_version: Option<&str>,
show_def_docs: bool) {
for trait_item in &t.items {
let n = trait_item.name.clone();
if i.items.iter().find(|m| m.name == n).is_some() {
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);
}
}
// 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);
}
}
write!(w, "");
}
fn item_opaque_ty(
w: &mut Buffer,
cx: &Context,
it: &clean::Item,
t: &clean::OpaqueTy,
) {
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)
}
fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item,
t: &clean::TraitAlias) {
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)
}
fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) {
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)
}
fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) {
writeln!(w, "extern {{");
render_attributes(w, it, false);
write!(
w,
" {}type {};\n}}
",
VisSpace(&it.visibility),
it.name.as_ref().unwrap(),
);
document(w, cx, it);
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) {
let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
|| it.is_enum() || it.is_mod() || it.is_typedef() {
write!(buffer, "
{}{}
",
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 {}
\
",
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)) == false {
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 = Rc::new(RefCell::new(&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,
&mut used_links_bor.borrow_mut(), false))
.collect::>();
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
if !ret.is_empty() {
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 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 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() {
sidebar.push_str(&format!("\
Associated Types>();
if !res.is_empty() {
res.sort();
sidebar.push_str(&format!("\
Implementations on Foreign Types{}", sidebar)
}
fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item, _p: &clean::PrimitiveType) {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item, _t: &clean::Typedef) {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn get_struct_fields_name(fields: &[clean::Item]) -> String {
fields.iter()
.filter(|f| if let clean::StructFieldItem(..) = f.inner {
true
} else {
false
})
.filter_map(|f| match f.name {
Some(ref name) => Some(format!("\
{name}", name=name)),
_ => None,
})
.collect()
}
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\
", fields));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(buf, "{}", sidebar);
}
}
fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
let mut sidebar = String::new();
let variants = e.variants.iter()
.filter_map(|v| match v.name {
Some(ref name) => Some(format!("{name}\
", name = name)),
_ => None,
})
.collect::();
if !variants.is_empty() {
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, _it: &clean::Item, 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,
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,
_p: &clean::PrimitiveType) {
document(w, cx, it);
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_keyword(w: &mut Buffer, cx: &Context,
it: &clean::Item,
_p: &str) {
document(w, cx, it)
}
crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
fn make_item_keywords(it: &clean::Item) -> String {
format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
}
fn get_index_search_type(item: &clean::Item) -> Option {
let (all_types, ret_types) = match item.inner {
clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
_ => return None,
};
let inputs = all_types.iter().map(|arg| {
get_index_type(&arg)
}).filter(|a| a.name.is_some()).collect();
let output = ret_types.iter().map(|arg| {
get_index_type(&arg)
}).filter(|a| a.name.is_some()).collect::>();
let output = if output.is_empty() {
None
} else {
Some(output)
};
Some(IndexItemFunctionType { inputs, output })
}
fn get_index_type(clean_type: &clean::Type) -> Type {
let t = Type {
name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
generics: get_generics(clean_type),
};
t
}
/// 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);
match fqp {
Some(path) => {
out.push(path.join("::"));
},
_ => {}
};
},
clean::Type::Tuple(tys) => {
work.extend(tys.into_iter());
},
clean::Type::Slice(ty) => {
work.push_back(*ty);
}
clean::Type::Array(ty, _) => {
work.push_back(*ty);
},
clean::Type::RawPointer(_, ty) => {
work.push_back(*ty);
},
clean::Type::BorrowedRef { type_, .. } => {
work.push_back(*type_);
},
clean::Type::QPath { self_type, trait_, .. } => {
work.push_back(*self_type);
work.push_back(*trait_);
},
_ => {}
}
};
out
}
fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option {
match *clean_type {
clean::ResolvedPath { ref path, .. } => {
let segments = &path.segments;
let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
"get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
clean_type, accept_generic
));
Some(path_segment.name.clone())
}
clean::Generic(ref s) if accept_generic => Some(s.clone()),
clean::Primitive(ref p) => Some(format!("{:?}", p)),
clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
// FIXME: add all from clean::Type.
_ => None
}
}
fn get_generics(clean_type: &clean::Type) -> Option> {
clean_type.generics()
.and_then(|types| {
let r = types.iter()
.filter_map(|t| get_index_type_name(t, false))
.map(|s| s.to_ascii_lowercase())
.collect::>();
if r.is_empty() {
None
} else {
Some(r)
}
})
}
pub fn cache() -> Arc {
CACHE_KEY.with(|c| c.borrow().clone())
}
", variants));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(buf, " ",
res.join("")));
}
}
sidebar.push_str("Implementors");
if t.auto {
sidebar.push_str("Auto Implementors");
}
sidebar.push_str(&sidebar_assoc_items(it));
write!(buf, " ",
types));
}
if !consts.is_empty() {
sidebar.push_str(&format!("\
Associated Constants ",
consts));
}
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| {
match extract_for_impl_name(&i.impl_item) {
Some((ref name, ref id)) => {
Some(format!("{}",
id,
Escape(name)))
}
_ => None,
}
})
.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) = impl_.inner_impl().items.iter().filter_map(|item| {
match item.inner {
clean::TypedefItem(ref t, true) => Some(&t.type_),
_ => None,
}
}).next() {
let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
c.primitive_locations.get(&prim).cloned()
})).and_then(|did| c.impls.get(&did));
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!("{:#}", 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,
true))
.collect::