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_with_root_path(
490 root_path: Option<&str>,
491 ) -> Result<(String, ItemType, Vec<String>), HrefError> {
492 let cache = &cx.cache();
493 let relative_to = &cx.current;
494 fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
495 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
498 if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
499 return Err(HrefError::Private);
502 let mut is_remote = false;
503 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
504 Some(&(ref fqp, shortty)) => (fqp, shortty, {
505 let module_fqp = to_module_fqp(shortty, fqp);
506 href_relative_parts(module_fqp, relative_to)
509 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
510 let module_fqp = to_module_fqp(shortty, fqp);
514 match cache.extern_locations[&did.krate] {
515 ExternalLocation::Remote(ref s) => {
517 let s = s.trim_end_matches('/');
519 s.extend(module_fqp[..].iter().map(String::as_str));
522 ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
523 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
527 return Err(HrefError::NotInExternalCache);
532 if let Some(root_path) = root_path {
533 let root = root_path.trim_end_matches('/');
534 url_parts.insert(0, root);
537 let last = &fqp.last().unwrap()[..];
540 ItemType::Module => {
541 url_parts.push("index.html");
544 filename = format!("{}.{}.html", shortty.as_str(), last);
545 url_parts.push(&filename);
548 Ok((url_parts.join("/"), shortty, fqp.to_vec()))
551 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<String>), HrefError> {
552 href_with_root_path(did, cx, None)
555 /// Both paths should only be modules.
556 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
557 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
558 crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String]) -> Vec<&'a str> {
559 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
560 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
562 let dissimilar_part_count = relative_to_fqp.len() - i;
563 let fqp_module = fqp[i..fqp.len()].iter().map(String::as_str);
564 return iter::repeat("..").take(dissimilar_part_count).chain(fqp_module).collect();
567 // e.g. linking to std::sync::atomic from std::sync
568 if relative_to_fqp.len() < fqp.len() {
569 fqp[relative_to_fqp.len()..fqp.len()].iter().map(String::as_str).collect()
570 // e.g. linking to std::sync from std::sync::atomic
571 } else if fqp.len() < relative_to_fqp.len() {
572 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
573 iter::repeat("..").take(dissimilar_part_count).collect()
574 // linking to the same module
580 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
581 /// rendering function with the necessary arguments for linking to a local path.
582 fn resolved_path<'a, 'cx: 'a>(
583 w: &mut fmt::Formatter<'_>,
588 cx: &'cx Context<'_>,
590 let last = path.segments.last().unwrap();
593 for seg in &path.segments[..path.segments.len() - 1] {
594 write!(w, "{}::", seg.name)?;
598 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
600 let path = if use_absolute {
601 if let Ok((_, _, fqp)) = href(did, cx) {
604 fqp[..fqp.len() - 1].join("::"),
605 anchor(did, fqp.last().unwrap(), cx)
608 last.name.to_string()
611 anchor(did, &*last.name.as_str(), cx).to_string()
613 write!(w, "{}{}", path, last.args.print(cx))?;
619 f: &mut fmt::Formatter<'_>,
620 prim: clean::PrimitiveType,
625 let mut needs_termination = false;
627 match m.primitive_locations.get(&prim) {
628 Some(&def_id) if def_id.is_local() => {
629 let len = cx.current.len();
630 let len = if len == 0 { 0 } else { len - 1 };
633 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
637 needs_termination = true;
641 let loc = match m.extern_locations[&def_id.krate] {
642 ExternalLocation::Remote(ref s) => {
644 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
645 Some(vec![s.trim_end_matches('/'), &cname_str[..]])
647 ExternalLocation::Local => {
649 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
650 Some(if cx.current.first().map(|x| &x[..]) == Some(&cname_str[..]) {
651 iter::repeat("..").take(cx.current.len() - 1).collect()
653 let cname = iter::once(&cname_str[..]);
654 iter::repeat("..").take(cx.current.len()).chain(cname).collect()
657 ExternalLocation::Unknown => None,
659 if let Some(loc) = loc {
662 "<a class=\"primitive\" href=\"{}/primitive.{}.html\">",
666 needs_termination = true;
672 write!(f, "{}", name)?;
673 if needs_termination {
679 /// Helper to render type parameters
680 fn tybounds<'a, 'tcx: 'a>(
681 bounds: &'a Vec<clean::PolyTrait>,
682 lt: &'a Option<clean::Lifetime>,
683 cx: &'a Context<'tcx>,
684 ) -> impl fmt::Display + 'a + Captures<'tcx> {
685 display_fn(move |f| {
686 for (i, bound) in bounds.iter().enumerate() {
691 fmt::Display::fmt(&bound.print(cx), f)?;
694 if let Some(lt) = lt {
696 fmt::Display::fmt(<.print(), f)?;
702 crate fn anchor<'a, 'cx: 'a>(
705 cx: &'cx Context<'_>,
706 ) -> impl fmt::Display + 'a {
707 let parts = href(did, cx);
708 display_fn(move |f| {
709 if let Ok((url, short_ty, fqp)) = parts {
712 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
720 write!(f, "{}", text)
727 f: &mut fmt::Formatter<'_>,
729 cx: &'cx Context<'_>,
731 debug!("fmt_type(t = {:?})", t);
734 clean::Generic(name) => write!(f, "{}", name),
735 clean::ResolvedPath { did, ref path, is_generic } => {
736 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
737 resolved_path(f, did, path, is_generic, use_absolute, cx)
739 clean::DynTrait(ref bounds, ref lt) => {
740 f.write_str("dyn ")?;
741 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
743 clean::Infer => write!(f, "_"),
744 clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
745 clean::BareFunction(ref decl) => {
750 decl.print_hrtb_with_space(cx),
751 decl.unsafety.print_with_space(),
752 print_abi_with_space(decl.abi),
759 decl.print_hrtb_with_space(cx),
760 decl.unsafety.print_with_space(),
761 print_abi_with_space(decl.abi)
763 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
764 write!(f, "{}", decl.decl.print(cx))
767 clean::Tuple(ref typs) => {
769 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
771 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
772 // Carry `f.alternate()` into this display w/o branching manually.
773 fmt::Display::fmt(&one.print(cx), f)?;
774 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
777 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
778 for (i, item) in many.iter().enumerate() {
782 fmt::Display::fmt(&item.print(cx), f)?;
784 primitive_link(f, PrimitiveType::Tuple, ")", cx)
788 clean::Slice(ref t) => {
789 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
790 fmt::Display::fmt(&t.print(cx), f)?;
791 primitive_link(f, PrimitiveType::Slice, "]", cx)
793 clean::Array(ref t, ref n) => {
794 primitive_link(f, PrimitiveType::Array, "[", cx)?;
795 fmt::Display::fmt(&t.print(cx), f)?;
797 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
799 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
802 clean::Never => primitive_link(f, PrimitiveType::Never, "!", cx),
803 clean::RawPointer(m, ref t) => {
805 hir::Mutability::Mut => "mut",
806 hir::Mutability::Not => "const",
809 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
813 clean::PrimitiveType::RawPointer,
814 &format!("*{} {:#}", m, t.print(cx)),
820 clean::PrimitiveType::RawPointer,
821 &format!("*{} {}", m, t.print(cx)),
827 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
828 fmt::Display::fmt(&t.print(cx), f)
832 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
834 Some(l) => format!("{} ", l.print()),
837 let m = mutability.print_with_space();
838 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
840 clean::Slice(ref bt) => {
841 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
843 clean::Generic(_) => {
847 PrimitiveType::Slice,
848 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
854 PrimitiveType::Slice,
855 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
863 PrimitiveType::Slice,
864 &format!("{}{}{}[", amp, lt, m),
868 write!(f, "{:#}", bt.print(cx))?;
870 write!(f, "{}", bt.print(cx))?;
872 primitive_link(f, PrimitiveType::Slice, "]", cx)
876 clean::DynTrait(ref bounds, ref trait_lt)
877 if bounds.len() > 1 || trait_lt.is_some() =>
879 write!(f, "{}{}{}(", amp, lt, m)?;
880 fmt_type(&ty, f, use_absolute, cx)?;
883 clean::Generic(..) => {
886 PrimitiveType::Reference,
887 &format!("{}{}{}", amp, lt, m),
890 fmt_type(&ty, f, use_absolute, cx)
893 write!(f, "{}{}{}", amp, lt, m)?;
894 fmt_type(&ty, f, use_absolute, cx)
898 clean::ImplTrait(ref bounds) => {
900 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
902 write!(f, "impl {}", print_generic_bounds(bounds, cx))
905 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
906 let should_show_cast = match *trait_ {
907 box clean::ResolvedPath { ref path, .. } => {
908 !path.segments.is_empty()
910 .zip(trait_.def_id())
911 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
916 if should_show_cast {
917 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
919 write!(f, "{:#}::", self_type.print(cx))?
922 if should_show_cast {
923 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
925 write!(f, "{}::", self_type.print(cx))?
929 // It's pretty unsightly to look at `<A as B>::C` in output, and
930 // we've got hyperlinking on our side, so try to avoid longer
931 // notation as much as possible by making `C` a hyperlink to trait
932 // `B` to disambiguate.
934 // FIXME: this is still a lossy conversion and there should probably
935 // be a better way of representing this in general? Most of
936 // the ugliness comes from inlining across crates where
937 // everything comes in as a fully resolved QPath (hard to
939 box clean::ResolvedPath { did, .. } => {
940 match href(did, cx) {
941 Ok((ref url, _, ref path)) if !f.alternate() => {
944 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
945 title=\"type {path}::{name}\">{name}</a>",
947 shortty = ItemType::AssocType,
949 path = path.join("::")
952 _ => write!(f, "{}", name)?,
956 _ => write!(f, "{}", name),
963 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
965 cx: &'a Context<'tcx>,
966 ) -> impl fmt::Display + 'b + Captures<'tcx> {
967 display_fn(move |f| fmt_type(self, f, false, cx))
972 crate fn print<'a, 'tcx: 'a>(
975 cx: &'a Context<'tcx>,
976 ) -> impl fmt::Display + 'a + Captures<'tcx> {
977 display_fn(move |f| {
979 write!(f, "impl{:#} ", self.generics.print(cx))?;
981 write!(f, "impl{} ", self.generics.print(cx))?;
984 if let Some(ref ty) = self.trait_ {
985 if self.negative_polarity {
988 fmt::Display::fmt(&ty.print(cx), f)?;
992 if let Some(ref ty) = self.blanket_impl {
993 fmt_type(ty, f, use_absolute, cx)?;
995 fmt_type(&self.for_, f, use_absolute, cx)?;
998 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1004 impl clean::Arguments {
1005 crate fn print<'a, 'tcx: 'a>(
1007 cx: &'a Context<'tcx>,
1008 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1009 display_fn(move |f| {
1010 for (i, input) in self.values.iter().enumerate() {
1011 if !input.name.is_empty() {
1012 write!(f, "{}: ", input.name)?;
1015 write!(f, "{:#}", input.type_.print(cx))?;
1017 write!(f, "{}", input.type_.print(cx))?;
1019 if i + 1 < self.values.len() {
1028 impl clean::FnRetTy {
1029 crate fn print<'a, 'tcx: 'a>(
1031 cx: &'a Context<'tcx>,
1032 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1033 display_fn(move |f| match self {
1034 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1035 clean::Return(ty) if f.alternate() => {
1036 write!(f, " -> {:#}", ty.print(cx))
1038 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1039 clean::DefaultReturn => Ok(()),
1044 impl clean::BareFunctionDecl {
1045 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1047 cx: &'a Context<'tcx>,
1048 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1049 display_fn(move |f| {
1050 if !self.generic_params.is_empty() {
1051 write!(f, "for<{}> ", comma_sep(self.generic_params.iter().map(|g| g.print(cx))))
1059 impl clean::FnDecl {
1060 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1062 cx: &'a Context<'tcx>,
1063 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1064 display_fn(move |f| {
1065 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1069 "({args:#}{ellipsis}){arrow:#}",
1070 args = self.inputs.print(cx),
1071 ellipsis = ellipsis,
1072 arrow = self.output.print(cx)
1077 "({args}{ellipsis}){arrow}",
1078 args = self.inputs.print(cx),
1079 ellipsis = ellipsis,
1080 arrow = self.output.print(cx)
1086 /// * `header_len`: The length of the function header and name. In other words, the number of
1087 /// characters in the function declaration up to but not including the parentheses.
1088 /// <br>Used to determine line-wrapping.
1089 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1091 /// * `asyncness`: Whether the function is async or not.
1092 crate fn full_print<'a, 'tcx: 'a>(
1096 asyncness: hir::IsAsync,
1097 cx: &'a Context<'tcx>,
1098 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1099 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1102 fn inner_full_print(
1106 asyncness: hir::IsAsync,
1107 f: &mut fmt::Formatter<'_>,
1110 let amp = if f.alternate() { "&" } else { "&" };
1111 let mut args = String::new();
1112 let mut args_plain = String::new();
1113 for (i, input) in self.inputs.values.iter().enumerate() {
1115 args.push_str("<br>");
1118 if let Some(selfty) = input.to_self() {
1120 clean::SelfValue => {
1121 args.push_str("self");
1122 args_plain.push_str("self");
1124 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1125 args.push_str(&format!(
1129 mtbl.print_with_space()
1131 args_plain.push_str(&format!(
1134 mtbl.print_with_space()
1137 clean::SelfBorrowed(None, mtbl) => {
1138 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1139 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1141 clean::SelfExplicit(ref typ) => {
1143 args.push_str(&format!("self: {:#}", typ.print(cx)));
1145 args.push_str(&format!("self: {}", typ.print(cx)));
1147 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1152 args.push_str(" <br>");
1153 args_plain.push(' ');
1155 if !input.name.is_empty() {
1156 args.push_str(&format!("{}: ", input.name));
1157 args_plain.push_str(&format!("{}: ", input.name));
1161 args.push_str(&format!("{:#}", input.type_.print(cx)));
1163 args.push_str(&input.type_.print(cx).to_string());
1165 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1167 if i + 1 < self.inputs.values.len() {
1169 args_plain.push(',');
1173 let mut args_plain = format!("({})", args_plain);
1175 if self.c_variadic {
1176 args.push_str(",<br> ...");
1177 args_plain.push_str(", ...");
1181 let arrow = if let hir::IsAsync::Async = asyncness {
1182 let output = self.sugared_async_return_type();
1183 arrow_plain = format!("{:#}", output.print(cx));
1184 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1186 arrow_plain = format!("{:#}", self.output.print(cx));
1187 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1190 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1191 let output = if declaration_len > 80 {
1192 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1193 let close_pad = format!("<br>{}", " ".repeat(indent));
1195 "({args}{close}){arrow}",
1196 args = args.replace("<br>", &full_pad),
1201 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1205 write!(f, "{}", output.replace("<br>", "\n"))
1207 write!(f, "{}", output)
1212 impl clean::Visibility {
1213 crate fn print_with_space<'a, 'tcx: 'a>(
1216 cx: &'a Context<'tcx>,
1217 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1218 let to_print = match self {
1219 clean::Public => "pub ".to_owned(),
1220 clean::Inherited => String::new(),
1221 clean::Visibility::Restricted(vis_did) => {
1222 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1223 // However, rustdoc currently never displays a module's
1224 // visibility, so it shouldn't matter.
1225 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1227 if vis_did.index == CRATE_DEF_INDEX {
1228 "pub(crate) ".to_owned()
1229 } else if parent_module == Some(vis_did) {
1230 // `pub(in foo)` where `foo` is the parent module
1231 // is the same as no visibility modifier
1233 } else if parent_module
1234 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1238 "pub(super) ".to_owned()
1240 let path = cx.tcx().def_path(vis_did);
1241 debug!("path={:?}", path);
1242 // modified from `resolved_path()` to work with `DefPathData`
1243 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1244 let anchor = anchor(vis_did, &last_name.as_str(), cx).to_string();
1246 let mut s = "pub(in ".to_owned();
1247 for seg in &path.data[..path.data.len() - 1] {
1248 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1250 s.push_str(&format!("{}) ", anchor));
1255 display_fn(move |f| f.write_str(&to_print))
1258 /// This function is the same as print_with_space, except that it renders no links.
1259 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1261 crate fn to_src_with_space<'a, 'tcx: 'a>(
1265 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1266 let to_print = match self {
1267 clean::Public => "pub ".to_owned(),
1268 clean::Inherited => String::new(),
1269 clean::Visibility::Restricted(vis_did) => {
1270 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1271 // However, rustdoc currently never displays a module's
1272 // visibility, so it shouldn't matter.
1273 let parent_module = find_nearest_parent_module(tcx, item_did);
1275 if vis_did.index == CRATE_DEF_INDEX {
1276 "pub(crate) ".to_owned()
1277 } else if parent_module == Some(vis_did) {
1278 // `pub(in foo)` where `foo` is the parent module
1279 // is the same as no visibility modifier
1281 } else if parent_module
1282 .map(|parent| find_nearest_parent_module(tcx, parent))
1286 "pub(super) ".to_owned()
1288 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1292 display_fn(move |f| f.write_str(&to_print))
1296 crate trait PrintWithSpace {
1297 fn print_with_space(&self) -> &str;
1300 impl PrintWithSpace for hir::Unsafety {
1301 fn print_with_space(&self) -> &str {
1303 hir::Unsafety::Unsafe => "unsafe ",
1304 hir::Unsafety::Normal => "",
1309 impl PrintWithSpace for hir::IsAsync {
1310 fn print_with_space(&self) -> &str {
1312 hir::IsAsync::Async => "async ",
1313 hir::IsAsync::NotAsync => "",
1318 impl PrintWithSpace for hir::Mutability {
1319 fn print_with_space(&self) -> &str {
1321 hir::Mutability::Not => "",
1322 hir::Mutability::Mut => "mut ",
1327 crate fn print_constness_with_space(
1329 s: Option<&ConstStability>,
1332 // const stable or when feature(staged_api) is not set
1334 hir::Constness::Const,
1335 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1337 | (hir::Constness::Const, None) => "const ",
1338 // const unstable or not const
1343 impl clean::Import {
1344 crate fn print<'a, 'tcx: 'a>(
1346 cx: &'a Context<'tcx>,
1347 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1348 display_fn(move |f| match self.kind {
1349 clean::ImportKind::Simple(name) => {
1350 if name == self.source.path.last() {
1351 write!(f, "use {};", self.source.print(cx))
1353 write!(f, "use {} as {};", self.source.print(cx), name)
1356 clean::ImportKind::Glob => {
1357 if self.source.path.segments.is_empty() {
1360 write!(f, "use {}::*;", self.source.print(cx))
1367 impl clean::ImportSource {
1368 crate fn print<'a, 'tcx: 'a>(
1370 cx: &'a Context<'tcx>,
1371 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1372 display_fn(move |f| match self.did {
1373 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1375 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1376 write!(f, "{}::", seg.name)?;
1378 let name = self.path.last_name();
1379 if let hir::def::Res::PrimTy(p) = self.path.res {
1380 primitive_link(f, PrimitiveType::from(p), &*name, cx)?;
1382 write!(f, "{}", name)?;
1390 impl clean::TypeBinding {
1391 crate fn print<'a, 'tcx: 'a>(
1393 cx: &'a Context<'tcx>,
1394 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1395 display_fn(move |f| {
1396 f.write_str(&*self.name.as_str())?;
1398 clean::TypeBindingKind::Equality { ref ty } => {
1400 write!(f, " = {:#}", ty.print(cx))?;
1402 write!(f, " = {}", ty.print(cx))?;
1405 clean::TypeBindingKind::Constraint { ref bounds } => {
1406 if !bounds.is_empty() {
1408 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1410 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1420 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1421 display_fn(move |f| {
1422 let quot = if f.alternate() { "\"" } else { """ };
1424 Abi::Rust => Ok(()),
1425 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1430 crate fn print_default_space<'a>(v: bool) -> &'a str {
1431 if v { "default " } else { "" }
1434 impl clean::GenericArg {
1435 crate fn print<'a, 'tcx: 'a>(
1437 cx: &'a Context<'tcx>,
1438 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1439 display_fn(move |f| match self {
1440 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1441 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1442 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1443 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1448 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1449 struct WithFormatter<F>(Cell<Option<F>>);
1451 impl<F> fmt::Display for WithFormatter<F>
1453 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456 (self.0.take()).unwrap()(f)
1460 WithFormatter(Cell::new(Some(f)))