// ignore-tidy-filelength
//! Rustdoc's HTML rendering module.
//!
//! This modules contains the bulk of the logic necessary for rendering a
//! rustdoc `clean::Crate` instance to a set of static HTML pages. This
//! rendering process is largely driven by the `format!` syntax extension to
//! perform all I/O into files and streams.
//!
//! The rendering process is largely driven by the `Context` and `Cache`
//! structures. The cache is pre-populated by crawling the crate in question,
//! and then it is shared among the various rendering threads. The cache is meant
//! to be a fairly large structure not implementing `Clone` (because it's shared
//! among threads). The context, however, should be a lightweight structure. This
//! is cloned per-thread and contains information about what is currently being
//! rendered.
//!
//! In order to speed up rendering (mostly because of markdown rendering), the
//! rendering process has been parallelized. This parallelization is only
//! exposed through the `crate` method on the context, and then also from the
//! fact that the shared cache is stored in TLS (and must be accessed as such).
//!
//! In addition to rendering the crate itself, this module is also responsible
//! for creating the corresponding search index and source file renderings.
//! These threads are not parallelized (they haven't been a bottleneck yet), and
//! both occur before the crate is rendered.
crate mod cache;
#[cfg(test)]
mod tests;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};
use std::default::Default;
use std::ffi::OsStr;
use std::fmt::{self, Write};
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::path::{Component, Path, PathBuf};
use std::rc::Rc;
use std::str;
use std::string::ToString;
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use itertools::Itertools;
use rustc_ast_pretty::pprust;
use rustc_attr::{Deprecation, StabilityLevel};
use rustc_data_structures::flock;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::Mutability;
use rustc_middle::middle::stability;
use rustc_middle::ty::TyCtxt;
use rustc_session::Session;
use rustc_span::edition::Edition;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::FileName;
use rustc_span::symbol::{kw, sym, Symbol};
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
use crate::config::{RenderInfo, RenderOptions};
use crate::docfs::{DocFS, PathError};
use crate::error::Error;
use crate::formats::cache::Cache;
use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::fmt_impl_for_trait_page;
use crate::html::format::Function;
use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
use crate::html::markdown::{
self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
};
use crate::html::sources;
use crate::html::{highlight, layout, static_files};
use cache::{build_index, ExternalLocation};
/// A pair of name and its optional document.
crate type NameDoc = (String, Option Crate {} Version {} Back to index Settings(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result(&self, serializer: S) -> Result\
List of all crates\
{}
",
krates
.iter()
.map(|s| {
format!(
"{}
", title, title, class);
for s in e.iter() {
write!(f, "
");
}
}
f.write_str(
"\
List of all items\
\
\
\
[−]\
\
List of all items\
",
);
// Note: print_entries does not escape the title, because we know the current set of titles
// don't require escaping.
print_entries(f, &self.structs, "Structs", "structs");
print_entries(f, &self.enums, "Enums", "enums");
print_entries(f, &self.unions, "Unions", "unions");
print_entries(f, &self.primitives, "Primitives", "primitives");
print_entries(f, &self.traits, "Traits", "traits");
print_entries(f, &self.macros, "Macros", "macros");
print_entries(f, &self.attributes, "Attribute Macros", "attributes");
print_entries(f, &self.derives, "Derive Macros", "derives");
print_entries(f, &self.functions, "Functions", "functions");
print_entries(f, &self.typedefs, "Typedefs", "typedefs");
print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
print_entries(f, &self.statics, "Statics", "statics");
print_entries(f, &self.constants, "Constants", "constants")
}
}
#[derive(Debug)]
enum Setting {
Section {
description: &'static str,
sub_settings: Vec\
Rustdoc settings\
\
");
let name = match *item.kind {
clean::ModuleItem(ref m) => {
if m.is_crate {
"Crate "
} else {
"Module "
}
}
clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
clean::TraitItem(..) => "Trait ",
clean::StructItem(..) => "Struct ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypedefItem(..) => "Type Definition ",
clean::MacroItem(..) => "Macro ",
clean::ProcMacroItem(ref mac) => match mac.kind {
MacroKind::Bang => "Macro ",
MacroKind::Attr => "Attribute Macro ",
MacroKind::Derive => "Derive Macro ",
},
clean::PrimitiveItem(..) => "Primitive Type ",
clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
clean::ConstantItem(..) => "Constant ",
clean::ForeignTypeItem => "Foreign Type ",
clean::KeywordItem(..) => "Keyword ",
clean::OpaqueTyItem(..) => "Opaque Type ",
clean::TraitAliasItem(..) => "Trait Alias ",
_ => {
// We don't generate pages for any other type.
unreachable!();
}
};
buf.write_str(name);
if !item.is_primitive() && !item.is_keyword() {
let cur = &cx.current;
let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
write!(
buf,
"{}::
"); // out-of-band
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::TypedefItem(ref t, _) => item_typedef(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),
_ => {
// We don't generate pages for any other type.
unreachable!();
}
}
}
fn item_path(ty: ItemType, name: &str) -> String {
match ty {
ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
_ => format!("{}.{}.html", ty, name),
}
}
fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
let mut s = cx.current.join("::");
s.push_str("::");
s.push_str(&item.name.unwrap().as_str());
s
}
fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
if let Some(ref name) = item.name {
info!("Documenting {}", name);
}
document_item_info(w, cx, item, false, parent);
document_full(w, item, cx, "", false);
}
/// Render md_text as markdown.
fn render_markdown(
w: &mut Buffer,
cx: &Context<'_>,
md_text: &str,
links: Vec
Struct {{ .. }} syntax; cannot be \
matched against without a wildcard ..; and \
struct update syntax will not work.",
);
} else if item.is_enum() {
w.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() {
w.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 {
w.write_str(
"This type will require a wildcard arm in any match statements or constructors.",
);
}
w.write_str("{}extern crate {} as {};",
myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
anchor(myitem.def_id, &*src.as_str(), cx.cache()),
name
),
None => write!(
w,
" |
{}", Escape(&feature.as_str()));
if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
feature.push_str(&format!(
" #{issue}",
url = url,
issue = issue
));
}
message.push_str(&format!(" ({})", feature));
if let Some(unstable_reason) = 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(cx.tcx(), it.def_id, cx.cache()),
name = it.name.as_ref().unwrap(),
typ = c.type_.print(cx.cache()),
);
if c.value.is_some() || c.is_literal {
write!(w, " = {expr};", expr = Escape(&c.expr));
} else {
w.write_str(";");
}
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));
}
}
}
w.write_str("");
document(w, cx, it, None)
}
fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
w.write_str("");
render_attributes(w, it, false);
write!(
w,
"{vis}static {mutability}{name}: {typ}",
vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
mutability = s.mutability.print_with_space(),
name = it.name.as_ref().unwrap(),
typ = s.type_.print(cx.cache())
);
document(w, cx, it, None)
}
fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
let header_len = format!(
"{}{}{}{}{:#}fn {}{:#}",
it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
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(cx.cache())
)
.len();
w.write_str("");
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(cx.tcx(), it.def_id, cx.cache()),
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(cx.cache()),
where_clause =
WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()),
decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
.print(cx.cache()),
spotlight = spotlight_decl(&f.decl, cx.cache()),
);
document(w, cx, it, None)
}
fn render_implementor(
cx: &Context<'_>,
implementor: &Impl,
trait_: &clean::Item,
w: &mut Buffer,
implementor_dups: &FxHashMap");
render_attributes(w, it, true);
write!(
w,
"{}{}{}trait {}{}{}",
it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
t.unsafety.print_with_space(),
if t.is_auto { "auto " } else { "" },
it.name.as_ref().unwrap(),
t.generics.print(cx.cache()),
bounds
);
if !t.generics.where_predicates.is_empty() {
let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true };
write!(w, "{}", where_.print(cx.cache()));
} else {
w.write_str(" ");
}
if t.items.is_empty() {
w.write_str("{ }");
} else {
// FIXME: we should be using a derived_id for the Anchors here
w.write_str("{\n");
for t in &types {
render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
w.write_str(";\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, cx);
w.write_str(";\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, cx);
w.write_str(";\n");
if pos < required.len() - 1 {
w.write_str("");
}
}
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, cx);
match *m.kind {
clean::MethodItem(ref inner, _)
if !inner.generics.where_predicates.is_empty() =>
{
w.write_str(",\n { ... }\n");
}
_ => {
w.write_str(" { ... }\n");
}
}
if pos < provided.len() - 1 {
w.write_str("");
}
}
w.write_str("}");
}
w.write_str("")
});
// Trait documentation
document(w, cx, it, None);
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, cx);
w.write_str("");
render_stability_since(w, m, t, cx.tcx());
write_srclink(cx, m, w);
w.write_str("");
render_attributes(w, it, true);
render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
w.write_str("")
});
document(w, cx, it, None);
let mut fields = s
.fields
.iter()
.filter_map(|f| match *f.kind {
clean::StructFieldItem(ref ty) => Some((f, ty)),
_ => None,
})
.peekable();
if let CtorKind::Fictive = 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(cx.cache())
);
document(w, cx, field, Some(it));
}
}
}
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| {
w.write_str("");
render_attributes(w, it, true);
render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
w.write_str("")
});
document(w, cx, it, None);
let mut fields = s
.fields
.iter()
.filter_map(|f| match *f.kind {
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(cx.cache())
);
if let Some(stability_class) = field.stability_class(cx.tcx()) {
write!(w, "", stab = stability_class);
}
document(w, cx, field, Some(it));
}
}
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| {
w.write_str("");
render_attributes(w, it, true);
write!(
w,
"{}enum {}{}{}",
it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
it.name.as_ref().unwrap(),
e.generics.print(cx.cache()),
WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache())
);
if e.variants.is_empty() && !e.variants_stripped {
w.write_str(" {}");
} else {
w.write_str(" {\n");
for v in &e.variants {
w.write_str(" ");
let name = v.name.as_ref().unwrap();
match *v.kind {
clean::VariantItem(ref var) => match var {
clean::Variant::CLike => write!(w, "{}", name),
clean::Variant::Tuple(ref tys) => {
write!(w, "{}(", name);
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
w.write_str(", ")
}
write!(w, "{}", ty.print(cx.cache()));
}
w.write_str(")");
}
clean::Variant::Struct(ref s) => {
render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
}
},
_ => unreachable!(),
}
w.write_str(",\n");
}
if e.variants_stripped {
w.write_str(" // some variants omitted\n");
}
w.write_str("}");
}
w.write_str("")
});
document(w, cx, it, None);
if !e.variants.is_empty() {
write!(
w,
"{name}",
id = id,
name = variant.name.as_ref().unwrap()
);
if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
w.write_str("(");
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
w.write_str(", ");
}
write!(w, "{}", ty.print(cx.cache()));
}
w.write_str(")");
}
w.write_str("{f}: {t}\
",
id = id,
f = field.name.as_ref().unwrap(),
t = ty.print(cx.cache())
);
document(w, cx, field, Some(variant));
}
}
w.write_str("",
impl_.for_.print(cache)
);
trait_.push_str(&impl_.for_.print(cache).to_string());
}
//use the "where" class here to make it small
write!(
&mut out,
"{}",
impl_.print(cache)
);
let t_did = impl_.trait_.def_id_full(cache).unwrap();
for it in &impl_.items {
if let clean::TypedefItem(ref tydef, _) = *it.kind {
out.push_str(" ");
assoc_type(
&mut out,
it,
&[],
Some(&tydef.type_),
AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
"",
cache,
);
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,
parent: &clean::Item,
link: AssocItemLink<'_>,
render_mode: RenderMode,
outer_version: Option<&str>,
outer_const_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],
) {
let traits = &cx.cache.traits;
let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
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, cx.cache())
} else {
format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
}
}
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, cx.cache());
if show_def_docs {
for it in &i.inner_impl().items {
if let clean::TypedefItem(ref tydef, _) = *it.kind {
w.write_str(" ");
assoc_type(
w,
it,
&[],
Some(&tydef.type_),
AssocItemLink::Anchor(None),
"",
cx.cache(),
);
w.write_str(";");
}
}
}
w.write_str("");
} else {
write!(
w,
"{}",
id,
aliases,
i.inner_impl().print(cx.cache())
);
}
write!(w, "", id);
render_stability_since_raw(
w,
i.impl_item.stable_since(cx.tcx()).as_deref(),
i.impl_item.const_stable_since(cx.tcx()).as_deref(),
outer_version,
outer_const_version,
);
write_srclink(cx, &i.impl_item, w);
w.write_str("
");
if trait_.is_some() {
if let Some(portability) = portability(&i.impl_item, Some(parent)) {
write!(w, "{}", portability);
}
}
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(&cx.cache),
&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,
parent: &clean::Item,
link: AssocItemLink<'_>,
render_mode: RenderMode,
is_default_item: bool,
outer_version: Option<&str>,
outer_const_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 = match render_mode {
RenderMode::Normal => true,
RenderMode::ForDeref { mut_: deref_mut_ } => {
should_render_item(&item, deref_mut_, &cx.cache)
}
};
let (is_hidden, extra_class) =
if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
&& !is_default_item
{
(false, "")
} else {
(true, " hidden")
};
match *item.kind {
clean::MethodItem(..) | clean::TyMethodItem(_) => {
// 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);
w.write_str("");
render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
w.write_str("");
render_stability_since_raw(
w,
item.stable_since(cx.tcx()).as_deref(),
item.const_stable_since(cx.tcx()).as_deref(),
outer_version,
outer_const_version,
);
write_srclink(cx, item, w);
w.write_str("
");
}
}
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),
"",
cx.cache(),
);
w.write_str("
");
}
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), "", cx);
w.write_str("");
render_stability_since_raw(
w,
item.stable_since(cx.tcx()).as_deref(),
item.const_stable_since(cx.tcx()).as_deref(),
outer_version,
outer_const_version,
);
write_srclink(cx, item, w);
w.write_str("
");
}
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), "", cx.cache());
w.write_str("
");
}
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.
if item.doc_value().is_some() {
document_item_info(w, cx, it, is_hidden, Some(parent));
document_full(w, item, cx, "", is_hidden);
} else {
// In case the item isn't documented,
// provide short documentation from the trait.
document_short(
w,
it,
cx,
link,
"",
is_hidden,
Some(parent),
show_def_docs,
);
}
}
} else {
document_item_info(w, cx, item, is_hidden, Some(parent));
if show_def_docs {
document_full(w, item, cx, "", is_hidden);
}
}
} else {
document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
}
}
}
w.write_str("");
for trait_item in &i.inner_impl().items {
doc_impl_item(
w,
cx,
trait_item,
if trait_.is_some() { &i.impl_item } else { parent },
link,
render_mode,
false,
outer_version,
outer_const_version,
trait_,
show_def_docs,
);
}
fn render_default_items(
w: &mut Buffer,
cx: &Context<'_>,
t: &clean::Trait,
i: &clean::Impl,
parent: &clean::Item,
render_mode: RenderMode,
outer_version: Option<&str>,
outer_const_version: Option<&str>,
show_def_docs: bool,
) {
for trait_item in &t.items {
let n = trait_item.name;
if i.items.iter().any(|m| m.name == n) {
continue;
}
let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
doc_impl_item(
w,
cx,
trait_item,
parent,
assoc_link,
render_mode,
true,
outer_version,
outer_const_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(),
&i.impl_item,
render_mode,
outer_version,
outer_const_version,
show_def_docs,
);
}
}
w.write_str("");
}
fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
w.write_str("");
render_attributes(w, it, false);
write!(
w,
"type {}{}{where_clause} = impl {bounds};",
it.name.as_ref().unwrap(),
t.generics.print(cx.cache()),
where_clause =
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
bounds = bounds(&t.bounds, false, cx.cache())
);
document(w, cx, it, None);
// 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) {
w.write_str("");
render_attributes(w, it, false);
write!(
w,
"trait {}{}{} = {};",
it.name.as_ref().unwrap(),
t.generics.print(cx.cache()),
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
bounds(&t.bounds, true, cx.cache())
);
document(w, cx, it, None);
// 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) {
w.write_str("");
render_attributes(w, it, false);
write!(
w,
"type {}{}{where_clause} = {type_};",
it.name.as_ref().unwrap(),
t.generics.print(cx.cache()),
where_clause =
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
type_ = t.type_.print(cx.cache())
);
document(w, cx, it, None);
// 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) {
w.write_str("extern {\n");
render_attributes(w, it, false);
write!(
w,
" {}type {};\n}}",
it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
it.name.as_ref().unwrap(),
);
document(w, cx, it, None);
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.kind {
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) = cx.cache.crate_version {
write!(
buffer,
"\
Version {}
\
",
Escape(version)
);
}
}
buffer.write_str("");
}
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,
cache: &Cache,
) -> 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, cache) {
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: String) -> String {
let mut st = String::new();
let mut last_match = 0;
for (idx, c) in s.char_indices() {
let escaped = match c {
'<' => "%3C",
'>' => "%3E",
' ' => "%20",
'?' => "%3F",
'\'' => "%27",
'&' => "%26",
',' => "%2C",
':' => "%3A",
';' => "%3B",
'[' => "%5B",
']' => "%5D",
'"' => "%22",
_ => continue,
};
st += &s[last_match..idx];
st += escaped;
// NOTE: we only expect single byte characters here - which is fine as long as we
// only match single byte characters
last_match = idx + 1;
}
if last_match != 0 {
st += &s[last_match..];
st
} else {
s
}
}
fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
if let Some(v) = cx.cache.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, &cx.cache)
})
.collect::>();
if !ret.is_empty() {
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
out.push_str(
"Methods\
");
}
}
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_full(cx.cache()) == cx.cache.deref_trait_did)
{
sidebar_deref_methods(cx, out, impl_, v);
}
let format_impls = |impls: Vec<&Impl>| {
let mut links = FxHashSet::default();
let mut ret = impls
.iter()
.filter_map(|it| {
if let Some(ref i) = it.inner_impl().trait_ {
let i_display = format!("{:#}", i.print(cx.cache()));
let out = Escape(&i_display);
let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
let generated = format!(
"{}{}",
encoded,
if it.inner_impl().negative_polarity { "!" } else { "" },
out
);
if links.insert(generated.clone()) { Some(generated) } else { None }
} else {
None
}
})
.collect::>();
ret.sort();
ret
};
let write_sidebar_links = |out: &mut Buffer, links: Vec| {
out.push_str("");
};
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",
);
write_sidebar_links(out, concrete_format);
}
if !synthetic_format.is_empty() {
out.push_str(
"\
Auto Trait Implementations",
);
write_sidebar_links(out, synthetic_format);
}
if !blanket_format.is_empty() {
out.push_str(
"\
Blanket Implementations",
);
write_sidebar_links(out, blanket_format);
}
}
}
}
fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec) {
let c = cx.cache();
debug!("found Deref: {:?}", impl_);
if let Some((target, real_target)) =
impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
clean::TypedefItem(ref t, true) => Some(match *t {
clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
_ => (&t.type_, &t.type_),
}),
_ => None,
})
{
debug!("found target, real_target: {:?} {:?}", target, real_target);
if let Some(did) = target.def_id_full(cx.cache()) {
if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
// `impl Deref for S`
if did == type_did {
// Avoid infinite cycles
return;
}
}
}
let deref_mut = v
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
let inner_impl = target
.def_id_full(cx.cache())
.or_else(|| {
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 {
debug!("found inner_impl: {:?}", impls);
let mut used_links = FxHashSet::default();
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, c))
.collect::>();
if !ret.is_empty() {
let deref_id_map = cx.deref_id_map.borrow();
let id = deref_id_map
.get(&real_target.def_id_full(cx.cache()).unwrap())
.expect("Deref section without derived id");
write!(
out,
"Methods from {}<Target={}>",
id,
Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
Escape(&format!("{:#}", real_target.print(c))),
);
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
out.push_str("");
}
}
// Recurse into any further impls that might exist for `target`
if let Some(target_did) = target.def_id_full(cx.cache()) {
if let Some(target_impls) = c.impls.get(&target_did) {
if let Some(target_deref_impl) = target_impls
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
{
sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
}
}
}
}
}
fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
let mut sidebar = Buffer::new();
let fields = get_struct_fields_name(&s.fields);
if !fields.is_empty() {
if let CtorKind::Fictive = s.struct_type {
sidebar.push_str(
"Fields\
");
}
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn get_id_for_impl_on_foreign_type(
for_: &clean::Type,
trait_: &clean::Type,
cache: &Cache,
) -> String {
small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
}
fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
match *item.kind {
clean::ItemKind::ImplItem(ref i) => {
if let Some(ref trait_) = i.trait_ {
Some((
format!("{:#}", i.for_.print(cache)),
get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
))
} else {
None
}
}
_ => None,
}
}
fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
buf.write_str("");
fn print_sidebar_section(
out: &mut Buffer,
items: &[clean::Item],
before: &str,
filter: impl Fn(&clean::Item) -> bool,
write: impl Fn(&mut Buffer, &Symbol),
after: &str,
) {
let mut items = items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if filter(m) => Some(name),
_ => None,
})
.collect::>();
if !items.is_empty() {
items.sort();
out.push_str(before);
for item in items.into_iter() {
write(out, item);
}
out.push_str(after);
}
}
print_sidebar_section(
buf,
&t.items,
"\
Associated Types",
);
print_sidebar_section(
buf,
&t.items,
"\
Associated Constants",
);
print_sidebar_section(
buf,
&t.items,
"\
Required Methods",
);
print_sidebar_section(
buf,
&t.items,
"\
Provided Methods",
);
if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
let mut res = implementors
.iter()
.filter(|i| {
i.inner_impl()
.for_
.def_id_full(cx.cache())
.map_or(false, |d| !cx.cache.paths.contains_key(&d))
})
.filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
.collect::>();
if !res.is_empty() {
res.sort();
buf.push_str(
"\
Implementations on Foreign Types\
");
}
}
sidebar_assoc_items(cx, buf, it);
buf.push_str("Implementors");
if t.is_auto {
buf.push_str(
"Auto Implementors",
);
}
buf.push_str(" ")
}
fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn get_struct_fields_name(fields: &[clean::Item]) -> Vec {
let mut fields = fields
.iter()
.filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
.filter_map(|f| {
f.name.map(|name| format!("{name}", name = name))
})
.collect::>();
fields.sort();
fields
}
fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
let mut sidebar = Buffer::new();
let fields = get_struct_fields_name(&u.fields);
if !fields.is_empty() {
sidebar.push_str(
"Fields\
");
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
let mut sidebar = Buffer::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\
",
variants.join(""),
));
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
match *ty {
ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
ItemType::Module => ("modules", "Modules"),
ItemType::Struct => ("structs", "Structs"),
ItemType::Union => ("unions", "Unions"),
ItemType::Enum => ("enums", "Enums"),
ItemType::Function => ("functions", "Functions"),
ItemType::Typedef => ("types", "Type Definitions"),
ItemType::Static => ("statics", "Statics"),
ItemType::Constant => ("constants", "Constants"),
ItemType::Trait => ("traits", "Traits"),
ItemType::Impl => ("impls", "Implementations"),
ItemType::TyMethod => ("tymethods", "Type Methods"),
ItemType::Method => ("methods", "Methods"),
ItemType::StructField => ("fields", "Struct Fields"),
ItemType::Variant => ("variants", "Variants"),
ItemType::Macro => ("macros", "Macros"),
ItemType::Primitive => ("primitives", "Primitive Types"),
ItemType::AssocType => ("associated-types", "Associated Types"),
ItemType::AssocConst => ("associated-consts", "Associated Constants"),
ItemType::ForeignType => ("foreign-types", "Foreign Types"),
ItemType::Keyword => ("keywords", "Keywords"),
ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
ItemType::ProcDerive => ("derives", "Derive Macros"),
ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
}
}
fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
let mut sidebar = String::new();
if items.iter().any(|it| {
it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
}) {
sidebar.push_str("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(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "{}", sidebar.into_inner());
}
}
fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
wrap_into_docblock(w, |w| {
highlight::render_with_highlighting(
&t.source,
w,
Some("macro"),
None,
None,
it.source.span().edition(),
);
});
document(w, cx, it, None)
}
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 => {
w.push_str("");
write!(w, "{}!() {{ /* proc-macro */ }}", name);
w.push_str("");
}
MacroKind::Attr => {
w.push_str("");
write!(w, "#[{}]", name);
w.push_str("");
}
MacroKind::Derive => {
w.push_str("");
write!(w, "#[derive({})]", name);
if !m.helpers.is_empty() {
w.push_str("\n{\n");
w.push_str(" // Attributes available to this derive:\n");
for attr in &m.helpers {
writeln!(w, " #[{}]", attr);
}
w.push_str("}\n");
}
w.push_str("");
}
}
document(w, cx, it, None)
}
fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
document(w, cx, it, None);
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
document(w, cx, it, None)
}
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, cache: &Cache) -> Vec {
let mut out = Vec::new();
let mut visited = FxHashSet::default();
let mut work = VecDeque::new();
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
}