1 //! HTML formatting module
3 //! This module contains a large number of `fmt::Display` implementations for
4 //! various types in `rustdoc::clean`. These implementations all currently
5 //! assume that HTML output is desired, although it may be possible to redesign
6 //! them in the future to instead emit any format desired.
13 use rustc_attr::{ConstStability, StabilityLevel};
14 use rustc_data_structures::captures::Captures;
15 use rustc_data_structures::fx::FxHashSet;
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
20 use rustc_middle::ty::DefIdTree;
21 use rustc_middle::ty::TyCtxt;
22 use rustc_span::symbol::kw;
23 use rustc_span::{sym, Symbol};
24 use rustc_target::spec::abi::Abi;
27 self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
30 use crate::formats::item_type::ItemType;
31 use crate::html::escape::Escape;
32 use crate::html::render::Context;
34 use super::url_parts_builder::estimate_item_path_byte_length;
35 use super::url_parts_builder::UrlPartsBuilder;
37 pub(crate) trait Print {
38 fn print(self, buffer: &mut Buffer);
43 F: FnOnce(&mut Buffer),
45 fn print(self, buffer: &mut Buffer) {
50 impl Print for String {
51 fn print(self, buffer: &mut Buffer) {
52 buffer.write_str(&self);
56 impl Print for &'_ str {
57 fn print(self, buffer: &mut Buffer) {
58 buffer.write_str(self);
62 #[derive(Debug, Clone)]
63 pub(crate) struct Buffer {
68 impl core::fmt::Write for Buffer {
70 fn write_str(&mut self, s: &str) -> fmt::Result {
71 self.buffer.write_str(s)
75 fn write_char(&mut self, c: char) -> fmt::Result {
76 self.buffer.write_char(c)
80 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
81 self.buffer.write_fmt(args)
86 pub(crate) fn empty_from(v: &Buffer) -> Buffer {
87 Buffer { for_html: v.for_html, buffer: String::new() }
90 pub(crate) fn html() -> Buffer {
91 Buffer { for_html: true, buffer: String::new() }
94 pub(crate) fn new() -> Buffer {
95 Buffer { for_html: false, buffer: String::new() }
98 pub(crate) fn is_empty(&self) -> bool {
99 self.buffer.is_empty()
102 pub(crate) fn into_inner(self) -> String {
106 pub(crate) fn insert_str(&mut self, idx: usize, s: &str) {
107 self.buffer.insert_str(idx, s);
110 pub(crate) fn push_str(&mut self, s: &str) {
111 self.buffer.push_str(s);
114 pub(crate) fn push_buffer(&mut self, other: Buffer) {
115 self.buffer.push_str(&other.buffer);
118 // Intended for consumption by write! and writeln! (std::fmt) but without
119 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
121 pub(crate) fn write_str(&mut self, s: &str) {
122 self.buffer.push_str(s);
125 // Intended for consumption by write! and writeln! (std::fmt) but without
126 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
128 pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
130 self.buffer.write_fmt(v).unwrap();
133 pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
138 pub(crate) fn is_for_html(&self) -> bool {
142 pub(crate) fn reserve(&mut self, additional: usize) {
143 self.buffer.reserve(additional)
147 fn comma_sep<T: fmt::Display>(
148 items: impl Iterator<Item = T>,
149 space_after_comma: bool,
150 ) -> impl fmt::Display {
151 display_fn(move |f| {
152 for (i, item) in items.enumerate() {
154 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
156 fmt::Display::fmt(&item, f)?;
162 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
163 bounds: &'a [clean::GenericBound],
164 cx: &'a Context<'tcx>,
165 ) -> impl fmt::Display + 'a + Captures<'tcx> {
166 display_fn(move |f| {
167 let mut bounds_dup = FxHashSet::default();
169 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
173 fmt::Display::fmt(&bound.print(cx), f)?;
179 impl clean::GenericParamDef {
180 pub(crate) fn print<'a, 'tcx: 'a>(
182 cx: &'a Context<'tcx>,
183 ) -> impl fmt::Display + 'a + Captures<'tcx> {
184 display_fn(move |f| match &self.kind {
185 clean::GenericParamDefKind::Lifetime { outlives } => {
186 write!(f, "{}", self.name)?;
188 if !outlives.is_empty() {
190 for (i, lt) in outlives.iter().enumerate() {
194 write!(f, "{}", lt.print())?;
200 clean::GenericParamDefKind::Type { bounds, default, .. } => {
201 f.write_str(self.name.as_str())?;
203 if !bounds.is_empty() {
205 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
207 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
211 if let Some(ref ty) = default {
213 write!(f, " = {:#}", ty.print(cx))?;
215 write!(f, " = {}", ty.print(cx))?;
221 clean::GenericParamDefKind::Const { ty, default, .. } => {
223 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
225 write!(f, "const {}: {}", self.name, ty.print(cx))?;
228 if let Some(default) = default {
230 write!(f, " = {:#}", default)?;
232 write!(f, " = {}", default)?;
242 impl clean::Generics {
243 pub(crate) fn print<'a, 'tcx: 'a>(
245 cx: &'a Context<'tcx>,
246 ) -> impl fmt::Display + 'a + Captures<'tcx> {
247 display_fn(move |f| {
248 let mut real_params =
249 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
250 if real_params.peek().is_none() {
255 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
257 write!(f, "<{}>", comma_sep(real_params.map(|g| g.print(cx)), true))
263 /// * The Generics from which to emit a where-clause.
264 /// * The number of spaces to indent each line with.
265 /// * Whether the where-clause needs to add a comma and newline after the last bound.
266 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
267 gens: &'a clean::Generics,
268 cx: &'a Context<'tcx>,
271 ) -> impl fmt::Display + 'a + Captures<'tcx> {
274 display_fn(move |f| {
275 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
276 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
278 display_fn(move |f| {
282 f.write_str("<br>")?;
286 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
287 let ty_cx = ty.print(cx);
288 let generic_bounds = print_generic_bounds(bounds, cx);
290 if bound_params.is_empty() {
292 write!(f, "{ty_cx:#}: {generic_bounds:#}")
294 write!(f, "{ty_cx}: {generic_bounds}")
300 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
301 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
306 "for<{}> {ty_cx}: {generic_bounds}",
307 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
312 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
313 let mut bounds_display = String::new();
314 for bound in bounds.iter().map(|b| b.print(cx)) {
315 write!(bounds_display, "{bound} + ")?;
317 bounds_display.truncate(bounds_display.len() - " + ".len());
318 write!(f, "{}: {bounds_display}", lifetime.print())
320 clean::WherePredicate::EqPredicate { lhs, rhs } => {
322 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
324 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
331 if where_predicates.peek().is_none() {
335 let where_preds = comma_sep(where_predicates, false);
336 let clause = if f.alternate() {
338 // add a space so stripping <br> tags and breaking spaces still renders properly
339 format!(" where{where_preds}, ")
341 format!(" where{where_preds}")
344 let mut br_with_padding = String::with_capacity(6 * indent + 28);
345 br_with_padding.push_str("<br>");
346 for _ in 0..indent + 4 {
347 br_with_padding.push_str(" ");
349 let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
352 let mut clause = " ".repeat(indent.saturating_sub(1));
353 // add a space so stripping <br> tags and breaking spaces still renders properly
356 " <span class=\"where fmt-newline\">where{where_preds}, </span>"
360 // insert a <br> tag after a single space but before multiple spaces at the start
362 format!(" <br><span class=\"where\">where{where_preds}</span>")
364 let mut clause = br_with_padding;
365 clause.truncate(clause.len() - 5 * " ".len());
366 write!(clause, " <span class=\"where\">where{where_preds}</span>")?;
371 write!(f, "{clause}")
375 impl clean::Lifetime {
376 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
381 impl clean::Constant {
382 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
383 let expr = self.expr(tcx);
386 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
392 impl clean::PolyTrait {
393 fn print<'a, 'tcx: 'a>(
395 cx: &'a Context<'tcx>,
396 ) -> impl fmt::Display + 'a + Captures<'tcx> {
397 display_fn(move |f| {
398 if !self.generic_params.is_empty() {
403 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
409 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
414 write!(f, "{:#}", self.trait_.print(cx))
416 write!(f, "{}", self.trait_.print(cx))
422 impl clean::GenericBound {
423 pub(crate) fn print<'a, 'tcx: 'a>(
425 cx: &'a Context<'tcx>,
426 ) -> impl fmt::Display + 'a + Captures<'tcx> {
427 display_fn(move |f| match self {
428 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
429 clean::GenericBound::TraitBound(ty, modifier) => {
430 let modifier_str = match modifier {
431 hir::TraitBoundModifier::None => "",
432 hir::TraitBoundModifier::Maybe => "?",
433 // ~const is experimental; do not display those bounds in rustdoc
434 hir::TraitBoundModifier::MaybeConst => "",
437 write!(f, "{}{:#}", modifier_str, ty.print(cx))
439 write!(f, "{}{}", modifier_str, ty.print(cx))
446 impl clean::GenericArgs {
447 fn print<'a, 'tcx: 'a>(
449 cx: &'a Context<'tcx>,
450 ) -> impl fmt::Display + 'a + Captures<'tcx> {
451 display_fn(move |f| {
453 clean::GenericArgs::AngleBracketed { args, bindings } => {
454 if !args.is_empty() || !bindings.is_empty() {
458 f.write_str("<")?;
460 let mut comma = false;
461 for arg in args.iter() {
467 write!(f, "{:#}", arg.print(cx))?;
469 write!(f, "{}", arg.print(cx))?;
472 for binding in bindings.iter() {
478 write!(f, "{:#}", binding.print(cx))?;
480 write!(f, "{}", binding.print(cx))?;
486 f.write_str(">")?;
490 clean::GenericArgs::Parenthesized { inputs, output } => {
492 let mut comma = false;
493 for ty in inputs.iter() {
499 write!(f, "{:#}", ty.print(cx))?;
501 write!(f, "{}", ty.print(cx))?;
505 if let Some(ref ty) = *output {
507 write!(f, " -> {:#}", ty.print(cx))?;
509 write!(f, " -> {}", ty.print(cx))?;
519 // Possible errors when computing href link source for a `DefId`
520 pub(crate) enum HrefError {
521 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
523 /// This can only happen for non-local items.
527 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
528 /// implements it for a local type.
529 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
532 /// rustc a.rs --crate-type=lib
533 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
536 /// Now, the associated items in the trait impl want to link to the corresponding item in the
537 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
538 /// *documentation (was) not built*.
539 DocumentationNotBuilt,
540 /// This can only happen for non-local items when `--document-private-items` is not passed.
542 // Not in external cache, href link should be in same page
546 // Panics if `syms` is empty.
547 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
548 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
549 s.push_str(syms[0].as_str());
550 for sym in &syms[1..] {
552 s.push_str(sym.as_str());
557 pub(crate) fn href_with_root_path(
560 root_path: Option<&str>,
561 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
563 let def_kind = tcx.def_kind(did);
564 let did = match def_kind {
565 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
566 // documented on their parent's page
571 let cache = cx.cache();
572 let relative_to = &cx.current;
573 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
574 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
578 && !cache.access_levels.is_public(did)
579 && !cache.document_private
580 && !cache.primitive_locations.values().any(|&id| id == did)
582 return Err(HrefError::Private);
585 let mut is_remote = false;
586 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
587 Some(&(ref fqp, shortty)) => (fqp, shortty, {
588 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
589 debug!(?fqp, ?shortty, ?module_fqp);
590 href_relative_parts(module_fqp, relative_to).collect()
593 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
594 let module_fqp = to_module_fqp(shortty, fqp);
598 match cache.extern_locations[&did.krate] {
599 ExternalLocation::Remote(ref s) => {
601 let s = s.trim_end_matches('/');
602 let mut builder = UrlPartsBuilder::singleton(s);
603 builder.extend(module_fqp.iter().copied());
606 ExternalLocation::Local => {
607 href_relative_parts(module_fqp, relative_to).collect()
609 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
613 return Err(HrefError::NotInExternalCache);
618 if let Some(root_path) = root_path {
619 let root = root_path.trim_end_matches('/');
620 url_parts.push_front(root);
625 ItemType::Module => {
626 url_parts.push("index.html");
629 let prefix = shortty.as_str();
630 let last = fqp.last().unwrap();
631 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
634 Ok((url_parts.finish(), shortty, fqp.to_vec()))
640 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
641 href_with_root_path(did, cx, None)
644 /// Both paths should only be modules.
645 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
646 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
647 pub(crate) fn href_relative_parts<'fqp>(
649 relative_to_fqp: &[Symbol],
650 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
651 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
652 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
654 let dissimilar_part_count = relative_to_fqp.len() - i;
655 let fqp_module = &fqp[i..fqp.len()];
656 return box iter::repeat(sym::dotdot)
657 .take(dissimilar_part_count)
658 .chain(fqp_module.iter().copied());
661 // e.g. linking to std::sync::atomic from std::sync
662 if relative_to_fqp.len() < fqp.len() {
663 box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
664 // e.g. linking to std::sync from std::sync::atomic
665 } else if fqp.len() < relative_to_fqp.len() {
666 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
667 box iter::repeat(sym::dotdot).take(dissimilar_part_count)
668 // linking to the same module
674 /// Used to render a [`clean::Path`].
675 fn resolved_path<'cx>(
676 w: &mut fmt::Formatter<'_>,
681 cx: &'cx Context<'_>,
683 let last = path.segments.last().unwrap();
686 for seg in &path.segments[..path.segments.len() - 1] {
687 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
691 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
693 let path = if use_absolute {
694 if let Ok((_, _, fqp)) = href(did, cx) {
697 join_with_double_colon(&fqp[..fqp.len() - 1]),
698 anchor(did, *fqp.last().unwrap(), cx)
701 last.name.to_string()
704 anchor(did, last.name, cx).to_string()
706 write!(w, "{}{}", path, last.args.print(cx))?;
712 f: &mut fmt::Formatter<'_>,
713 prim: clean::PrimitiveType,
718 let mut needs_termination = false;
720 match m.primitive_locations.get(&prim) {
721 Some(&def_id) if def_id.is_local() => {
722 let len = cx.current.len();
723 let len = if len == 0 { 0 } else { len - 1 };
726 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
730 needs_termination = true;
733 let loc = match m.extern_locations[&def_id.krate] {
734 ExternalLocation::Remote(ref s) => {
735 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
736 let builder: UrlPartsBuilder =
737 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
742 ExternalLocation::Local => {
743 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
744 Some(if cx.current.first() == Some(&cname_sym) {
745 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
747 iter::repeat(sym::dotdot)
748 .take(cx.current.len())
749 .chain(iter::once(cname_sym))
753 ExternalLocation::Unknown => None,
755 if let Some(mut loc) = loc {
756 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
757 write!(f, "<a class=\"primitive\" href=\"{}\">", loc.finish())?;
758 needs_termination = true;
764 write!(f, "{}", name)?;
765 if needs_termination {
771 /// Helper to render type parameters
772 fn tybounds<'a, 'tcx: 'a>(
773 bounds: &'a [clean::PolyTrait],
774 lt: &'a Option<clean::Lifetime>,
775 cx: &'a Context<'tcx>,
776 ) -> impl fmt::Display + 'a + Captures<'tcx> {
777 display_fn(move |f| {
778 for (i, bound) in bounds.iter().enumerate() {
783 fmt::Display::fmt(&bound.print(cx), f)?;
786 if let Some(lt) = lt {
788 fmt::Display::fmt(<.print(), f)?;
794 pub(crate) fn anchor<'a, 'cx: 'a>(
797 cx: &'cx Context<'_>,
798 ) -> impl fmt::Display + 'a {
799 let parts = href(did, cx);
800 display_fn(move |f| {
801 if let Ok((url, short_ty, fqp)) = parts {
804 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
808 join_with_double_colon(&fqp),
812 write!(f, "{}", text)
819 f: &mut fmt::Formatter<'_>,
821 cx: &'cx Context<'_>,
823 trace!("fmt_type(t = {:?})", t);
826 clean::Generic(name) => write!(f, "{}", name),
827 clean::Type::Path { ref path } => {
828 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
829 let did = path.def_id();
830 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
832 clean::DynTrait(ref bounds, ref lt) => {
833 f.write_str("dyn ")?;
834 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
836 clean::Infer => write!(f, "_"),
837 clean::Primitive(clean::PrimitiveType::Never) => {
838 primitive_link(f, PrimitiveType::Never, "!", cx)
840 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
841 clean::BareFunction(ref decl) => {
846 decl.print_hrtb_with_space(cx),
847 decl.unsafety.print_with_space(),
848 print_abi_with_space(decl.abi),
855 decl.print_hrtb_with_space(cx),
856 decl.unsafety.print_with_space(),
857 print_abi_with_space(decl.abi)
859 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
860 write!(f, "{}", decl.decl.print(cx))
863 clean::Tuple(ref typs) => {
865 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
867 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
868 // Carry `f.alternate()` into this display w/o branching manually.
869 fmt::Display::fmt(&one.print(cx), f)?;
870 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
873 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
874 for (i, item) in many.iter().enumerate() {
878 fmt::Display::fmt(&item.print(cx), f)?;
880 primitive_link(f, PrimitiveType::Tuple, ")", cx)
884 clean::Slice(ref t) => match **t {
885 clean::Generic(name) => {
886 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
889 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
890 fmt::Display::fmt(&t.print(cx), f)?;
891 primitive_link(f, PrimitiveType::Slice, "]", cx)
894 clean::Array(ref t, ref n) => {
895 primitive_link(f, PrimitiveType::Array, "[", cx)?;
896 fmt::Display::fmt(&t.print(cx), f)?;
898 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
900 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
903 clean::RawPointer(m, ref t) => {
905 hir::Mutability::Mut => "mut",
906 hir::Mutability::Not => "const",
909 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
910 let text = if f.alternate() {
911 format!("*{} {:#}", m, t.print(cx))
913 format!("*{} {}", m, t.print(cx))
915 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
917 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
918 fmt::Display::fmt(&t.print(cx), f)
921 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
923 Some(l) => format!("{} ", l.print()),
926 let m = mutability.print_with_space();
927 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
929 clean::Slice(ref bt) => {
930 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
932 clean::Generic(name) => primitive_link(
934 PrimitiveType::Slice,
935 &format!("{amp}{lt}{m}[{name}]"),
941 PrimitiveType::Slice,
942 &format!("{}{}{}[", amp, lt, m),
946 write!(f, "{:#}", bt.print(cx))?;
948 write!(f, "{}", bt.print(cx))?;
950 primitive_link(f, PrimitiveType::Slice, "]", cx)
954 clean::DynTrait(ref bounds, ref trait_lt)
955 if bounds.len() > 1 || trait_lt.is_some() =>
957 write!(f, "{}{}{}(", amp, lt, m)?;
958 fmt_type(ty, f, use_absolute, cx)?;
961 clean::Generic(..) => {
964 PrimitiveType::Reference,
965 &format!("{}{}{}", amp, lt, m),
968 fmt_type(ty, f, use_absolute, cx)
971 write!(f, "{}{}{}", amp, lt, m)?;
972 fmt_type(ty, f, use_absolute, cx)
976 clean::ImplTrait(ref bounds) => {
978 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
980 write!(f, "impl {}", print_generic_bounds(bounds, cx))
983 clean::QPath { ref assoc, ref self_type, ref trait_, should_show_cast } => {
985 if should_show_cast {
986 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
988 write!(f, "{:#}::", self_type.print(cx))?
991 if should_show_cast {
992 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
994 write!(f, "{}::", self_type.print(cx))?
997 // It's pretty unsightly to look at `<A as B>::C` in output, and
998 // we've got hyperlinking on our side, so try to avoid longer
999 // notation as much as possible by making `C` a hyperlink to trait
1000 // `B` to disambiguate.
1002 // FIXME: this is still a lossy conversion and there should probably
1003 // be a better way of representing this in general? Most of
1004 // the ugliness comes from inlining across crates where
1005 // everything comes in as a fully resolved QPath (hard to
1007 match href(trait_.def_id(), cx) {
1008 Ok((ref url, _, ref path)) if !f.alternate() => {
1011 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1012 title=\"type {path}::{name}\">{name}</a>{args}",
1014 shortty = ItemType::AssocType,
1016 path = join_with_double_colon(path),
1017 args = assoc.args.print(cx),
1020 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1028 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1030 cx: &'a Context<'tcx>,
1031 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1032 display_fn(move |f| fmt_type(self, f, false, cx))
1037 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1039 cx: &'a Context<'tcx>,
1040 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1041 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1046 pub(crate) fn print<'a, 'tcx: 'a>(
1049 cx: &'a Context<'tcx>,
1050 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1051 display_fn(move |f| {
1053 write!(f, "impl{:#} ", self.generics.print(cx))?;
1055 write!(f, "impl{} ", self.generics.print(cx))?;
1058 if let Some(ref ty) = self.trait_ {
1059 match self.polarity {
1060 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1061 ty::ImplPolarity::Negative => write!(f, "!")?,
1063 fmt::Display::fmt(&ty.print(cx), f)?;
1064 write!(f, " for ")?;
1067 if let Some(ty) = self.kind.as_blanket_ty() {
1068 fmt_type(ty, f, use_absolute, cx)?;
1070 fmt_type(&self.for_, f, use_absolute, cx)?;
1073 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1079 impl clean::Arguments {
1080 pub(crate) fn print<'a, 'tcx: 'a>(
1082 cx: &'a Context<'tcx>,
1083 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1084 display_fn(move |f| {
1085 for (i, input) in self.values.iter().enumerate() {
1086 if !input.name.is_empty() {
1087 write!(f, "{}: ", input.name)?;
1090 write!(f, "{:#}", input.type_.print(cx))?;
1092 write!(f, "{}", input.type_.print(cx))?;
1094 if i + 1 < self.values.len() {
1103 impl clean::FnRetTy {
1104 pub(crate) fn print<'a, 'tcx: 'a>(
1106 cx: &'a Context<'tcx>,
1107 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1108 display_fn(move |f| match self {
1109 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1110 clean::Return(ty) if f.alternate() => {
1111 write!(f, " -> {:#}", ty.print(cx))
1113 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1114 clean::DefaultReturn => Ok(()),
1119 impl clean::BareFunctionDecl {
1120 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1122 cx: &'a Context<'tcx>,
1123 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1124 display_fn(move |f| {
1125 if !self.generic_params.is_empty() {
1129 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1138 impl clean::FnDecl {
1139 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1141 cx: &'a Context<'tcx>,
1142 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1143 display_fn(move |f| {
1144 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1148 "({args:#}{ellipsis}){arrow:#}",
1149 args = self.inputs.print(cx),
1150 ellipsis = ellipsis,
1151 arrow = self.output.print(cx)
1156 "({args}{ellipsis}){arrow}",
1157 args = self.inputs.print(cx),
1158 ellipsis = ellipsis,
1159 arrow = self.output.print(cx)
1165 /// * `header_len`: The length of the function header and name. In other words, the number of
1166 /// characters in the function declaration up to but not including the parentheses.
1167 /// <br>Used to determine line-wrapping.
1168 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1170 /// * `asyncness`: Whether the function is async or not.
1171 pub(crate) fn full_print<'a, 'tcx: 'a>(
1175 asyncness: hir::IsAsync,
1176 cx: &'a Context<'tcx>,
1177 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1178 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1181 fn inner_full_print(
1185 asyncness: hir::IsAsync,
1186 f: &mut fmt::Formatter<'_>,
1189 let amp = if f.alternate() { "&" } else { "&" };
1190 let mut args = Buffer::html();
1191 let mut args_plain = Buffer::new();
1192 for (i, input) in self.inputs.values.iter().enumerate() {
1194 args.push_str("<br>");
1197 if let Some(selfty) = input.to_self() {
1199 clean::SelfValue => {
1200 args.push_str("self");
1201 args_plain.push_str("self");
1203 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1204 write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1205 write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1207 clean::SelfBorrowed(None, mtbl) => {
1208 write!(args, "{}{}self", amp, mtbl.print_with_space());
1209 write!(args_plain, "&{}self", mtbl.print_with_space());
1211 clean::SelfExplicit(ref typ) => {
1213 write!(args, "self: {:#}", typ.print(cx));
1215 write!(args, "self: {}", typ.print(cx));
1217 write!(args_plain, "self: {:#}", typ.print(cx));
1222 args.push_str(" <br>");
1223 args_plain.push_str(" ");
1226 args.push_str("const ");
1227 args_plain.push_str("const ");
1229 if !input.name.is_empty() {
1230 write!(args, "{}: ", input.name);
1231 write!(args_plain, "{}: ", input.name);
1235 write!(args, "{:#}", input.type_.print(cx));
1237 write!(args, "{}", input.type_.print(cx));
1239 write!(args_plain, "{:#}", input.type_.print(cx));
1241 if i + 1 < self.inputs.values.len() {
1243 args_plain.push_str(",");
1247 let mut args_plain = format!("({})", args_plain.into_inner());
1248 let mut args = args.into_inner();
1250 if self.c_variadic {
1251 args.push_str(",<br> ...");
1252 args_plain.push_str(", ...");
1256 let arrow = if let hir::IsAsync::Async = asyncness {
1257 let output = self.sugared_async_return_type();
1258 arrow_plain = format!("{:#}", output.print(cx));
1259 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1261 arrow_plain = format!("{:#}", self.output.print(cx));
1262 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1265 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1266 let output = if declaration_len > 80 {
1267 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1268 let close_pad = format!("<br>{}", " ".repeat(indent));
1270 "({args}{close}){arrow}",
1271 args = args.replace("<br>", &full_pad),
1276 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1280 write!(f, "{}", output.replace("<br>", "\n"))
1282 write!(f, "{}", output)
1287 impl clean::Visibility {
1288 pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1291 cx: &'a Context<'tcx>,
1292 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1293 use std::fmt::Write as _;
1295 let to_print: Cow<'static, str> = match self {
1296 clean::Public => "pub ".into(),
1297 clean::Inherited => "".into(),
1298 clean::Visibility::Restricted(vis_did) => {
1299 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1300 // However, rustdoc currently never displays a module's
1301 // visibility, so it shouldn't matter.
1302 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1304 if vis_did.is_crate_root() {
1305 "pub(crate) ".into()
1306 } else if parent_module == Some(vis_did) {
1307 // `pub(in foo)` where `foo` is the parent module
1308 // is the same as no visibility modifier
1310 } else if parent_module
1311 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1314 "pub(super) ".into()
1316 let path = cx.tcx().def_path(vis_did);
1317 debug!("path={:?}", path);
1318 // modified from `resolved_path()` to work with `DefPathData`
1319 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1320 let anchor = anchor(vis_did, last_name, cx).to_string();
1322 let mut s = "pub(in ".to_owned();
1323 for seg in &path.data[..path.data.len() - 1] {
1324 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1326 let _ = write!(s, "{}) ", anchor);
1331 display_fn(move |f| write!(f, "{}", to_print))
1334 /// This function is the same as print_with_space, except that it renders no links.
1335 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1337 pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1341 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1342 let to_print = match self {
1343 clean::Public => "pub ".to_owned(),
1344 clean::Inherited => String::new(),
1345 clean::Visibility::Restricted(vis_did) => {
1346 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1347 // However, rustdoc currently never displays a module's
1348 // visibility, so it shouldn't matter.
1349 let parent_module = find_nearest_parent_module(tcx, item_did);
1351 if vis_did.is_crate_root() {
1352 "pub(crate) ".to_owned()
1353 } else if parent_module == Some(vis_did) {
1354 // `pub(in foo)` where `foo` is the parent module
1355 // is the same as no visibility modifier
1357 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1360 "pub(super) ".to_owned()
1362 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1366 display_fn(move |f| f.write_str(&to_print))
1370 pub(crate) trait PrintWithSpace {
1371 fn print_with_space(&self) -> &str;
1374 impl PrintWithSpace for hir::Unsafety {
1375 fn print_with_space(&self) -> &str {
1377 hir::Unsafety::Unsafe => "unsafe ",
1378 hir::Unsafety::Normal => "",
1383 impl PrintWithSpace for hir::IsAsync {
1384 fn print_with_space(&self) -> &str {
1386 hir::IsAsync::Async => "async ",
1387 hir::IsAsync::NotAsync => "",
1392 impl PrintWithSpace for hir::Mutability {
1393 fn print_with_space(&self) -> &str {
1395 hir::Mutability::Not => "",
1396 hir::Mutability::Mut => "mut ",
1401 pub(crate) fn print_constness_with_space(
1403 s: Option<ConstStability>,
1406 // const stable or when feature(staged_api) is not set
1408 hir::Constness::Const,
1409 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1411 | (hir::Constness::Const, None) => "const ",
1412 // const unstable or not const
1417 impl clean::Import {
1418 pub(crate) fn print<'a, 'tcx: 'a>(
1420 cx: &'a Context<'tcx>,
1421 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1422 display_fn(move |f| match self.kind {
1423 clean::ImportKind::Simple(name) => {
1424 if name == self.source.path.last() {
1425 write!(f, "use {};", self.source.print(cx))
1427 write!(f, "use {} as {};", self.source.print(cx), name)
1430 clean::ImportKind::Glob => {
1431 if self.source.path.segments.is_empty() {
1434 write!(f, "use {}::*;", self.source.print(cx))
1441 impl clean::ImportSource {
1442 pub(crate) fn print<'a, 'tcx: 'a>(
1444 cx: &'a Context<'tcx>,
1445 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1446 display_fn(move |f| match self.did {
1447 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1449 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1450 write!(f, "{}::", seg.name)?;
1452 let name = self.path.last();
1453 if let hir::def::Res::PrimTy(p) = self.path.res {
1454 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1456 write!(f, "{}", name)?;
1464 impl clean::TypeBinding {
1465 pub(crate) fn print<'a, 'tcx: 'a>(
1467 cx: &'a Context<'tcx>,
1468 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1469 display_fn(move |f| {
1470 f.write_str(self.assoc.name.as_str())?;
1472 write!(f, "{:#}", self.assoc.args.print(cx))?;
1474 write!(f, "{}", self.assoc.args.print(cx))?;
1477 clean::TypeBindingKind::Equality { ref term } => {
1479 write!(f, " = {:#}", term.print(cx))?;
1481 write!(f, " = {}", term.print(cx))?;
1484 clean::TypeBindingKind::Constraint { ref bounds } => {
1485 if !bounds.is_empty() {
1487 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1489 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1499 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1500 display_fn(move |f| {
1501 let quot = if f.alternate() { "\"" } else { """ };
1503 Abi::Rust => Ok(()),
1504 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1509 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1510 if v { "default " } else { "" }
1513 impl clean::GenericArg {
1514 pub(crate) fn print<'a, 'tcx: 'a>(
1516 cx: &'a Context<'tcx>,
1517 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1518 display_fn(move |f| match self {
1519 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1520 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1521 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1522 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1527 impl clean::types::Term {
1528 pub(crate) fn print<'a, 'tcx: 'a>(
1530 cx: &'a Context<'tcx>,
1531 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1533 clean::types::Term::Type(ty) => ty.print(cx),
1539 pub(crate) fn display_fn(
1540 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1541 ) -> impl fmt::Display {
1542 struct WithFormatter<F>(Cell<Option<F>>);
1544 impl<F> fmt::Display for WithFormatter<F>
1546 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549 (self.0.take()).unwrap()(f)
1553 WithFormatter(Cell::new(Some(f)))