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.
12 use rustc_attr::{ConstStability, StabilityLevel};
13 use rustc_data_structures::captures::Captures;
14 use rustc_data_structures::fx::FxHashSet;
16 use rustc_hir::def::DefKind;
17 use rustc_hir::def_id::DefId;
19 use rustc_middle::ty::DefIdTree;
20 use rustc_middle::ty::TyCtxt;
21 use rustc_span::def_id::CRATE_DEF_INDEX;
22 use rustc_span::{sym, Symbol};
23 use rustc_target::spec::abi::Abi;
26 self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
29 use crate::formats::item_type::ItemType;
30 use crate::html::escape::Escape;
31 use crate::html::render::Context;
33 use super::url_parts_builder::estimate_item_path_byte_length;
34 use super::url_parts_builder::UrlPartsBuilder;
37 fn print(self, buffer: &mut Buffer);
42 F: FnOnce(&mut Buffer),
44 fn print(self, buffer: &mut Buffer) {
49 impl Print for String {
50 fn print(self, buffer: &mut Buffer) {
51 buffer.write_str(&self);
55 impl Print for &'_ str {
56 fn print(self, buffer: &mut Buffer) {
57 buffer.write_str(self);
61 #[derive(Debug, Clone)]
68 crate fn empty_from(v: &Buffer) -> Buffer {
69 Buffer { for_html: v.for_html, buffer: String::new() }
72 crate fn html() -> Buffer {
73 Buffer { for_html: true, buffer: String::new() }
76 crate fn new() -> Buffer {
77 Buffer { for_html: false, buffer: String::new() }
80 crate fn is_empty(&self) -> bool {
81 self.buffer.is_empty()
84 crate fn into_inner(self) -> String {
88 crate fn insert_str(&mut self, idx: usize, s: &str) {
89 self.buffer.insert_str(idx, s);
92 crate fn push_str(&mut self, s: &str) {
93 self.buffer.push_str(s);
96 crate fn push_buffer(&mut self, other: Buffer) {
97 self.buffer.push_str(&other.buffer);
100 // Intended for consumption by write! and writeln! (std::fmt) but without
101 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
103 crate fn write_str(&mut self, s: &str) {
104 self.buffer.push_str(s);
107 // Intended for consumption by write! and writeln! (std::fmt) but without
108 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
110 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
112 self.buffer.write_fmt(v).unwrap();
115 crate fn to_display<T: Print>(mut self, t: T) -> String {
120 crate fn is_for_html(&self) -> bool {
124 crate fn reserve(&mut self, additional: usize) {
125 self.buffer.reserve(additional)
129 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
130 display_fn(move |f| {
131 for (i, item) in items.enumerate() {
135 fmt::Display::fmt(&item, f)?;
141 crate fn print_generic_bounds<'a, 'tcx: 'a>(
142 bounds: &'a [clean::GenericBound],
143 cx: &'a Context<'tcx>,
144 ) -> impl fmt::Display + 'a + Captures<'tcx> {
145 display_fn(move |f| {
146 let mut bounds_dup = FxHashSet::default();
148 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
152 fmt::Display::fmt(&bound.print(cx), f)?;
158 impl clean::GenericParamDef {
159 crate fn print<'a, 'tcx: 'a>(
161 cx: &'a Context<'tcx>,
162 ) -> impl fmt::Display + 'a + Captures<'tcx> {
163 display_fn(move |f| match &self.kind {
164 clean::GenericParamDefKind::Lifetime { outlives } => {
165 write!(f, "{}", self.name)?;
167 if !outlives.is_empty() {
169 for (i, lt) in outlives.iter().enumerate() {
173 write!(f, "{}", lt.print())?;
179 clean::GenericParamDefKind::Type { bounds, default, .. } => {
180 f.write_str(self.name.as_str())?;
182 if !bounds.is_empty() {
184 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
186 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
190 if let Some(ref ty) = default {
192 write!(f, " = {:#}", ty.print(cx))?;
194 write!(f, " = {}", ty.print(cx))?;
200 clean::GenericParamDefKind::Const { ty, default, .. } => {
202 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
204 write!(f, "const {}: {}", self.name, ty.print(cx))?;
207 if let Some(default) = default {
209 write!(f, " = {:#}", default)?;
211 write!(f, " = {}", default)?;
221 impl clean::Generics {
222 crate fn print<'a, 'tcx: 'a>(
224 cx: &'a Context<'tcx>,
225 ) -> impl fmt::Display + 'a + Captures<'tcx> {
226 display_fn(move |f| {
227 let mut real_params =
228 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
229 if real_params.peek().is_none() {
234 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx))))
236 write!(f, "<{}>", comma_sep(real_params.map(|g| g.print(cx))))
242 /// * The Generics from which to emit a where-clause.
243 /// * The number of spaces to indent each line with.
244 /// * Whether the where-clause needs to add a comma and newline after the last bound.
245 crate fn print_where_clause<'a, 'tcx: 'a>(
246 gens: &'a clean::Generics,
247 cx: &'a Context<'tcx>,
250 ) -> impl fmt::Display + 'a + Captures<'tcx> {
251 display_fn(move |f| {
252 if gens.where_predicates.is_empty() {
255 let mut clause = String::new();
257 clause.push_str(" where");
260 clause.push_str(" <span class=\"where fmt-newline\">where");
262 clause.push_str(" <span class=\"where\">where");
265 for (i, pred) in gens.where_predicates.iter().enumerate() {
269 clause.push_str("<br>");
273 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
275 let for_prefix = match bound_params.len() {
277 _ if f.alternate() => {
280 comma_sep(bound_params.iter().map(|lt| lt.print()))
285 comma_sep(bound_params.iter().map(|lt| lt.print()))
290 clause.push_str(&format!(
294 print_generic_bounds(bounds, cx)
297 clause.push_str(&format!(
301 print_generic_bounds(bounds, cx)
305 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
306 clause.push_str(&format!(
311 .map(|b| b.print(cx).to_string())
316 clean::WherePredicate::EqPredicate { lhs, rhs } => {
318 clause.push_str(&format!("{:#} == {:#}", lhs.print(cx), rhs.print(cx),));
320 clause.push_str(&format!("{} == {}", lhs.print(cx), rhs.print(cx),));
325 if i < gens.where_predicates.len() - 1 || end_newline {
331 // add a space so stripping <br> tags and breaking spaces still renders properly
335 clause.push_str(" ");
340 clause.push_str("</span>");
341 let padding = " ".repeat(indent + 4);
342 clause = clause.replace("<br>", &format!("<br>{}", padding));
343 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
345 clause.insert_str(0, "<br>");
348 write!(f, "{}", clause)
352 impl clean::Lifetime {
353 crate fn print(&self) -> impl fmt::Display + '_ {
358 impl clean::Constant {
359 crate fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
360 let expr = self.expr(tcx);
363 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
369 impl clean::PolyTrait {
370 fn print<'a, 'tcx: 'a>(
372 cx: &'a Context<'tcx>,
373 ) -> impl fmt::Display + 'a + Captures<'tcx> {
374 display_fn(move |f| {
375 if !self.generic_params.is_empty() {
380 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
386 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
391 write!(f, "{:#}", self.trait_.print(cx))
393 write!(f, "{}", self.trait_.print(cx))
399 impl clean::GenericBound {
400 crate fn print<'a, 'tcx: 'a>(
402 cx: &'a Context<'tcx>,
403 ) -> impl fmt::Display + 'a + Captures<'tcx> {
404 display_fn(move |f| match self {
405 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
406 clean::GenericBound::TraitBound(ty, modifier) => {
407 let modifier_str = match modifier {
408 hir::TraitBoundModifier::None => "",
409 hir::TraitBoundModifier::Maybe => "?",
410 hir::TraitBoundModifier::MaybeConst => "~const",
413 write!(f, "{}{:#}", modifier_str, ty.print(cx))
415 write!(f, "{}{}", modifier_str, ty.print(cx))
422 impl clean::GenericArgs {
423 fn print<'a, 'tcx: 'a>(
425 cx: &'a Context<'tcx>,
426 ) -> impl fmt::Display + 'a + Captures<'tcx> {
427 display_fn(move |f| {
429 clean::GenericArgs::AngleBracketed { args, bindings } => {
430 if !args.is_empty() || !bindings.is_empty() {
434 f.write_str("<")?;
436 let mut comma = false;
443 write!(f, "{:#}", arg.print(cx))?;
445 write!(f, "{}", arg.print(cx))?;
448 for binding in bindings {
454 write!(f, "{:#}", binding.print(cx))?;
456 write!(f, "{}", binding.print(cx))?;
462 f.write_str(">")?;
466 clean::GenericArgs::Parenthesized { inputs, output } => {
468 let mut comma = false;
475 write!(f, "{:#}", ty.print(cx))?;
477 write!(f, "{}", ty.print(cx))?;
481 if let Some(ref ty) = *output {
483 write!(f, " -> {:#}", ty.print(cx))?;
485 write!(f, " -> {}", ty.print(cx))?;
495 // Possible errors when computing href link source for a `DefId`
496 crate enum HrefError {
497 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
499 /// This can only happen for non-local items.
500 DocumentationNotBuilt,
501 /// This can only happen for non-local items when `--document-private-items` is not passed.
503 // Not in external cache, href link should be in same page
507 // Panics if `syms` is empty.
508 crate fn join_with_double_colon(syms: &[Symbol]) -> String {
509 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
510 s.push_str(&syms[0].as_str());
511 for sym in &syms[1..] {
513 s.push_str(&sym.as_str());
518 crate fn href_with_root_path(
521 root_path: Option<&str>,
522 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
524 let def_kind = tcx.def_kind(did);
525 let did = match def_kind {
526 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
527 // documented on their parent's page
528 tcx.parent(did).unwrap()
532 let cache = cx.cache();
533 let relative_to = &cx.current;
534 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
535 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
539 && !cache.access_levels.is_public(did)
540 && !cache.document_private
541 && !cache.primitive_locations.values().any(|&id| id == did)
543 return Err(HrefError::Private);
546 let mut is_remote = false;
547 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
548 Some(&(ref fqp, shortty)) => (fqp, shortty, {
549 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
550 debug!(?fqp, ?shortty, ?module_fqp);
551 href_relative_parts(module_fqp, relative_to).collect()
554 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
555 let module_fqp = to_module_fqp(shortty, fqp);
559 match cache.extern_locations[&did.krate] {
560 ExternalLocation::Remote(ref s) => {
562 let s = s.trim_end_matches('/');
563 let mut builder = UrlPartsBuilder::singleton(s);
564 builder.extend(module_fqp.iter().copied());
567 ExternalLocation::Local => {
568 href_relative_parts(module_fqp, relative_to).collect()
570 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
574 return Err(HrefError::NotInExternalCache);
579 if let Some(root_path) = root_path {
580 let root = root_path.trim_end_matches('/');
581 url_parts.push_front(root);
586 ItemType::Module => {
587 url_parts.push("index.html");
590 let prefix = shortty.as_str();
591 let last = fqp.last().unwrap();
592 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
595 Ok((url_parts.finish(), shortty, fqp.to_vec()))
598 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
599 href_with_root_path(did, cx, None)
602 /// Both paths should only be modules.
603 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
604 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
605 crate fn href_relative_parts<'fqp>(
607 relative_to_fqp: &[Symbol],
608 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
609 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
610 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
612 let dissimilar_part_count = relative_to_fqp.len() - i;
613 let fqp_module = &fqp[i..fqp.len()];
614 return box iter::repeat(sym::dotdot)
615 .take(dissimilar_part_count)
616 .chain(fqp_module.iter().copied());
619 // e.g. linking to std::sync::atomic from std::sync
620 if relative_to_fqp.len() < fqp.len() {
621 box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
622 // e.g. linking to std::sync from std::sync::atomic
623 } else if fqp.len() < relative_to_fqp.len() {
624 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
625 box iter::repeat(sym::dotdot).take(dissimilar_part_count)
626 // linking to the same module
632 /// Used to render a [`clean::Path`].
633 fn resolved_path<'cx>(
634 w: &mut fmt::Formatter<'_>,
639 cx: &'cx Context<'_>,
641 let last = path.segments.last().unwrap();
644 for seg in &path.segments[..path.segments.len() - 1] {
645 write!(w, "{}::", seg.name)?;
649 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
651 let path = if use_absolute {
652 if let Ok((_, _, fqp)) = href(did, cx) {
655 join_with_double_colon(&fqp[..fqp.len() - 1]),
656 anchor(did, *fqp.last().unwrap(), cx)
659 last.name.to_string()
662 anchor(did, last.name, cx).to_string()
664 write!(w, "{}{}", path, last.args.print(cx))?;
670 f: &mut fmt::Formatter<'_>,
671 prim: clean::PrimitiveType,
676 let mut needs_termination = false;
678 match m.primitive_locations.get(&prim) {
679 Some(&def_id) if def_id.is_local() => {
680 let len = cx.current.len();
681 let len = if len == 0 { 0 } else { len - 1 };
684 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
688 needs_termination = true;
691 let loc = match m.extern_locations[&def_id.krate] {
692 ExternalLocation::Remote(ref s) => {
693 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
694 let builder: UrlPartsBuilder =
695 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
700 ExternalLocation::Local => {
701 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
702 Some(if cx.current.first() == Some(&cname_sym) {
703 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
705 iter::repeat(sym::dotdot)
706 .take(cx.current.len())
707 .chain(iter::once(cname_sym))
711 ExternalLocation::Unknown => None,
713 if let Some(mut loc) = loc {
714 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
715 write!(f, "<a class=\"primitive\" href=\"{}\">", loc.finish())?;
716 needs_termination = true;
722 write!(f, "{}", name)?;
723 if needs_termination {
729 /// Helper to render type parameters
730 fn tybounds<'a, 'tcx: 'a>(
731 bounds: &'a [clean::PolyTrait],
732 lt: &'a Option<clean::Lifetime>,
733 cx: &'a Context<'tcx>,
734 ) -> impl fmt::Display + 'a + Captures<'tcx> {
735 display_fn(move |f| {
736 for (i, bound) in bounds.iter().enumerate() {
741 fmt::Display::fmt(&bound.print(cx), f)?;
744 if let Some(lt) = lt {
746 fmt::Display::fmt(<.print(), f)?;
752 crate fn anchor<'a, 'cx: 'a>(
755 cx: &'cx Context<'_>,
756 ) -> impl fmt::Display + 'a {
757 let parts = href(did, cx);
758 display_fn(move |f| {
759 if let Ok((url, short_ty, fqp)) = parts {
762 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
766 join_with_double_colon(&fqp),
770 write!(f, "{}", text)
777 f: &mut fmt::Formatter<'_>,
779 cx: &'cx Context<'_>,
781 trace!("fmt_type(t = {:?})", t);
784 clean::Generic(name) => write!(f, "{}", name),
785 clean::Type::Path { ref path } => {
786 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
787 let did = path.def_id();
788 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
790 clean::DynTrait(ref bounds, ref lt) => {
791 f.write_str("dyn ")?;
792 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
794 clean::Infer => write!(f, "_"),
795 clean::Primitive(clean::PrimitiveType::Never) => {
796 primitive_link(f, PrimitiveType::Never, "!", cx)
798 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
799 clean::BareFunction(ref decl) => {
804 decl.print_hrtb_with_space(cx),
805 decl.unsafety.print_with_space(),
806 print_abi_with_space(decl.abi),
813 decl.print_hrtb_with_space(cx),
814 decl.unsafety.print_with_space(),
815 print_abi_with_space(decl.abi)
817 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
818 write!(f, "{}", decl.decl.print(cx))
821 clean::Tuple(ref typs) => {
823 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
825 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
826 // Carry `f.alternate()` into this display w/o branching manually.
827 fmt::Display::fmt(&one.print(cx), f)?;
828 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
831 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
832 for (i, item) in many.iter().enumerate() {
836 fmt::Display::fmt(&item.print(cx), f)?;
838 primitive_link(f, PrimitiveType::Tuple, ")", cx)
842 clean::Slice(ref t) => {
843 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
844 fmt::Display::fmt(&t.print(cx), f)?;
845 primitive_link(f, PrimitiveType::Slice, "]", cx)
847 clean::Array(ref t, ref n) => {
848 primitive_link(f, PrimitiveType::Array, "[", cx)?;
849 fmt::Display::fmt(&t.print(cx), f)?;
851 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
853 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
856 clean::RawPointer(m, ref t) => {
858 hir::Mutability::Mut => "mut",
859 hir::Mutability::Not => "const",
862 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
863 let text = if f.alternate() {
864 format!("*{} {:#}", m, t.print(cx))
866 format!("*{} {}", m, t.print(cx))
868 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
870 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
871 fmt::Display::fmt(&t.print(cx), f)
874 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
876 Some(l) => format!("{} ", l.print()),
879 let m = mutability.print_with_space();
880 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
882 clean::Slice(ref bt) => {
883 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
885 clean::Generic(_) => {
889 PrimitiveType::Slice,
890 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
896 PrimitiveType::Slice,
897 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
905 PrimitiveType::Slice,
906 &format!("{}{}{}[", amp, lt, m),
910 write!(f, "{:#}", bt.print(cx))?;
912 write!(f, "{}", bt.print(cx))?;
914 primitive_link(f, PrimitiveType::Slice, "]", cx)
918 clean::DynTrait(ref bounds, ref trait_lt)
919 if bounds.len() > 1 || trait_lt.is_some() =>
921 write!(f, "{}{}{}(", amp, lt, m)?;
922 fmt_type(ty, f, use_absolute, cx)?;
925 clean::Generic(..) => {
928 PrimitiveType::Reference,
929 &format!("{}{}{}", amp, lt, m),
932 fmt_type(ty, f, use_absolute, cx)
935 write!(f, "{}{}{}", amp, lt, m)?;
936 fmt_type(ty, f, use_absolute, cx)
940 clean::ImplTrait(ref bounds) => {
942 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
944 write!(f, "impl {}", print_generic_bounds(bounds, cx))
947 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
948 let should_show_cast = !trait_.segments.is_empty()
950 .zip(Some(trait_.def_id()))
951 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_);
953 if should_show_cast {
954 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
956 write!(f, "{:#}::", self_type.print(cx))?
959 if should_show_cast {
960 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
962 write!(f, "{}::", self_type.print(cx))?
965 // It's pretty unsightly to look at `<A as B>::C` in output, and
966 // we've got hyperlinking on our side, so try to avoid longer
967 // notation as much as possible by making `C` a hyperlink to trait
968 // `B` to disambiguate.
970 // FIXME: this is still a lossy conversion and there should probably
971 // be a better way of representing this in general? Most of
972 // the ugliness comes from inlining across crates where
973 // everything comes in as a fully resolved QPath (hard to
975 match href(trait_.def_id(), cx) {
976 Ok((ref url, _, ref path)) if !f.alternate() => {
979 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
980 title=\"type {path}::{name}\">{name}</a>",
982 shortty = ItemType::AssocType,
984 path = join_with_double_colon(path),
987 _ => write!(f, "{}", name)?,
995 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
997 cx: &'a Context<'tcx>,
998 ) -> impl fmt::Display + 'b + Captures<'tcx> {
999 display_fn(move |f| fmt_type(self, f, false, cx))
1004 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1006 cx: &'a Context<'tcx>,
1007 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1008 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1013 crate fn print<'a, 'tcx: 'a>(
1016 cx: &'a Context<'tcx>,
1017 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1018 display_fn(move |f| {
1020 write!(f, "impl{:#} ", self.generics.print(cx))?;
1022 write!(f, "impl{} ", self.generics.print(cx))?;
1025 if let Some(ref ty) = self.trait_ {
1026 match self.polarity {
1027 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1028 ty::ImplPolarity::Negative => write!(f, "!")?,
1030 fmt::Display::fmt(&ty.print(cx), f)?;
1031 write!(f, " for ")?;
1034 if let Some(ref ty) = self.kind.as_blanket_ty() {
1035 fmt_type(ty, f, use_absolute, cx)?;
1037 fmt_type(&self.for_, f, use_absolute, cx)?;
1040 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1046 impl clean::Arguments {
1047 crate fn print<'a, 'tcx: 'a>(
1049 cx: &'a Context<'tcx>,
1050 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1051 display_fn(move |f| {
1052 for (i, input) in self.values.iter().enumerate() {
1053 if !input.name.is_empty() {
1054 write!(f, "{}: ", input.name)?;
1057 write!(f, "{:#}", input.type_.print(cx))?;
1059 write!(f, "{}", input.type_.print(cx))?;
1061 if i + 1 < self.values.len() {
1070 impl clean::FnRetTy {
1071 crate fn print<'a, 'tcx: 'a>(
1073 cx: &'a Context<'tcx>,
1074 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1075 display_fn(move |f| match self {
1076 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1077 clean::Return(ty) if f.alternate() => {
1078 write!(f, " -> {:#}", ty.print(cx))
1080 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1081 clean::DefaultReturn => Ok(()),
1086 impl clean::BareFunctionDecl {
1087 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1089 cx: &'a Context<'tcx>,
1090 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1091 display_fn(move |f| {
1092 if !self.generic_params.is_empty() {
1096 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
1105 impl clean::FnDecl {
1106 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1108 cx: &'a Context<'tcx>,
1109 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1110 display_fn(move |f| {
1111 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1115 "({args:#}{ellipsis}){arrow:#}",
1116 args = self.inputs.print(cx),
1117 ellipsis = ellipsis,
1118 arrow = self.output.print(cx)
1123 "({args}{ellipsis}){arrow}",
1124 args = self.inputs.print(cx),
1125 ellipsis = ellipsis,
1126 arrow = self.output.print(cx)
1132 /// * `header_len`: The length of the function header and name. In other words, the number of
1133 /// characters in the function declaration up to but not including the parentheses.
1134 /// <br>Used to determine line-wrapping.
1135 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1137 /// * `asyncness`: Whether the function is async or not.
1138 crate fn full_print<'a, 'tcx: 'a>(
1142 asyncness: hir::IsAsync,
1143 cx: &'a Context<'tcx>,
1144 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1145 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1148 fn inner_full_print(
1152 asyncness: hir::IsAsync,
1153 f: &mut fmt::Formatter<'_>,
1156 let amp = if f.alternate() { "&" } else { "&" };
1157 let mut args = String::new();
1158 let mut args_plain = String::new();
1159 for (i, input) in self.inputs.values.iter().enumerate() {
1161 args.push_str("<br>");
1164 if let Some(selfty) = input.to_self() {
1166 clean::SelfValue => {
1167 args.push_str("self");
1168 args_plain.push_str("self");
1170 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1171 args.push_str(&format!(
1175 mtbl.print_with_space()
1177 args_plain.push_str(&format!(
1180 mtbl.print_with_space()
1183 clean::SelfBorrowed(None, mtbl) => {
1184 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1185 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1187 clean::SelfExplicit(ref typ) => {
1189 args.push_str(&format!("self: {:#}", typ.print(cx)));
1191 args.push_str(&format!("self: {}", typ.print(cx)));
1193 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1198 args.push_str(" <br>");
1199 args_plain.push(' ');
1202 args.push_str("const ");
1203 args_plain.push_str("const ");
1205 if !input.name.is_empty() {
1206 args.push_str(&format!("{}: ", input.name));
1207 args_plain.push_str(&format!("{}: ", input.name));
1211 args.push_str(&format!("{:#}", input.type_.print(cx)));
1213 args.push_str(&input.type_.print(cx).to_string());
1215 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1217 if i + 1 < self.inputs.values.len() {
1219 args_plain.push(',');
1223 let mut args_plain = format!("({})", args_plain);
1225 if self.c_variadic {
1226 args.push_str(",<br> ...");
1227 args_plain.push_str(", ...");
1231 let arrow = if let hir::IsAsync::Async = asyncness {
1232 let output = self.sugared_async_return_type();
1233 arrow_plain = format!("{:#}", output.print(cx));
1234 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1236 arrow_plain = format!("{:#}", self.output.print(cx));
1237 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1240 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1241 let output = if declaration_len > 80 {
1242 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1243 let close_pad = format!("<br>{}", " ".repeat(indent));
1245 "({args}{close}){arrow}",
1246 args = args.replace("<br>", &full_pad),
1251 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1255 write!(f, "{}", output.replace("<br>", "\n"))
1257 write!(f, "{}", output)
1262 impl clean::Visibility {
1263 crate fn print_with_space<'a, 'tcx: 'a>(
1266 cx: &'a Context<'tcx>,
1267 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1268 let to_print = match self {
1269 clean::Public => "pub ".to_owned(),
1270 clean::Inherited => String::new(),
1271 clean::Visibility::Restricted(vis_did) => {
1272 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1273 // However, rustdoc currently never displays a module's
1274 // visibility, so it shouldn't matter.
1275 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1277 if vis_did.index == CRATE_DEF_INDEX {
1278 "pub(crate) ".to_owned()
1279 } else if parent_module == Some(vis_did) {
1280 // `pub(in foo)` where `foo` is the parent module
1281 // is the same as no visibility modifier
1283 } else if parent_module
1284 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1288 "pub(super) ".to_owned()
1290 let path = cx.tcx().def_path(vis_did);
1291 debug!("path={:?}", path);
1292 // modified from `resolved_path()` to work with `DefPathData`
1293 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1294 let anchor = anchor(vis_did, last_name, cx).to_string();
1296 let mut s = "pub(in ".to_owned();
1297 for seg in &path.data[..path.data.len() - 1] {
1298 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1300 s.push_str(&format!("{}) ", anchor));
1305 display_fn(move |f| f.write_str(&to_print))
1308 /// This function is the same as print_with_space, except that it renders no links.
1309 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1311 crate fn to_src_with_space<'a, 'tcx: 'a>(
1315 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1316 let to_print = match self {
1317 clean::Public => "pub ".to_owned(),
1318 clean::Inherited => String::new(),
1319 clean::Visibility::Restricted(vis_did) => {
1320 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1321 // However, rustdoc currently never displays a module's
1322 // visibility, so it shouldn't matter.
1323 let parent_module = find_nearest_parent_module(tcx, item_did);
1325 if vis_did.index == CRATE_DEF_INDEX {
1326 "pub(crate) ".to_owned()
1327 } else if parent_module == Some(vis_did) {
1328 // `pub(in foo)` where `foo` is the parent module
1329 // is the same as no visibility modifier
1331 } else if parent_module
1332 .map(|parent| find_nearest_parent_module(tcx, parent))
1336 "pub(super) ".to_owned()
1338 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1342 display_fn(move |f| f.write_str(&to_print))
1346 crate trait PrintWithSpace {
1347 fn print_with_space(&self) -> &str;
1350 impl PrintWithSpace for hir::Unsafety {
1351 fn print_with_space(&self) -> &str {
1353 hir::Unsafety::Unsafe => "unsafe ",
1354 hir::Unsafety::Normal => "",
1359 impl PrintWithSpace for hir::IsAsync {
1360 fn print_with_space(&self) -> &str {
1362 hir::IsAsync::Async => "async ",
1363 hir::IsAsync::NotAsync => "",
1368 impl PrintWithSpace for hir::Mutability {
1369 fn print_with_space(&self) -> &str {
1371 hir::Mutability::Not => "",
1372 hir::Mutability::Mut => "mut ",
1377 crate fn print_constness_with_space(c: &hir::Constness, s: Option<ConstStability>) -> &'static str {
1379 // const stable or when feature(staged_api) is not set
1381 hir::Constness::Const,
1382 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1384 | (hir::Constness::Const, None) => "const ",
1385 // const unstable or not const
1390 impl clean::Import {
1391 crate fn print<'a, 'tcx: 'a>(
1393 cx: &'a Context<'tcx>,
1394 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1395 display_fn(move |f| match self.kind {
1396 clean::ImportKind::Simple(name) => {
1397 if name == self.source.path.last() {
1398 write!(f, "use {};", self.source.print(cx))
1400 write!(f, "use {} as {};", self.source.print(cx), name)
1403 clean::ImportKind::Glob => {
1404 if self.source.path.segments.is_empty() {
1407 write!(f, "use {}::*;", self.source.print(cx))
1414 impl clean::ImportSource {
1415 crate fn print<'a, 'tcx: 'a>(
1417 cx: &'a Context<'tcx>,
1418 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1419 display_fn(move |f| match self.did {
1420 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1422 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1423 write!(f, "{}::", seg.name)?;
1425 let name = self.path.last();
1426 if let hir::def::Res::PrimTy(p) = self.path.res {
1427 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1429 write!(f, "{}", name)?;
1437 impl clean::TypeBinding {
1438 crate fn print<'a, 'tcx: 'a>(
1440 cx: &'a Context<'tcx>,
1441 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1442 display_fn(move |f| {
1443 f.write_str(self.name.as_str())?;
1445 clean::TypeBindingKind::Equality { ref ty } => {
1447 write!(f, " = {:#}", ty.print(cx))?;
1449 write!(f, " = {}", ty.print(cx))?;
1452 clean::TypeBindingKind::Constraint { ref bounds } => {
1453 if !bounds.is_empty() {
1455 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1457 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1467 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1468 display_fn(move |f| {
1469 let quot = if f.alternate() { "\"" } else { """ };
1471 Abi::Rust => Ok(()),
1472 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1477 crate fn print_default_space<'a>(v: bool) -> &'a str {
1478 if v { "default " } else { "" }
1481 impl clean::GenericArg {
1482 crate fn print<'a, 'tcx: 'a>(
1484 cx: &'a Context<'tcx>,
1485 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1486 display_fn(move |f| match self {
1487 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1488 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1489 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1490 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1495 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1496 struct WithFormatter<F>(Cell<Option<F>>);
1498 impl<F> fmt::Display for WithFormatter<F>
1500 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503 (self.0.take()).unwrap()(f)
1507 WithFormatter(Cell::new(Some(f)))