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_id::DefId;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_span::def_id::CRATE_DEF_INDEX;
19 use rustc_target::spec::abi::Abi;
22 self, utils::find_nearest_parent_module, ExternalCrate, GetDefId, ItemId, PrimitiveType,
24 use crate::formats::item_type::ItemType;
25 use crate::html::escape::Escape;
26 use crate::html::render::cache::ExternalLocation;
27 use crate::html::render::Context;
30 fn print(self, buffer: &mut Buffer);
35 F: FnOnce(&mut Buffer),
37 fn print(self, buffer: &mut Buffer) {
42 impl Print for String {
43 fn print(self, buffer: &mut Buffer) {
44 buffer.write_str(&self);
48 impl Print for &'_ str {
49 fn print(self, buffer: &mut Buffer) {
50 buffer.write_str(self);
54 #[derive(Debug, Clone)]
61 crate fn empty_from(v: &Buffer) -> Buffer {
62 Buffer { for_html: v.for_html, buffer: String::new() }
65 crate fn html() -> Buffer {
66 Buffer { for_html: true, buffer: String::new() }
69 crate fn new() -> Buffer {
70 Buffer { for_html: false, buffer: String::new() }
73 crate fn is_empty(&self) -> bool {
74 self.buffer.is_empty()
77 crate fn into_inner(self) -> String {
81 crate fn insert_str(&mut self, idx: usize, s: &str) {
82 self.buffer.insert_str(idx, s);
85 crate fn push_str(&mut self, s: &str) {
86 self.buffer.push_str(s);
89 crate fn push_buffer(&mut self, other: Buffer) {
90 self.buffer.push_str(&other.buffer);
93 // Intended for consumption by write! and writeln! (std::fmt) but without
94 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
96 crate fn write_str(&mut self, s: &str) {
97 self.buffer.push_str(s);
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_fmt(&mut self, v: fmt::Arguments<'_>) {
105 self.buffer.write_fmt(v).unwrap();
108 crate fn to_display<T: Print>(mut self, t: T) -> String {
113 crate fn is_for_html(&self) -> bool {
117 crate fn reserve(&mut self, additional: usize) {
118 self.buffer.reserve(additional)
122 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
123 display_fn(move |f| {
124 for (i, item) in items.enumerate() {
128 fmt::Display::fmt(&item, f)?;
134 crate fn print_generic_bounds<'a, 'tcx: 'a>(
135 bounds: &'a [clean::GenericBound],
136 cx: &'a Context<'tcx>,
137 ) -> impl fmt::Display + 'a + Captures<'tcx> {
138 display_fn(move |f| {
139 let mut bounds_dup = FxHashSet::default();
142 bounds.iter().filter(|b| bounds_dup.insert(b.print(cx).to_string())).enumerate()
147 fmt::Display::fmt(&bound.print(cx), f)?;
153 impl clean::GenericParamDef {
154 crate fn print<'a, 'tcx: 'a>(
156 cx: &'a Context<'tcx>,
157 ) -> impl fmt::Display + 'a + Captures<'tcx> {
158 display_fn(move |f| match self.kind {
159 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
160 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
161 f.write_str(&*self.name.as_str())?;
163 if !bounds.is_empty() {
165 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
167 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
171 if let Some(ref ty) = default {
173 write!(f, " = {:#}", ty.print(cx))?;
175 write!(f, " = {}", ty.print(cx))?;
181 clean::GenericParamDefKind::Const { ref ty, ref default, .. } => {
183 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
185 write!(f, "const {}: {}", self.name, ty.print(cx))?;
188 if let Some(default) = default {
190 write!(f, " = {:#}", default)?;
192 write!(f, " = {}", default)?;
202 impl clean::Generics {
203 crate fn print<'a, 'tcx: 'a>(
205 cx: &'a Context<'tcx>,
206 ) -> impl fmt::Display + 'a + Captures<'tcx> {
207 display_fn(move |f| {
209 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
210 if real_params.is_empty() {
214 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
216 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
222 /// * The Generics from which to emit a where-clause.
223 /// * The number of spaces to indent each line with.
224 /// * Whether the where-clause needs to add a comma and newline after the last bound.
225 crate fn print_where_clause<'a, 'tcx: 'a>(
226 gens: &'a clean::Generics,
227 cx: &'a Context<'tcx>,
230 ) -> impl fmt::Display + 'a + Captures<'tcx> {
231 display_fn(move |f| {
232 if gens.where_predicates.is_empty() {
235 let mut clause = String::new();
237 clause.push_str(" where");
240 clause.push_str(" <span class=\"where fmt-newline\">where");
242 clause.push_str(" <span class=\"where\">where");
245 for (i, pred) in gens.where_predicates.iter().enumerate() {
249 clause.push_str("<br>");
253 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
255 let for_prefix = match bound_params.len() {
257 _ if f.alternate() => {
260 comma_sep(bound_params.iter().map(|lt| lt.print()))
265 comma_sep(bound_params.iter().map(|lt| lt.print()))
270 clause.push_str(&format!(
274 print_generic_bounds(bounds, cx)
277 clause.push_str(&format!(
281 print_generic_bounds(bounds, cx)
285 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
286 clause.push_str(&format!(
291 .map(|b| b.print(cx).to_string())
296 clean::WherePredicate::EqPredicate { lhs, rhs } => {
298 clause.push_str(&format!("{:#} == {:#}", lhs.print(cx), rhs.print(cx),));
300 clause.push_str(&format!("{} == {}", lhs.print(cx), rhs.print(cx),));
305 if i < gens.where_predicates.len() - 1 || end_newline {
311 // add a space so stripping <br> tags and breaking spaces still renders properly
315 clause.push_str(" ");
320 clause.push_str("</span>");
321 let padding = " ".repeat(indent + 4);
322 clause = clause.replace("<br>", &format!("<br>{}", padding));
323 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
325 clause.insert_str(0, "<br>");
328 write!(f, "{}", clause)
332 impl clean::Lifetime {
333 crate fn print(&self) -> impl fmt::Display + '_ {
338 impl clean::Constant {
339 crate fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
340 let expr = self.expr(tcx);
343 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
349 impl clean::PolyTrait {
350 fn print<'a, 'tcx: 'a>(
352 cx: &'a Context<'tcx>,
353 ) -> impl fmt::Display + 'a + Captures<'tcx> {
354 display_fn(move |f| {
355 if !self.generic_params.is_empty() {
360 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
366 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
371 write!(f, "{:#}", self.trait_.print(cx))
373 write!(f, "{}", self.trait_.print(cx))
379 impl clean::GenericBound {
380 crate fn print<'a, 'tcx: 'a>(
382 cx: &'a Context<'tcx>,
383 ) -> impl fmt::Display + 'a + Captures<'tcx> {
384 display_fn(move |f| match self {
385 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
386 clean::GenericBound::TraitBound(ty, modifier) => {
387 let modifier_str = match modifier {
388 hir::TraitBoundModifier::None => "",
389 hir::TraitBoundModifier::Maybe => "?",
390 hir::TraitBoundModifier::MaybeConst => "?const",
393 write!(f, "{}{:#}", modifier_str, ty.print(cx))
395 write!(f, "{}{}", modifier_str, ty.print(cx))
402 impl clean::GenericArgs {
403 fn print<'a, 'tcx: 'a>(
405 cx: &'a Context<'tcx>,
406 ) -> impl fmt::Display + 'a + Captures<'tcx> {
407 display_fn(move |f| {
409 clean::GenericArgs::AngleBracketed { args, bindings } => {
410 if !args.is_empty() || !bindings.is_empty() {
414 f.write_str("<")?;
416 let mut comma = false;
423 write!(f, "{:#}", arg.print(cx))?;
425 write!(f, "{}", arg.print(cx))?;
428 for binding in bindings {
434 write!(f, "{:#}", binding.print(cx))?;
436 write!(f, "{}", binding.print(cx))?;
442 f.write_str(">")?;
446 clean::GenericArgs::Parenthesized { inputs, output } => {
448 let mut comma = false;
455 write!(f, "{:#}", ty.print(cx))?;
457 write!(f, "{}", ty.print(cx))?;
461 if let Some(ref ty) = *output {
463 write!(f, " -> {:#}", ty.print(cx))?;
465 write!(f, " -> {}", ty.print(cx))?;
475 // Possible errors when computing href link source for a `DefId`
476 crate enum HrefError {
477 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
479 /// This can only happen for non-local items.
480 DocumentationNotBuilt,
481 /// This can only happen for non-local items when `--document-private-items` is not passed.
483 // Not in external cache, href link should be in same page
487 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<String>), HrefError> {
488 let cache = &cx.cache();
489 let relative_to = &cx.current;
490 fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
491 if shortty == ItemType::Module { &fqp[..] } else { &fqp[..fqp.len() - 1] }
494 if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
495 return Err(HrefError::Private);
498 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
499 Some(&(ref fqp, shortty)) => (fqp, shortty, {
500 let module_fqp = to_module_fqp(shortty, fqp);
501 href_relative_parts(module_fqp, relative_to)
504 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
505 let module_fqp = to_module_fqp(shortty, fqp);
509 match cache.extern_locations[&did.krate] {
510 ExternalLocation::Remote(ref s) => {
511 let s = s.trim_end_matches('/');
512 let mut s = vec![&s[..]];
513 s.extend(module_fqp[..].iter().map(String::as_str));
516 ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
517 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
521 return Err(HrefError::NotInExternalCache);
525 let last = &fqp.last().unwrap()[..];
528 ItemType::Module => {
529 url_parts.push("index.html");
532 filename = format!("{}.{}.html", shortty.as_str(), last);
533 url_parts.push(&filename);
536 Ok((url_parts.join("/"), shortty, fqp.to_vec()))
539 /// Both paths should only be modules.
540 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
541 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
542 crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String]) -> Vec<&'a str> {
543 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
544 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
546 let dissimilar_part_count = relative_to_fqp.len() - i;
547 let fqp_module = fqp[i..fqp.len()].iter().map(String::as_str);
548 return iter::repeat("..").take(dissimilar_part_count).chain(fqp_module).collect();
551 // e.g. linking to std::sync::atomic from std::sync
552 if relative_to_fqp.len() < fqp.len() {
553 fqp[relative_to_fqp.len()..fqp.len()].iter().map(String::as_str).collect()
554 // e.g. linking to std::sync from std::sync::atomic
555 } else if fqp.len() < relative_to_fqp.len() {
556 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
557 iter::repeat("..").take(dissimilar_part_count).collect()
558 // linking to the same module
564 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
565 /// rendering function with the necessary arguments for linking to a local path.
566 fn resolved_path<'a, 'cx: 'a>(
567 w: &mut fmt::Formatter<'_>,
572 cx: &'cx Context<'_>,
574 let last = path.segments.last().unwrap();
577 for seg in &path.segments[..path.segments.len() - 1] {
578 write!(w, "{}::", seg.name)?;
582 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
584 let path = if use_absolute {
585 if let Ok((_, _, fqp)) = href(did, cx) {
588 fqp[..fqp.len() - 1].join("::"),
589 anchor(did, fqp.last().unwrap(), cx)
592 last.name.to_string()
595 anchor(did, &*last.name.as_str(), cx).to_string()
597 write!(w, "{}{}", path, last.args.print(cx))?;
603 f: &mut fmt::Formatter<'_>,
604 prim: clean::PrimitiveType,
609 let mut needs_termination = false;
611 match m.primitive_locations.get(&prim) {
612 Some(&def_id) if def_id.is_local() => {
613 let len = cx.current.len();
614 let len = if len == 0 { 0 } else { len - 1 };
617 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
621 needs_termination = true;
625 let loc = match m.extern_locations[&def_id.krate] {
626 ExternalLocation::Remote(ref s) => {
628 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
629 Some(vec![s.trim_end_matches('/'), &cname_str[..]])
631 ExternalLocation::Local => {
633 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
634 Some(if cx.current.first().map(|x| &x[..]) == Some(&cname_str[..]) {
635 iter::repeat("..").take(cx.current.len() - 1).collect()
637 let cname = iter::once(&cname_str[..]);
638 iter::repeat("..").take(cx.current.len()).chain(cname).collect()
641 ExternalLocation::Unknown => None,
643 if let Some(loc) = loc {
646 "<a class=\"primitive\" href=\"{}/primitive.{}.html\">",
650 needs_termination = true;
656 write!(f, "{}", name)?;
657 if needs_termination {
663 /// Helper to render type parameters
664 fn tybounds<'a, 'tcx: 'a>(
665 bounds: &'a Vec<clean::PolyTrait>,
666 lt: &'a Option<clean::Lifetime>,
667 cx: &'a Context<'tcx>,
668 ) -> impl fmt::Display + 'a + Captures<'tcx> {
669 display_fn(move |f| {
670 for (i, bound) in bounds.iter().enumerate() {
675 fmt::Display::fmt(&bound.print(cx), f)?;
678 if let Some(lt) = lt {
680 fmt::Display::fmt(<.print(), f)?;
686 crate fn anchor<'a, 'cx: 'a>(
689 cx: &'cx Context<'_>,
690 ) -> impl fmt::Display + 'a {
691 let parts = href(did.into(), cx);
692 display_fn(move |f| {
693 if let Ok((url, short_ty, fqp)) = parts {
696 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
704 write!(f, "{}", text)
711 f: &mut fmt::Formatter<'_>,
713 cx: &'cx Context<'_>,
715 debug!("fmt_type(t = {:?})", t);
718 clean::Generic(name) => write!(f, "{}", name),
719 clean::ResolvedPath { did, ref path, is_generic } => {
720 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
721 resolved_path(f, did, path, is_generic, use_absolute, cx)
723 clean::DynTrait(ref bounds, ref lt) => {
724 f.write_str("dyn ")?;
725 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
727 clean::Infer => write!(f, "_"),
728 clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
729 clean::BareFunction(ref decl) => {
734 decl.print_hrtb_with_space(cx),
735 decl.unsafety.print_with_space(),
736 print_abi_with_space(decl.abi),
743 decl.print_hrtb_with_space(cx),
744 decl.unsafety.print_with_space(),
745 print_abi_with_space(decl.abi)
747 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
748 write!(f, "{}", decl.decl.print(cx))
751 clean::Tuple(ref typs) => {
753 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
755 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
756 // Carry `f.alternate()` into this display w/o branching manually.
757 fmt::Display::fmt(&one.print(cx), f)?;
758 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
761 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
762 for (i, item) in many.iter().enumerate() {
766 fmt::Display::fmt(&item.print(cx), f)?;
768 primitive_link(f, PrimitiveType::Tuple, ")", cx)
772 clean::Slice(ref t) => {
773 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
774 fmt::Display::fmt(&t.print(cx), f)?;
775 primitive_link(f, PrimitiveType::Slice, "]", cx)
777 clean::Array(ref t, ref n) => {
778 primitive_link(f, PrimitiveType::Array, "[", cx)?;
779 fmt::Display::fmt(&t.print(cx), f)?;
781 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
783 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
786 clean::Never => primitive_link(f, PrimitiveType::Never, "!", cx),
787 clean::RawPointer(m, ref t) => {
789 hir::Mutability::Mut => "mut",
790 hir::Mutability::Not => "const",
793 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
797 clean::PrimitiveType::RawPointer,
798 &format!("*{} {:#}", m, t.print(cx)),
804 clean::PrimitiveType::RawPointer,
805 &format!("*{} {}", m, t.print(cx)),
811 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
812 fmt::Display::fmt(&t.print(cx), f)
816 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
818 Some(l) => format!("{} ", l.print()),
821 let m = mutability.print_with_space();
822 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
824 clean::Slice(ref bt) => {
825 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
827 clean::Generic(_) => {
831 PrimitiveType::Slice,
832 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
838 PrimitiveType::Slice,
839 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
847 PrimitiveType::Slice,
848 &format!("{}{}{}[", amp, lt, m),
852 write!(f, "{:#}", bt.print(cx))?;
854 write!(f, "{}", bt.print(cx))?;
856 primitive_link(f, PrimitiveType::Slice, "]", cx)
860 clean::DynTrait(ref bounds, ref trait_lt)
861 if bounds.len() > 1 || trait_lt.is_some() =>
863 write!(f, "{}{}{}(", amp, lt, m)?;
864 fmt_type(&ty, f, use_absolute, cx)?;
867 clean::Generic(..) => {
870 PrimitiveType::Reference,
871 &format!("{}{}{}", amp, lt, m),
874 fmt_type(&ty, f, use_absolute, cx)
877 write!(f, "{}{}{}", amp, lt, m)?;
878 fmt_type(&ty, f, use_absolute, cx)
882 clean::ImplTrait(ref bounds) => {
884 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
886 write!(f, "impl {}", print_generic_bounds(bounds, cx))
889 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
890 let should_show_cast = match *trait_ {
891 box clean::ResolvedPath { ref path, .. } => {
892 !path.segments.is_empty()
894 .zip(trait_.def_id())
895 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
900 if should_show_cast {
901 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
903 write!(f, "{:#}::", self_type.print(cx))?
906 if should_show_cast {
907 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
909 write!(f, "{}::", self_type.print(cx))?
913 // It's pretty unsightly to look at `<A as B>::C` in output, and
914 // we've got hyperlinking on our side, so try to avoid longer
915 // notation as much as possible by making `C` a hyperlink to trait
916 // `B` to disambiguate.
918 // FIXME: this is still a lossy conversion and there should probably
919 // be a better way of representing this in general? Most of
920 // the ugliness comes from inlining across crates where
921 // everything comes in as a fully resolved QPath (hard to
923 box clean::ResolvedPath { did, .. } => {
924 match href(did.into(), cx) {
925 Ok((ref url, _, ref path)) if !f.alternate() => {
928 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
929 title=\"type {path}::{name}\">{name}</a>",
931 shortty = ItemType::AssocType,
933 path = path.join("::")
936 _ => write!(f, "{}", name)?,
940 _ => write!(f, "{}", name),
947 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
949 cx: &'a Context<'tcx>,
950 ) -> impl fmt::Display + 'b + Captures<'tcx> {
951 display_fn(move |f| fmt_type(self, f, false, cx))
956 crate fn print<'a, 'tcx: 'a>(
959 cx: &'a Context<'tcx>,
960 ) -> impl fmt::Display + 'a + Captures<'tcx> {
961 display_fn(move |f| {
963 write!(f, "impl{:#} ", self.generics.print(cx))?;
965 write!(f, "impl{} ", self.generics.print(cx))?;
968 if let Some(ref ty) = self.trait_ {
969 if self.negative_polarity {
972 fmt::Display::fmt(&ty.print(cx), f)?;
976 if let Some(ref ty) = self.blanket_impl {
977 fmt_type(ty, f, use_absolute, cx)?;
979 fmt_type(&self.for_, f, use_absolute, cx)?;
982 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
988 impl clean::Arguments {
989 crate fn print<'a, 'tcx: 'a>(
991 cx: &'a Context<'tcx>,
992 ) -> impl fmt::Display + 'a + Captures<'tcx> {
993 display_fn(move |f| {
994 for (i, input) in self.values.iter().enumerate() {
995 if !input.name.is_empty() {
996 write!(f, "{}: ", input.name)?;
999 write!(f, "{:#}", input.type_.print(cx))?;
1001 write!(f, "{}", input.type_.print(cx))?;
1003 if i + 1 < self.values.len() {
1012 impl clean::FnRetTy {
1013 crate fn print<'a, 'tcx: 'a>(
1015 cx: &'a Context<'tcx>,
1016 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1017 display_fn(move |f| match self {
1018 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1019 clean::Return(ty) if f.alternate() => {
1020 write!(f, " -> {:#}", ty.print(cx))
1022 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1023 clean::DefaultReturn => Ok(()),
1028 impl clean::BareFunctionDecl {
1029 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1031 cx: &'a Context<'tcx>,
1032 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1033 display_fn(move |f| {
1034 if !self.generic_params.is_empty() {
1035 write!(f, "for<{}> ", comma_sep(self.generic_params.iter().map(|g| g.print(cx))))
1043 impl clean::FnDecl {
1044 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1046 cx: &'a Context<'tcx>,
1047 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1048 display_fn(move |f| {
1049 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1053 "({args:#}{ellipsis}){arrow:#}",
1054 args = self.inputs.print(cx),
1055 ellipsis = ellipsis,
1056 arrow = self.output.print(cx)
1061 "({args}{ellipsis}){arrow}",
1062 args = self.inputs.print(cx),
1063 ellipsis = ellipsis,
1064 arrow = self.output.print(cx)
1070 /// * `header_len`: The length of the function header and name. In other words, the number of
1071 /// characters in the function declaration up to but not including the parentheses.
1072 /// <br>Used to determine line-wrapping.
1073 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1075 /// * `asyncness`: Whether the function is async or not.
1076 crate fn full_print<'a, 'tcx: 'a>(
1080 asyncness: hir::IsAsync,
1081 cx: &'a Context<'tcx>,
1082 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1083 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1086 fn inner_full_print(
1090 asyncness: hir::IsAsync,
1091 f: &mut fmt::Formatter<'_>,
1094 let amp = if f.alternate() { "&" } else { "&" };
1095 let mut args = String::new();
1096 let mut args_plain = String::new();
1097 for (i, input) in self.inputs.values.iter().enumerate() {
1099 args.push_str("<br>");
1102 if let Some(selfty) = input.to_self() {
1104 clean::SelfValue => {
1105 args.push_str("self");
1106 args_plain.push_str("self");
1108 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1109 args.push_str(&format!(
1113 mtbl.print_with_space()
1115 args_plain.push_str(&format!(
1118 mtbl.print_with_space()
1121 clean::SelfBorrowed(None, mtbl) => {
1122 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1123 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1125 clean::SelfExplicit(ref typ) => {
1127 args.push_str(&format!("self: {:#}", typ.print(cx)));
1129 args.push_str(&format!("self: {}", typ.print(cx)));
1131 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1136 args.push_str(" <br>");
1137 args_plain.push(' ');
1139 if !input.name.is_empty() {
1140 args.push_str(&format!("{}: ", input.name));
1141 args_plain.push_str(&format!("{}: ", input.name));
1145 args.push_str(&format!("{:#}", input.type_.print(cx)));
1147 args.push_str(&input.type_.print(cx).to_string());
1149 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1151 if i + 1 < self.inputs.values.len() {
1153 args_plain.push(',');
1157 let mut args_plain = format!("({})", args_plain);
1159 if self.c_variadic {
1160 args.push_str(",<br> ...");
1161 args_plain.push_str(", ...");
1165 let arrow = if let hir::IsAsync::Async = asyncness {
1166 let output = self.sugared_async_return_type();
1167 arrow_plain = format!("{:#}", output.print(cx));
1168 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1170 arrow_plain = format!("{:#}", self.output.print(cx));
1171 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1174 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1175 let output = if declaration_len > 80 {
1176 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1177 let close_pad = format!("<br>{}", " ".repeat(indent));
1179 "({args}{close}){arrow}",
1180 args = args.replace("<br>", &full_pad),
1185 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1189 write!(f, "{}", output.replace("<br>", "\n"))
1191 write!(f, "{}", output)
1196 impl clean::Visibility {
1197 crate fn print_with_space<'a, 'tcx: 'a>(
1200 cx: &'a Context<'tcx>,
1201 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1202 let to_print = match self {
1203 clean::Public => "pub ".to_owned(),
1204 clean::Inherited => String::new(),
1205 clean::Visibility::Restricted(vis_did) => {
1206 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1207 // However, rustdoc currently never displays a module's
1208 // visibility, so it shouldn't matter.
1209 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1211 if vis_did.index == CRATE_DEF_INDEX {
1212 "pub(crate) ".to_owned()
1213 } else if parent_module == Some(vis_did) {
1214 // `pub(in foo)` where `foo` is the parent module
1215 // is the same as no visibility modifier
1217 } else if parent_module
1218 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1222 "pub(super) ".to_owned()
1224 let path = cx.tcx().def_path(vis_did);
1225 debug!("path={:?}", path);
1226 // modified from `resolved_path()` to work with `DefPathData`
1227 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1228 let anchor = anchor(vis_did, &last_name.as_str(), cx).to_string();
1230 let mut s = "pub(in ".to_owned();
1231 for seg in &path.data[..path.data.len() - 1] {
1232 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1234 s.push_str(&format!("{}) ", anchor));
1239 display_fn(move |f| f.write_str(&to_print))
1242 /// This function is the same as print_with_space, except that it renders no links.
1243 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1245 crate fn to_src_with_space<'a, 'tcx: 'a>(
1249 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1250 let to_print = match self {
1251 clean::Public => "pub ".to_owned(),
1252 clean::Inherited => String::new(),
1253 clean::Visibility::Restricted(vis_did) => {
1254 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1255 // However, rustdoc currently never displays a module's
1256 // visibility, so it shouldn't matter.
1257 let parent_module = find_nearest_parent_module(tcx, item_did);
1259 if vis_did.index == CRATE_DEF_INDEX {
1260 "pub(crate) ".to_owned()
1261 } else if parent_module == Some(vis_did) {
1262 // `pub(in foo)` where `foo` is the parent module
1263 // is the same as no visibility modifier
1265 } else if parent_module
1266 .map(|parent| find_nearest_parent_module(tcx, parent))
1270 "pub(super) ".to_owned()
1272 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1276 display_fn(move |f| f.write_str(&to_print))
1280 crate trait PrintWithSpace {
1281 fn print_with_space(&self) -> &str;
1284 impl PrintWithSpace for hir::Unsafety {
1285 fn print_with_space(&self) -> &str {
1287 hir::Unsafety::Unsafe => "unsafe ",
1288 hir::Unsafety::Normal => "",
1293 impl PrintWithSpace for hir::IsAsync {
1294 fn print_with_space(&self) -> &str {
1296 hir::IsAsync::Async => "async ",
1297 hir::IsAsync::NotAsync => "",
1302 impl PrintWithSpace for hir::Mutability {
1303 fn print_with_space(&self) -> &str {
1305 hir::Mutability::Not => "",
1306 hir::Mutability::Mut => "mut ",
1311 crate fn print_constness_with_space(
1313 s: Option<&ConstStability>,
1316 // const stable or when feature(staged_api) is not set
1318 hir::Constness::Const,
1319 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1321 | (hir::Constness::Const, None) => "const ",
1322 // const unstable or not const
1327 impl clean::Import {
1328 crate fn print<'a, 'tcx: 'a>(
1330 cx: &'a Context<'tcx>,
1331 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1332 display_fn(move |f| match self.kind {
1333 clean::ImportKind::Simple(name) => {
1334 if name == self.source.path.last() {
1335 write!(f, "use {};", self.source.print(cx))
1337 write!(f, "use {} as {};", self.source.print(cx), name)
1340 clean::ImportKind::Glob => {
1341 if self.source.path.segments.is_empty() {
1344 write!(f, "use {}::*;", self.source.print(cx))
1351 impl clean::ImportSource {
1352 crate fn print<'a, 'tcx: 'a>(
1354 cx: &'a Context<'tcx>,
1355 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1356 display_fn(move |f| match self.did {
1357 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1359 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1360 write!(f, "{}::", seg.name)?;
1362 let name = self.path.last_name();
1363 if let hir::def::Res::PrimTy(p) = self.path.res {
1364 primitive_link(f, PrimitiveType::from(p), &*name, cx)?;
1366 write!(f, "{}", name)?;
1374 impl clean::TypeBinding {
1375 crate fn print<'a, 'tcx: 'a>(
1377 cx: &'a Context<'tcx>,
1378 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1379 display_fn(move |f| {
1380 f.write_str(&*self.name.as_str())?;
1382 clean::TypeBindingKind::Equality { ref ty } => {
1384 write!(f, " = {:#}", ty.print(cx))?;
1386 write!(f, " = {}", ty.print(cx))?;
1389 clean::TypeBindingKind::Constraint { ref bounds } => {
1390 if !bounds.is_empty() {
1392 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1394 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1404 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1405 display_fn(move |f| {
1406 let quot = if f.alternate() { "\"" } else { """ };
1408 Abi::Rust => Ok(()),
1409 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1414 crate fn print_default_space<'a>(v: bool) -> &'a str {
1415 if v { "default " } else { "" }
1418 impl clean::GenericArg {
1419 crate fn print<'a, 'tcx: 'a>(
1421 cx: &'a Context<'tcx>,
1422 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1423 display_fn(move |f| match self {
1424 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1425 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1426 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1431 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1432 struct WithFormatter<F>(Cell<Option<F>>);
1434 impl<F> fmt::Display for WithFormatter<F>
1436 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 (self.0.take()).unwrap()(f)
1443 WithFormatter(Cell::new(Some(f)))