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 // `DefId` is in an unknown location. This seems to happen when building without dependencies
478 // but a trait from a dependency is still visible
480 // Unavailable because private
482 // Not in external cache, href link should be in same page
486 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<String>), HrefError> {
487 let cache = &cx.cache();
488 let relative_to = &cx.current;
489 fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
490 if shortty == ItemType::Module { &fqp[..] } else { &fqp[..fqp.len() - 1] }
493 if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
494 return Err(HrefError::Unavailable);
497 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
498 Some(&(ref fqp, shortty)) => (fqp, shortty, {
499 let module_fqp = to_module_fqp(shortty, fqp);
500 href_relative_parts(module_fqp, relative_to)
503 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
504 let module_fqp = to_module_fqp(shortty, fqp);
508 match cache.extern_locations[&did.krate] {
509 ExternalLocation::Remote(ref s) => {
510 let s = s.trim_end_matches('/');
511 let mut s = vec![&s[..]];
512 s.extend(module_fqp[..].iter().map(String::as_str));
515 ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
516 ExternalLocation::Unknown => return Err(HrefError::UnknownLocation),
520 return Err(HrefError::NotInExternalCache);
524 let last = &fqp.last().unwrap()[..];
527 ItemType::Module => {
528 url_parts.push("index.html");
531 filename = format!("{}.{}.html", shortty.as_str(), last);
532 url_parts.push(&filename);
535 Ok((url_parts.join("/"), shortty, fqp.to_vec()))
538 /// Both paths should only be modules.
539 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
540 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
541 crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String]) -> Vec<&'a str> {
542 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
543 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
545 let dissimilar_part_count = relative_to_fqp.len() - i;
546 let fqp_module = fqp[i..fqp.len()].iter().map(String::as_str);
547 return iter::repeat("..").take(dissimilar_part_count).chain(fqp_module).collect();
550 // e.g. linking to std::sync::atomic from std::sync
551 if relative_to_fqp.len() < fqp.len() {
552 fqp[relative_to_fqp.len()..fqp.len()].iter().map(String::as_str).collect()
553 // e.g. linking to std::sync from std::sync::atomic
554 } else if fqp.len() < relative_to_fqp.len() {
555 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
556 iter::repeat("..").take(dissimilar_part_count).collect()
557 // linking to the same module
563 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
564 /// rendering function with the necessary arguments for linking to a local path.
565 fn resolved_path<'a, 'cx: 'a>(
566 w: &mut fmt::Formatter<'_>,
571 cx: &'cx Context<'_>,
573 let last = path.segments.last().unwrap();
576 for seg in &path.segments[..path.segments.len() - 1] {
577 write!(w, "{}::", seg.name)?;
581 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
583 let path = if use_absolute {
584 if let Ok((_, _, fqp)) = href(did, cx) {
587 fqp[..fqp.len() - 1].join("::"),
588 anchor(did, fqp.last().unwrap(), cx)
591 last.name.to_string()
594 anchor(did, &*last.name.as_str(), cx).to_string()
596 write!(w, "{}{}", path, last.args.print(cx))?;
602 f: &mut fmt::Formatter<'_>,
603 prim: clean::PrimitiveType,
608 let mut needs_termination = false;
610 match m.primitive_locations.get(&prim) {
611 Some(&def_id) if def_id.is_local() => {
612 let len = cx.current.len();
613 let len = if len == 0 { 0 } else { len - 1 };
616 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
620 needs_termination = true;
624 let loc = match m.extern_locations[&def_id.krate] {
625 ExternalLocation::Remote(ref s) => {
627 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
628 Some(vec![s.trim_end_matches('/'), &cname_str[..]])
630 ExternalLocation::Local => {
632 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
633 Some(if cx.current.first().map(|x| &x[..]) == Some(&cname_str[..]) {
634 iter::repeat("..").take(cx.current.len() - 1).collect()
636 let cname = iter::once(&cname_str[..]);
637 iter::repeat("..").take(cx.current.len()).chain(cname).collect()
640 ExternalLocation::Unknown => None,
642 if let Some(loc) = loc {
645 "<a class=\"primitive\" href=\"{}/primitive.{}.html\">",
649 needs_termination = true;
655 write!(f, "{}", name)?;
656 if needs_termination {
662 /// Helper to render type parameters
663 fn tybounds<'a, 'tcx: 'a>(
664 bounds: &'a Vec<clean::PolyTrait>,
665 lt: &'a Option<clean::Lifetime>,
666 cx: &'a Context<'tcx>,
667 ) -> impl fmt::Display + 'a + Captures<'tcx> {
668 display_fn(move |f| {
669 for (i, bound) in bounds.iter().enumerate() {
674 fmt::Display::fmt(&bound.print(cx), f)?;
677 if let Some(lt) = lt {
679 fmt::Display::fmt(<.print(), f)?;
685 crate fn anchor<'a, 'cx: 'a>(
688 cx: &'cx Context<'_>,
689 ) -> impl fmt::Display + 'a {
690 let parts = href(did.into(), cx);
691 display_fn(move |f| {
692 if let Ok((url, short_ty, fqp)) = parts {
695 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
703 write!(f, "{}", text)
710 f: &mut fmt::Formatter<'_>,
712 cx: &'cx Context<'_>,
714 debug!("fmt_type(t = {:?})", t);
717 clean::Generic(name) => write!(f, "{}", name),
718 clean::ResolvedPath { did, ref path, is_generic } => {
719 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
720 resolved_path(f, did, path, is_generic, use_absolute, cx)
722 clean::DynTrait(ref bounds, ref lt) => {
723 f.write_str("dyn ")?;
724 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
726 clean::Infer => write!(f, "_"),
727 clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
728 clean::BareFunction(ref decl) => {
733 decl.print_hrtb_with_space(cx),
734 decl.unsafety.print_with_space(),
735 print_abi_with_space(decl.abi),
742 decl.print_hrtb_with_space(cx),
743 decl.unsafety.print_with_space(),
744 print_abi_with_space(decl.abi)
746 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
747 write!(f, "{}", decl.decl.print(cx))
750 clean::Tuple(ref typs) => {
752 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
754 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
755 // Carry `f.alternate()` into this display w/o branching manually.
756 fmt::Display::fmt(&one.print(cx), f)?;
757 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
760 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
761 for (i, item) in many.iter().enumerate() {
765 fmt::Display::fmt(&item.print(cx), f)?;
767 primitive_link(f, PrimitiveType::Tuple, ")", cx)
771 clean::Slice(ref t) => {
772 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
773 fmt::Display::fmt(&t.print(cx), f)?;
774 primitive_link(f, PrimitiveType::Slice, "]", cx)
776 clean::Array(ref t, ref n) => {
777 primitive_link(f, PrimitiveType::Array, "[", cx)?;
778 fmt::Display::fmt(&t.print(cx), f)?;
780 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
782 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
785 clean::Never => primitive_link(f, PrimitiveType::Never, "!", cx),
786 clean::RawPointer(m, ref t) => {
788 hir::Mutability::Mut => "mut",
789 hir::Mutability::Not => "const",
792 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
796 clean::PrimitiveType::RawPointer,
797 &format!("*{} {:#}", m, t.print(cx)),
803 clean::PrimitiveType::RawPointer,
804 &format!("*{} {}", m, t.print(cx)),
810 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
811 fmt::Display::fmt(&t.print(cx), f)
815 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
817 Some(l) => format!("{} ", l.print()),
820 let m = mutability.print_with_space();
821 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
823 clean::Slice(ref bt) => {
824 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
826 clean::Generic(_) => {
830 PrimitiveType::Slice,
831 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
837 PrimitiveType::Slice,
838 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
846 PrimitiveType::Slice,
847 &format!("{}{}{}[", amp, lt, m),
851 write!(f, "{:#}", bt.print(cx))?;
853 write!(f, "{}", bt.print(cx))?;
855 primitive_link(f, PrimitiveType::Slice, "]", cx)
859 clean::DynTrait(ref bounds, ref trait_lt)
860 if bounds.len() > 1 || trait_lt.is_some() =>
862 write!(f, "{}{}{}(", amp, lt, m)?;
863 fmt_type(&ty, f, use_absolute, cx)?;
866 clean::Generic(..) => {
869 PrimitiveType::Reference,
870 &format!("{}{}{}", amp, lt, m),
873 fmt_type(&ty, f, use_absolute, cx)
876 write!(f, "{}{}{}", amp, lt, m)?;
877 fmt_type(&ty, f, use_absolute, cx)
881 clean::ImplTrait(ref bounds) => {
883 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
885 write!(f, "impl {}", print_generic_bounds(bounds, cx))
888 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
889 let should_show_cast = match *trait_ {
890 box clean::ResolvedPath { ref path, .. } => {
891 !path.segments.is_empty()
893 .zip(trait_.def_id())
894 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
899 if should_show_cast {
900 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
902 write!(f, "{:#}::", self_type.print(cx))?
905 if should_show_cast {
906 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
908 write!(f, "{}::", self_type.print(cx))?
912 // It's pretty unsightly to look at `<A as B>::C` in output, and
913 // we've got hyperlinking on our side, so try to avoid longer
914 // notation as much as possible by making `C` a hyperlink to trait
915 // `B` to disambiguate.
917 // FIXME: this is still a lossy conversion and there should probably
918 // be a better way of representing this in general? Most of
919 // the ugliness comes from inlining across crates where
920 // everything comes in as a fully resolved QPath (hard to
922 box clean::ResolvedPath { did, .. } => {
923 match href(did.into(), cx) {
924 Ok((ref url, _, ref path)) if !f.alternate() => {
927 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
928 title=\"type {path}::{name}\">{name}</a>",
930 shortty = ItemType::AssocType,
932 path = path.join("::")
935 _ => write!(f, "{}", name)?,
939 _ => write!(f, "{}", name),
946 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
948 cx: &'a Context<'tcx>,
949 ) -> impl fmt::Display + 'b + Captures<'tcx> {
950 display_fn(move |f| fmt_type(self, f, false, cx))
955 crate fn print<'a, 'tcx: 'a>(
958 cx: &'a Context<'tcx>,
959 ) -> impl fmt::Display + 'a + Captures<'tcx> {
960 display_fn(move |f| {
962 write!(f, "impl{:#} ", self.generics.print(cx))?;
964 write!(f, "impl{} ", self.generics.print(cx))?;
967 if let Some(ref ty) = self.trait_ {
968 if self.negative_polarity {
971 fmt::Display::fmt(&ty.print(cx), f)?;
975 if let Some(ref ty) = self.blanket_impl {
976 fmt_type(ty, f, use_absolute, cx)?;
978 fmt_type(&self.for_, f, use_absolute, cx)?;
981 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
987 impl clean::Arguments {
988 crate fn print<'a, 'tcx: 'a>(
990 cx: &'a Context<'tcx>,
991 ) -> impl fmt::Display + 'a + Captures<'tcx> {
992 display_fn(move |f| {
993 for (i, input) in self.values.iter().enumerate() {
994 if !input.name.is_empty() {
995 write!(f, "{}: ", input.name)?;
998 write!(f, "{:#}", input.type_.print(cx))?;
1000 write!(f, "{}", input.type_.print(cx))?;
1002 if i + 1 < self.values.len() {
1011 impl clean::FnRetTy {
1012 crate fn print<'a, 'tcx: 'a>(
1014 cx: &'a Context<'tcx>,
1015 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1016 display_fn(move |f| match self {
1017 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1018 clean::Return(ty) if f.alternate() => {
1019 write!(f, " -> {:#}", ty.print(cx))
1021 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1022 clean::DefaultReturn => Ok(()),
1027 impl clean::BareFunctionDecl {
1028 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1030 cx: &'a Context<'tcx>,
1031 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1032 display_fn(move |f| {
1033 if !self.generic_params.is_empty() {
1034 write!(f, "for<{}> ", comma_sep(self.generic_params.iter().map(|g| g.print(cx))))
1042 impl clean::FnDecl {
1043 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1045 cx: &'a Context<'tcx>,
1046 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1047 display_fn(move |f| {
1048 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1052 "({args:#}{ellipsis}){arrow:#}",
1053 args = self.inputs.print(cx),
1054 ellipsis = ellipsis,
1055 arrow = self.output.print(cx)
1060 "({args}{ellipsis}){arrow}",
1061 args = self.inputs.print(cx),
1062 ellipsis = ellipsis,
1063 arrow = self.output.print(cx)
1069 /// * `header_len`: The length of the function header and name. In other words, the number of
1070 /// characters in the function declaration up to but not including the parentheses.
1071 /// <br>Used to determine line-wrapping.
1072 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1074 /// * `asyncness`: Whether the function is async or not.
1075 crate fn full_print<'a, 'tcx: 'a>(
1079 asyncness: hir::IsAsync,
1080 cx: &'a Context<'tcx>,
1081 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1082 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1085 fn inner_full_print(
1089 asyncness: hir::IsAsync,
1090 f: &mut fmt::Formatter<'_>,
1093 let amp = if f.alternate() { "&" } else { "&" };
1094 let mut args = String::new();
1095 let mut args_plain = String::new();
1096 for (i, input) in self.inputs.values.iter().enumerate() {
1098 args.push_str("<br>");
1101 if let Some(selfty) = input.to_self() {
1103 clean::SelfValue => {
1104 args.push_str("self");
1105 args_plain.push_str("self");
1107 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1108 args.push_str(&format!(
1112 mtbl.print_with_space()
1114 args_plain.push_str(&format!(
1117 mtbl.print_with_space()
1120 clean::SelfBorrowed(None, mtbl) => {
1121 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1122 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1124 clean::SelfExplicit(ref typ) => {
1126 args.push_str(&format!("self: {:#}", typ.print(cx)));
1128 args.push_str(&format!("self: {}", typ.print(cx)));
1130 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1135 args.push_str(" <br>");
1136 args_plain.push(' ');
1138 if !input.name.is_empty() {
1139 args.push_str(&format!("{}: ", input.name));
1140 args_plain.push_str(&format!("{}: ", input.name));
1144 args.push_str(&format!("{:#}", input.type_.print(cx)));
1146 args.push_str(&input.type_.print(cx).to_string());
1148 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1150 if i + 1 < self.inputs.values.len() {
1152 args_plain.push(',');
1156 let mut args_plain = format!("({})", args_plain);
1158 if self.c_variadic {
1159 args.push_str(",<br> ...");
1160 args_plain.push_str(", ...");
1164 let arrow = if let hir::IsAsync::Async = asyncness {
1165 let output = self.sugared_async_return_type();
1166 arrow_plain = format!("{:#}", output.print(cx));
1167 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1169 arrow_plain = format!("{:#}", self.output.print(cx));
1170 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1173 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1174 let output = if declaration_len > 80 {
1175 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1176 let close_pad = format!("<br>{}", " ".repeat(indent));
1178 "({args}{close}){arrow}",
1179 args = args.replace("<br>", &full_pad),
1184 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1188 write!(f, "{}", output.replace("<br>", "\n"))
1190 write!(f, "{}", output)
1195 impl clean::Visibility {
1196 crate fn print_with_space<'a, 'tcx: 'a>(
1199 cx: &'a Context<'tcx>,
1200 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1201 let to_print = match self {
1202 clean::Public => "pub ".to_owned(),
1203 clean::Inherited => String::new(),
1204 clean::Visibility::Restricted(vis_did) => {
1205 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1206 // However, rustdoc currently never displays a module's
1207 // visibility, so it shouldn't matter.
1208 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1210 if vis_did.index == CRATE_DEF_INDEX {
1211 "pub(crate) ".to_owned()
1212 } else if parent_module == Some(vis_did) {
1213 // `pub(in foo)` where `foo` is the parent module
1214 // is the same as no visibility modifier
1216 } else if parent_module
1217 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1221 "pub(super) ".to_owned()
1223 let path = cx.tcx().def_path(vis_did);
1224 debug!("path={:?}", path);
1225 // modified from `resolved_path()` to work with `DefPathData`
1226 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1227 let anchor = anchor(vis_did, &last_name.as_str(), cx).to_string();
1229 let mut s = "pub(in ".to_owned();
1230 for seg in &path.data[..path.data.len() - 1] {
1231 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1233 s.push_str(&format!("{}) ", anchor));
1238 display_fn(move |f| f.write_str(&to_print))
1241 /// This function is the same as print_with_space, except that it renders no links.
1242 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1244 crate fn to_src_with_space<'a, 'tcx: 'a>(
1248 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1249 let to_print = match self {
1250 clean::Public => "pub ".to_owned(),
1251 clean::Inherited => String::new(),
1252 clean::Visibility::Restricted(vis_did) => {
1253 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1254 // However, rustdoc currently never displays a module's
1255 // visibility, so it shouldn't matter.
1256 let parent_module = find_nearest_parent_module(tcx, item_did);
1258 if vis_did.index == CRATE_DEF_INDEX {
1259 "pub(crate) ".to_owned()
1260 } else if parent_module == Some(vis_did) {
1261 // `pub(in foo)` where `foo` is the parent module
1262 // is the same as no visibility modifier
1264 } else if parent_module
1265 .map(|parent| find_nearest_parent_module(tcx, parent))
1269 "pub(super) ".to_owned()
1271 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1275 display_fn(move |f| f.write_str(&to_print))
1279 crate trait PrintWithSpace {
1280 fn print_with_space(&self) -> &str;
1283 impl PrintWithSpace for hir::Unsafety {
1284 fn print_with_space(&self) -> &str {
1286 hir::Unsafety::Unsafe => "unsafe ",
1287 hir::Unsafety::Normal => "",
1292 impl PrintWithSpace for hir::IsAsync {
1293 fn print_with_space(&self) -> &str {
1295 hir::IsAsync::Async => "async ",
1296 hir::IsAsync::NotAsync => "",
1301 impl PrintWithSpace for hir::Mutability {
1302 fn print_with_space(&self) -> &str {
1304 hir::Mutability::Not => "",
1305 hir::Mutability::Mut => "mut ",
1310 crate fn print_constness_with_space(
1312 s: Option<&ConstStability>,
1315 // const stable or when feature(staged_api) is not set
1317 hir::Constness::Const,
1318 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1320 | (hir::Constness::Const, None) => "const ",
1321 // const unstable or not const
1326 impl clean::Import {
1327 crate fn print<'a, 'tcx: 'a>(
1329 cx: &'a Context<'tcx>,
1330 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1331 display_fn(move |f| match self.kind {
1332 clean::ImportKind::Simple(name) => {
1333 if name == self.source.path.last() {
1334 write!(f, "use {};", self.source.print(cx))
1336 write!(f, "use {} as {};", self.source.print(cx), name)
1339 clean::ImportKind::Glob => {
1340 if self.source.path.segments.is_empty() {
1343 write!(f, "use {}::*;", self.source.print(cx))
1350 impl clean::ImportSource {
1351 crate fn print<'a, 'tcx: 'a>(
1353 cx: &'a Context<'tcx>,
1354 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1355 display_fn(move |f| match self.did {
1356 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1358 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1359 write!(f, "{}::", seg.name)?;
1361 let name = self.path.last_name();
1362 if let hir::def::Res::PrimTy(p) = self.path.res {
1363 primitive_link(f, PrimitiveType::from(p), &*name, cx)?;
1365 write!(f, "{}", name)?;
1373 impl clean::TypeBinding {
1374 crate fn print<'a, 'tcx: 'a>(
1376 cx: &'a Context<'tcx>,
1377 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1378 display_fn(move |f| {
1379 f.write_str(&*self.name.as_str())?;
1381 clean::TypeBindingKind::Equality { ref ty } => {
1383 write!(f, " = {:#}", ty.print(cx))?;
1385 write!(f, " = {}", ty.print(cx))?;
1388 clean::TypeBindingKind::Constraint { ref bounds } => {
1389 if !bounds.is_empty() {
1391 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1393 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1403 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1404 display_fn(move |f| {
1405 let quot = if f.alternate() { "\"" } else { """ };
1407 Abi::Rust => Ok(()),
1408 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1413 crate fn print_default_space<'a>(v: bool) -> &'a str {
1414 if v { "default " } else { "" }
1417 impl clean::GenericArg {
1418 crate fn print<'a, 'tcx: 'a>(
1420 cx: &'a Context<'tcx>,
1421 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1422 display_fn(move |f| match self {
1423 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1424 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1425 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1430 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1431 struct WithFormatter<F>(Cell<Option<F>>);
1433 impl<F> fmt::Display for WithFormatter<F>
1435 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1438 (self.0.take()).unwrap()(f)
1442 WithFormatter(Cell::new(Some(f)))