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;
21 use crate::clean::{self, utils::find_nearest_parent_module, ExternalCrate, ItemId, PrimitiveType};
22 use crate::formats::item_type::ItemType;
23 use crate::html::escape::Escape;
24 use crate::html::render::cache::ExternalLocation;
25 use crate::html::render::Context;
28 fn print(self, buffer: &mut Buffer);
33 F: FnOnce(&mut Buffer),
35 fn print(self, buffer: &mut Buffer) {
40 impl Print for String {
41 fn print(self, buffer: &mut Buffer) {
42 buffer.write_str(&self);
46 impl Print for &'_ str {
47 fn print(self, buffer: &mut Buffer) {
48 buffer.write_str(self);
52 #[derive(Debug, Clone)]
59 crate fn empty_from(v: &Buffer) -> Buffer {
60 Buffer { for_html: v.for_html, buffer: String::new() }
63 crate fn html() -> Buffer {
64 Buffer { for_html: true, buffer: String::new() }
67 crate fn new() -> Buffer {
68 Buffer { for_html: false, buffer: String::new() }
71 crate fn is_empty(&self) -> bool {
72 self.buffer.is_empty()
75 crate fn into_inner(self) -> String {
79 crate fn insert_str(&mut self, idx: usize, s: &str) {
80 self.buffer.insert_str(idx, s);
83 crate fn push_str(&mut self, s: &str) {
84 self.buffer.push_str(s);
87 crate fn push_buffer(&mut self, other: Buffer) {
88 self.buffer.push_str(&other.buffer);
91 // Intended for consumption by write! and writeln! (std::fmt) but without
92 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
94 crate fn write_str(&mut self, s: &str) {
95 self.buffer.push_str(s);
98 // Intended for consumption by write! and writeln! (std::fmt) but without
99 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
101 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
103 self.buffer.write_fmt(v).unwrap();
106 crate fn to_display<T: Print>(mut self, t: T) -> String {
111 crate fn is_for_html(&self) -> bool {
115 crate fn reserve(&mut self, additional: usize) {
116 self.buffer.reserve(additional)
120 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
121 display_fn(move |f| {
122 for (i, item) in items.enumerate() {
126 fmt::Display::fmt(&item, f)?;
132 crate fn print_generic_bounds<'a, 'tcx: 'a>(
133 bounds: &'a [clean::GenericBound],
134 cx: &'a Context<'tcx>,
135 ) -> impl fmt::Display + 'a + Captures<'tcx> {
136 display_fn(move |f| {
137 let mut bounds_dup = FxHashSet::default();
140 bounds.iter().filter(|b| bounds_dup.insert(b.print(cx).to_string())).enumerate()
145 fmt::Display::fmt(&bound.print(cx), f)?;
151 impl clean::GenericParamDef {
152 crate fn print<'a, 'tcx: 'a>(
154 cx: &'a Context<'tcx>,
155 ) -> impl fmt::Display + 'a + Captures<'tcx> {
156 display_fn(move |f| match &self.kind {
157 clean::GenericParamDefKind::Lifetime { outlives } => {
158 write!(f, "{}", self.name)?;
160 if !outlives.is_empty() {
162 for (i, lt) in outlives.iter().enumerate() {
166 write!(f, "{}", lt.print())?;
172 clean::GenericParamDefKind::Type { bounds, default, .. } => {
173 f.write_str(&*self.name.as_str())?;
175 if !bounds.is_empty() {
177 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
179 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
183 if let Some(ref ty) = default {
185 write!(f, " = {:#}", ty.print(cx))?;
187 write!(f, " = {}", ty.print(cx))?;
193 clean::GenericParamDefKind::Const { ty, default, .. } => {
195 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
197 write!(f, "const {}: {}", self.name, ty.print(cx))?;
200 if let Some(default) = default {
202 write!(f, " = {:#}", default)?;
204 write!(f, " = {}", default)?;
214 impl clean::Generics {
215 crate fn print<'a, 'tcx: 'a>(
217 cx: &'a Context<'tcx>,
218 ) -> impl fmt::Display + 'a + Captures<'tcx> {
219 display_fn(move |f| {
221 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
222 if real_params.is_empty() {
226 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
228 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
234 /// * The Generics from which to emit a where-clause.
235 /// * The number of spaces to indent each line with.
236 /// * Whether the where-clause needs to add a comma and newline after the last bound.
237 crate fn print_where_clause<'a, 'tcx: 'a>(
238 gens: &'a clean::Generics,
239 cx: &'a Context<'tcx>,
242 ) -> impl fmt::Display + 'a + Captures<'tcx> {
243 display_fn(move |f| {
244 if gens.where_predicates.is_empty() {
247 let mut clause = String::new();
249 clause.push_str(" where");
252 clause.push_str(" <span class=\"where fmt-newline\">where");
254 clause.push_str(" <span class=\"where\">where");
257 for (i, pred) in gens.where_predicates.iter().enumerate() {
261 clause.push_str("<br>");
265 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
267 let for_prefix = match bound_params.len() {
269 _ if f.alternate() => {
272 comma_sep(bound_params.iter().map(|lt| lt.print()))
277 comma_sep(bound_params.iter().map(|lt| lt.print()))
282 clause.push_str(&format!(
286 print_generic_bounds(bounds, cx)
289 clause.push_str(&format!(
293 print_generic_bounds(bounds, cx)
297 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
298 clause.push_str(&format!(
303 .map(|b| b.print(cx).to_string())
308 clean::WherePredicate::EqPredicate { lhs, rhs } => {
310 clause.push_str(&format!("{:#} == {:#}", lhs.print(cx), rhs.print(cx),));
312 clause.push_str(&format!("{} == {}", lhs.print(cx), rhs.print(cx),));
317 if i < gens.where_predicates.len() - 1 || end_newline {
323 // add a space so stripping <br> tags and breaking spaces still renders properly
327 clause.push_str(" ");
332 clause.push_str("</span>");
333 let padding = " ".repeat(indent + 4);
334 clause = clause.replace("<br>", &format!("<br>{}", padding));
335 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
337 clause.insert_str(0, "<br>");
340 write!(f, "{}", clause)
344 impl clean::Lifetime {
345 crate fn print(&self) -> impl fmt::Display + '_ {
350 impl clean::Constant {
351 crate fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
352 let expr = self.expr(tcx);
355 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
361 impl clean::PolyTrait {
362 fn print<'a, 'tcx: 'a>(
364 cx: &'a Context<'tcx>,
365 ) -> impl fmt::Display + 'a + Captures<'tcx> {
366 display_fn(move |f| {
367 if !self.generic_params.is_empty() {
372 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
378 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
383 write!(f, "{:#}", self.trait_.print(cx))
385 write!(f, "{}", self.trait_.print(cx))
391 impl clean::GenericBound {
392 crate fn print<'a, 'tcx: 'a>(
394 cx: &'a Context<'tcx>,
395 ) -> impl fmt::Display + 'a + Captures<'tcx> {
396 display_fn(move |f| match self {
397 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
398 clean::GenericBound::TraitBound(ty, modifier) => {
399 let modifier_str = match modifier {
400 hir::TraitBoundModifier::None => "",
401 hir::TraitBoundModifier::Maybe => "?",
402 hir::TraitBoundModifier::MaybeConst => "~const",
405 write!(f, "{}{:#}", modifier_str, ty.print(cx))
407 write!(f, "{}{}", modifier_str, ty.print(cx))
414 impl clean::GenericArgs {
415 fn print<'a, 'tcx: 'a>(
417 cx: &'a Context<'tcx>,
418 ) -> impl fmt::Display + 'a + Captures<'tcx> {
419 display_fn(move |f| {
421 clean::GenericArgs::AngleBracketed { args, bindings } => {
422 if !args.is_empty() || !bindings.is_empty() {
426 f.write_str("<")?;
428 let mut comma = false;
435 write!(f, "{:#}", arg.print(cx))?;
437 write!(f, "{}", arg.print(cx))?;
440 for binding in bindings {
446 write!(f, "{:#}", binding.print(cx))?;
448 write!(f, "{}", binding.print(cx))?;
454 f.write_str(">")?;
458 clean::GenericArgs::Parenthesized { inputs, output } => {
460 let mut comma = false;
467 write!(f, "{:#}", ty.print(cx))?;
469 write!(f, "{}", ty.print(cx))?;
473 if let Some(ref ty) = *output {
475 write!(f, " -> {:#}", ty.print(cx))?;
477 write!(f, " -> {}", ty.print(cx))?;
487 // Possible errors when computing href link source for a `DefId`
488 crate enum HrefError {
489 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
491 /// This can only happen for non-local items.
492 DocumentationNotBuilt,
493 /// This can only happen for non-local items when `--document-private-items` is not passed.
495 // Not in external cache, href link should be in same page
499 crate fn href_with_root_path(
502 root_path: Option<&str>,
503 ) -> Result<(String, ItemType, Vec<String>), HrefError> {
504 let cache = &cx.cache();
505 let relative_to = &cx.current;
506 fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
507 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
511 && !cache.access_levels.is_public(did)
512 && !cache.document_private
513 && !cache.primitive_locations.values().any(|&id| id == did)
515 return Err(HrefError::Private);
518 let mut is_remote = false;
519 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
520 Some(&(ref fqp, shortty)) => (fqp, shortty, {
521 let module_fqp = to_module_fqp(shortty, fqp);
522 debug!(?fqp, ?shortty, ?module_fqp);
523 href_relative_parts(module_fqp, relative_to)
526 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
527 let module_fqp = to_module_fqp(shortty, fqp);
531 match cache.extern_locations[&did.krate] {
532 ExternalLocation::Remote(ref s) => {
534 let s = s.trim_end_matches('/');
536 s.extend(module_fqp[..].iter().map(String::as_str));
539 ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
540 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
544 return Err(HrefError::NotInExternalCache);
549 if let Some(root_path) = root_path {
550 let root = root_path.trim_end_matches('/');
551 url_parts.insert(0, root);
555 let last = &fqp.last().unwrap()[..];
558 ItemType::Module => {
559 url_parts.push("index.html");
562 filename = format!("{}.{}.html", shortty.as_str(), last);
563 url_parts.push(&filename);
566 Ok((url_parts.join("/"), shortty, fqp.to_vec()))
569 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<String>), HrefError> {
570 href_with_root_path(did, cx, None)
573 /// Both paths should only be modules.
574 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
575 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
576 crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String]) -> Vec<&'a str> {
577 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
578 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
580 let dissimilar_part_count = relative_to_fqp.len() - i;
581 let fqp_module = fqp[i..fqp.len()].iter().map(String::as_str);
582 return iter::repeat("..").take(dissimilar_part_count).chain(fqp_module).collect();
585 // e.g. linking to std::sync::atomic from std::sync
586 if relative_to_fqp.len() < fqp.len() {
587 fqp[relative_to_fqp.len()..fqp.len()].iter().map(String::as_str).collect()
588 // e.g. linking to std::sync from std::sync::atomic
589 } else if fqp.len() < relative_to_fqp.len() {
590 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
591 iter::repeat("..").take(dissimilar_part_count).collect()
592 // linking to the same module
598 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
599 /// rendering function with the necessary arguments for linking to a local path.
600 fn resolved_path<'cx>(
601 w: &mut fmt::Formatter<'_>,
606 cx: &'cx Context<'_>,
608 let last = path.segments.last().unwrap();
611 for seg in &path.segments[..path.segments.len() - 1] {
612 write!(w, "{}::", seg.name)?;
616 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
618 let path = if use_absolute {
619 if let Ok((_, _, fqp)) = href(did, cx) {
622 fqp[..fqp.len() - 1].join("::"),
623 anchor(did, fqp.last().unwrap(), cx)
626 last.name.to_string()
629 anchor(did, &*last.name.as_str(), cx).to_string()
631 write!(w, "{}{}", path, last.args.print(cx))?;
637 f: &mut fmt::Formatter<'_>,
638 prim: clean::PrimitiveType,
643 let mut needs_termination = false;
645 match m.primitive_locations.get(&prim) {
646 Some(&def_id) if def_id.is_local() => {
647 let len = cx.current.len();
648 let len = if len == 0 { 0 } else { len - 1 };
651 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
655 needs_termination = true;
659 let loc = match m.extern_locations[&def_id.krate] {
660 ExternalLocation::Remote(ref s) => {
662 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
663 Some(vec![s.trim_end_matches('/'), &cname_str[..]])
665 ExternalLocation::Local => {
667 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
668 Some(if cx.current.first().map(|x| &x[..]) == Some(&cname_str[..]) {
669 iter::repeat("..").take(cx.current.len() - 1).collect()
671 let cname = iter::once(&cname_str[..]);
672 iter::repeat("..").take(cx.current.len()).chain(cname).collect()
675 ExternalLocation::Unknown => None,
677 if let Some(loc) = loc {
680 "<a class=\"primitive\" href=\"{}/primitive.{}.html\">",
684 needs_termination = true;
690 write!(f, "{}", name)?;
691 if needs_termination {
697 /// Helper to render type parameters
698 fn tybounds<'a, 'tcx: 'a>(
699 bounds: &'a [clean::PolyTrait],
700 lt: &'a Option<clean::Lifetime>,
701 cx: &'a Context<'tcx>,
702 ) -> impl fmt::Display + 'a + Captures<'tcx> {
703 display_fn(move |f| {
704 for (i, bound) in bounds.iter().enumerate() {
709 fmt::Display::fmt(&bound.print(cx), f)?;
712 if let Some(lt) = lt {
714 fmt::Display::fmt(<.print(), f)?;
720 crate fn anchor<'a, 'cx: 'a>(
723 cx: &'cx Context<'_>,
724 ) -> impl fmt::Display + 'a {
725 let parts = href(did, cx);
726 display_fn(move |f| {
727 if let Ok((url, short_ty, fqp)) = parts {
730 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
738 write!(f, "{}", text)
745 f: &mut fmt::Formatter<'_>,
747 cx: &'cx Context<'_>,
749 trace!("fmt_type(t = {:?})", t);
752 clean::Generic(name) => write!(f, "{}", name),
753 clean::ResolvedPath { did, ref path } => {
754 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
755 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
757 clean::DynTrait(ref bounds, ref lt) => {
758 f.write_str("dyn ")?;
759 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
761 clean::Infer => write!(f, "_"),
762 clean::Primitive(clean::PrimitiveType::Never) => {
763 primitive_link(f, PrimitiveType::Never, "!", cx)
765 clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
766 clean::BareFunction(ref decl) => {
771 decl.print_hrtb_with_space(cx),
772 decl.unsafety.print_with_space(),
773 print_abi_with_space(decl.abi),
780 decl.print_hrtb_with_space(cx),
781 decl.unsafety.print_with_space(),
782 print_abi_with_space(decl.abi)
784 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
785 write!(f, "{}", decl.decl.print(cx))
788 clean::Tuple(ref typs) => {
790 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
792 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
793 // Carry `f.alternate()` into this display w/o branching manually.
794 fmt::Display::fmt(&one.print(cx), f)?;
795 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
798 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
799 for (i, item) in many.iter().enumerate() {
803 fmt::Display::fmt(&item.print(cx), f)?;
805 primitive_link(f, PrimitiveType::Tuple, ")", cx)
809 clean::Slice(ref t) => {
810 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
811 fmt::Display::fmt(&t.print(cx), f)?;
812 primitive_link(f, PrimitiveType::Slice, "]", cx)
814 clean::Array(ref t, ref n) => {
815 primitive_link(f, PrimitiveType::Array, "[", cx)?;
816 fmt::Display::fmt(&t.print(cx), f)?;
818 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
820 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
823 clean::RawPointer(m, ref t) => {
825 hir::Mutability::Mut => "mut",
826 hir::Mutability::Not => "const",
829 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
830 let text = if f.alternate() {
831 format!("*{} {:#}", m, t.print(cx))
833 format!("*{} {}", m, t.print(cx))
835 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
837 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
838 fmt::Display::fmt(&t.print(cx), f)
841 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
843 Some(l) => format!("{} ", l.print()),
846 let m = mutability.print_with_space();
847 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
849 clean::Slice(ref bt) => {
850 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
852 clean::Generic(_) => {
856 PrimitiveType::Slice,
857 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
863 PrimitiveType::Slice,
864 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
872 PrimitiveType::Slice,
873 &format!("{}{}{}[", amp, lt, m),
877 write!(f, "{:#}", bt.print(cx))?;
879 write!(f, "{}", bt.print(cx))?;
881 primitive_link(f, PrimitiveType::Slice, "]", cx)
885 clean::DynTrait(ref bounds, ref trait_lt)
886 if bounds.len() > 1 || trait_lt.is_some() =>
888 write!(f, "{}{}{}(", amp, lt, m)?;
889 fmt_type(ty, f, use_absolute, cx)?;
892 clean::Generic(..) => {
895 PrimitiveType::Reference,
896 &format!("{}{}{}", amp, lt, m),
899 fmt_type(ty, f, use_absolute, cx)
902 write!(f, "{}{}{}", amp, lt, m)?;
903 fmt_type(ty, f, use_absolute, cx)
907 clean::ImplTrait(ref bounds) => {
909 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
911 write!(f, "impl {}", print_generic_bounds(bounds, cx))
914 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
915 let should_show_cast = !trait_.segments.is_empty()
917 .zip(Some(trait_.def_id()))
918 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_);
920 if should_show_cast {
921 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
923 write!(f, "{:#}::", self_type.print(cx))?
926 if should_show_cast {
927 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
929 write!(f, "{}::", self_type.print(cx))?
932 // It's pretty unsightly to look at `<A as B>::C` in output, and
933 // we've got hyperlinking on our side, so try to avoid longer
934 // notation as much as possible by making `C` a hyperlink to trait
935 // `B` to disambiguate.
937 // FIXME: this is still a lossy conversion and there should probably
938 // be a better way of representing this in general? Most of
939 // the ugliness comes from inlining across crates where
940 // everything comes in as a fully resolved QPath (hard to
942 match href(trait_.def_id(), cx) {
943 Ok((ref url, _, ref path)) if !f.alternate() => {
946 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
947 title=\"type {path}::{name}\">{name}</a>",
949 shortty = ItemType::AssocType,
951 path = path.join("::")
954 _ => write!(f, "{}", name)?,
962 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
964 cx: &'a Context<'tcx>,
965 ) -> impl fmt::Display + 'b + Captures<'tcx> {
966 display_fn(move |f| fmt_type(self, f, false, cx))
971 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
973 cx: &'a Context<'tcx>,
974 ) -> impl fmt::Display + 'b + Captures<'tcx> {
975 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
980 crate fn print<'a, 'tcx: 'a>(
983 cx: &'a Context<'tcx>,
984 ) -> impl fmt::Display + 'a + Captures<'tcx> {
985 display_fn(move |f| {
987 write!(f, "impl{:#} ", self.generics.print(cx))?;
989 write!(f, "impl{} ", self.generics.print(cx))?;
992 if let Some(ref ty) = self.trait_ {
993 if self.negative_polarity {
996 fmt::Display::fmt(&ty.print(cx), f)?;
1000 if let Some(ref ty) = self.blanket_impl {
1001 fmt_type(ty, f, use_absolute, cx)?;
1003 fmt_type(&self.for_, f, use_absolute, cx)?;
1006 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1012 impl clean::Arguments {
1013 crate fn print<'a, 'tcx: 'a>(
1015 cx: &'a Context<'tcx>,
1016 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1017 display_fn(move |f| {
1018 for (i, input) in self.values.iter().enumerate() {
1019 if !input.name.is_empty() {
1020 write!(f, "{}: ", input.name)?;
1023 write!(f, "{:#}", input.type_.print(cx))?;
1025 write!(f, "{}", input.type_.print(cx))?;
1027 if i + 1 < self.values.len() {
1036 impl clean::FnRetTy {
1037 crate fn print<'a, 'tcx: 'a>(
1039 cx: &'a Context<'tcx>,
1040 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1041 display_fn(move |f| match self {
1042 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1043 clean::Return(ty) if f.alternate() => {
1044 write!(f, " -> {:#}", ty.print(cx))
1046 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1047 clean::DefaultReturn => Ok(()),
1052 impl clean::BareFunctionDecl {
1053 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1055 cx: &'a Context<'tcx>,
1056 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1057 display_fn(move |f| {
1058 if !self.generic_params.is_empty() {
1062 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
1071 impl clean::FnDecl {
1072 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1074 cx: &'a Context<'tcx>,
1075 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1076 display_fn(move |f| {
1077 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1081 "({args:#}{ellipsis}){arrow:#}",
1082 args = self.inputs.print(cx),
1083 ellipsis = ellipsis,
1084 arrow = self.output.print(cx)
1089 "({args}{ellipsis}){arrow}",
1090 args = self.inputs.print(cx),
1091 ellipsis = ellipsis,
1092 arrow = self.output.print(cx)
1098 /// * `header_len`: The length of the function header and name. In other words, the number of
1099 /// characters in the function declaration up to but not including the parentheses.
1100 /// <br>Used to determine line-wrapping.
1101 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1103 /// * `asyncness`: Whether the function is async or not.
1104 crate fn full_print<'a, 'tcx: 'a>(
1108 asyncness: hir::IsAsync,
1109 cx: &'a Context<'tcx>,
1110 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1111 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1114 fn inner_full_print(
1118 asyncness: hir::IsAsync,
1119 f: &mut fmt::Formatter<'_>,
1122 let amp = if f.alternate() { "&" } else { "&" };
1123 let mut args = String::new();
1124 let mut args_plain = String::new();
1125 for (i, input) in self.inputs.values.iter().enumerate() {
1127 args.push_str("<br>");
1130 if let Some(selfty) = input.to_self() {
1132 clean::SelfValue => {
1133 args.push_str("self");
1134 args_plain.push_str("self");
1136 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1137 args.push_str(&format!(
1141 mtbl.print_with_space()
1143 args_plain.push_str(&format!(
1146 mtbl.print_with_space()
1149 clean::SelfBorrowed(None, mtbl) => {
1150 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1151 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1153 clean::SelfExplicit(ref typ) => {
1155 args.push_str(&format!("self: {:#}", typ.print(cx)));
1157 args.push_str(&format!("self: {}", typ.print(cx)));
1159 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1164 args.push_str(" <br>");
1165 args_plain.push(' ');
1167 if !input.name.is_empty() {
1168 args.push_str(&format!("{}: ", input.name));
1169 args_plain.push_str(&format!("{}: ", input.name));
1173 args.push_str(&format!("{:#}", input.type_.print(cx)));
1175 args.push_str(&input.type_.print(cx).to_string());
1177 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1179 if i + 1 < self.inputs.values.len() {
1181 args_plain.push(',');
1185 let mut args_plain = format!("({})", args_plain);
1187 if self.c_variadic {
1188 args.push_str(",<br> ...");
1189 args_plain.push_str(", ...");
1193 let arrow = if let hir::IsAsync::Async = asyncness {
1194 let output = self.sugared_async_return_type();
1195 arrow_plain = format!("{:#}", output.print(cx));
1196 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1198 arrow_plain = format!("{:#}", self.output.print(cx));
1199 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1202 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1203 let output = if declaration_len > 80 {
1204 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1205 let close_pad = format!("<br>{}", " ".repeat(indent));
1207 "({args}{close}){arrow}",
1208 args = args.replace("<br>", &full_pad),
1213 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1217 write!(f, "{}", output.replace("<br>", "\n"))
1219 write!(f, "{}", output)
1224 impl clean::Visibility {
1225 crate fn print_with_space<'a, 'tcx: 'a>(
1228 cx: &'a Context<'tcx>,
1229 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1230 let to_print = match self {
1231 clean::Public => "pub ".to_owned(),
1232 clean::Inherited => String::new(),
1233 clean::Visibility::Restricted(vis_did) => {
1234 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1235 // However, rustdoc currently never displays a module's
1236 // visibility, so it shouldn't matter.
1237 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1239 if vis_did.index == CRATE_DEF_INDEX {
1240 "pub(crate) ".to_owned()
1241 } else if parent_module == Some(vis_did) {
1242 // `pub(in foo)` where `foo` is the parent module
1243 // is the same as no visibility modifier
1245 } else if parent_module
1246 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1250 "pub(super) ".to_owned()
1252 let path = cx.tcx().def_path(vis_did);
1253 debug!("path={:?}", path);
1254 // modified from `resolved_path()` to work with `DefPathData`
1255 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1256 let anchor = anchor(vis_did, &last_name.as_str(), cx).to_string();
1258 let mut s = "pub(in ".to_owned();
1259 for seg in &path.data[..path.data.len() - 1] {
1260 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1262 s.push_str(&format!("{}) ", anchor));
1267 display_fn(move |f| f.write_str(&to_print))
1270 /// This function is the same as print_with_space, except that it renders no links.
1271 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1273 crate fn to_src_with_space<'a, 'tcx: 'a>(
1277 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1278 let to_print = match self {
1279 clean::Public => "pub ".to_owned(),
1280 clean::Inherited => String::new(),
1281 clean::Visibility::Restricted(vis_did) => {
1282 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1283 // However, rustdoc currently never displays a module's
1284 // visibility, so it shouldn't matter.
1285 let parent_module = find_nearest_parent_module(tcx, item_did);
1287 if vis_did.index == CRATE_DEF_INDEX {
1288 "pub(crate) ".to_owned()
1289 } else if parent_module == Some(vis_did) {
1290 // `pub(in foo)` where `foo` is the parent module
1291 // is the same as no visibility modifier
1293 } else if parent_module
1294 .map(|parent| find_nearest_parent_module(tcx, parent))
1298 "pub(super) ".to_owned()
1300 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1304 display_fn(move |f| f.write_str(&to_print))
1308 crate trait PrintWithSpace {
1309 fn print_with_space(&self) -> &str;
1312 impl PrintWithSpace for hir::Unsafety {
1313 fn print_with_space(&self) -> &str {
1315 hir::Unsafety::Unsafe => "unsafe ",
1316 hir::Unsafety::Normal => "",
1321 impl PrintWithSpace for hir::IsAsync {
1322 fn print_with_space(&self) -> &str {
1324 hir::IsAsync::Async => "async ",
1325 hir::IsAsync::NotAsync => "",
1330 impl PrintWithSpace for hir::Mutability {
1331 fn print_with_space(&self) -> &str {
1333 hir::Mutability::Not => "",
1334 hir::Mutability::Mut => "mut ",
1339 crate fn print_constness_with_space(
1341 s: Option<&ConstStability>,
1344 // const stable or when feature(staged_api) is not set
1346 hir::Constness::Const,
1347 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1349 | (hir::Constness::Const, None) => "const ",
1350 // const unstable or not const
1355 impl clean::Import {
1356 crate fn print<'a, 'tcx: 'a>(
1358 cx: &'a Context<'tcx>,
1359 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1360 display_fn(move |f| match self.kind {
1361 clean::ImportKind::Simple(name) => {
1362 if name == self.source.path.last() {
1363 write!(f, "use {};", self.source.print(cx))
1365 write!(f, "use {} as {};", self.source.print(cx), name)
1368 clean::ImportKind::Glob => {
1369 if self.source.path.segments.is_empty() {
1372 write!(f, "use {}::*;", self.source.print(cx))
1379 impl clean::ImportSource {
1380 crate fn print<'a, 'tcx: 'a>(
1382 cx: &'a Context<'tcx>,
1383 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1384 display_fn(move |f| match self.did {
1385 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1387 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1388 write!(f, "{}::", seg.name)?;
1390 let name = self.path.last_name();
1391 if let hir::def::Res::PrimTy(p) = self.path.res {
1392 primitive_link(f, PrimitiveType::from(p), &*name, cx)?;
1394 write!(f, "{}", name)?;
1402 impl clean::TypeBinding {
1403 crate fn print<'a, 'tcx: 'a>(
1405 cx: &'a Context<'tcx>,
1406 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1407 display_fn(move |f| {
1408 f.write_str(&*self.name.as_str())?;
1410 clean::TypeBindingKind::Equality { ref ty } => {
1412 write!(f, " = {:#}", ty.print(cx))?;
1414 write!(f, " = {}", ty.print(cx))?;
1417 clean::TypeBindingKind::Constraint { ref bounds } => {
1418 if !bounds.is_empty() {
1420 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1422 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1432 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1433 display_fn(move |f| {
1434 let quot = if f.alternate() { "\"" } else { """ };
1436 Abi::Rust => Ok(()),
1437 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1442 crate fn print_default_space<'a>(v: bool) -> &'a str {
1443 if v { "default " } else { "" }
1446 impl clean::GenericArg {
1447 crate fn print<'a, 'tcx: 'a>(
1449 cx: &'a Context<'tcx>,
1450 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1451 display_fn(move |f| match self {
1452 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1453 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1454 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1455 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1460 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1461 struct WithFormatter<F>(Cell<Option<F>>);
1463 impl<F> fmt::Display for WithFormatter<F>
1465 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1468 (self.0.take()).unwrap()(f)
1472 WithFormatter(Cell::new(Some(f)))