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_data_structures::fx::FxHashSet;
14 use rustc_hir::def_id::DefId;
15 use rustc_target::spec::abi::Abi;
17 use crate::clean::{self, PrimitiveType};
18 use crate::html::escape::Escape;
19 use crate::html::item_type::ItemType;
20 use crate::html::render::{self, cache, CURRENT_DEPTH};
23 fn print(self, buffer: &mut Buffer);
28 F: FnOnce(&mut Buffer),
30 fn print(self, buffer: &mut Buffer) {
35 impl Print for String {
36 fn print(self, buffer: &mut Buffer) {
37 buffer.write_str(&self);
41 impl Print for &'_ str {
42 fn print(self, buffer: &mut Buffer) {
43 buffer.write_str(self);
47 #[derive(Debug, Clone)]
54 crate fn empty_from(v: &Buffer) -> Buffer {
55 Buffer { for_html: v.for_html, buffer: String::new() }
58 crate fn html() -> Buffer {
59 Buffer { for_html: true, buffer: String::new() }
62 crate fn new() -> Buffer {
63 Buffer { for_html: false, buffer: String::new() }
66 crate fn is_empty(&self) -> bool {
67 self.buffer.is_empty()
70 crate fn into_inner(self) -> String {
74 crate fn insert_str(&mut self, idx: usize, s: &str) {
75 self.buffer.insert_str(idx, s);
78 crate fn push_str(&mut self, s: &str) {
79 self.buffer.push_str(s);
82 // Intended for consumption by write! and writeln! (std::fmt) but without
83 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
85 crate fn write_str(&mut self, s: &str) {
86 self.buffer.push_str(s);
89 // Intended for consumption by write! and writeln! (std::fmt) but without
90 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
92 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
94 self.buffer.write_fmt(v).unwrap();
97 crate fn to_display<T: Print>(mut self, t: T) -> String {
102 crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
104 write!(self, "{}", t);
106 write!(self, "{:#}", t);
110 crate fn is_for_html(&self) -> bool {
115 /// Wrapper struct for properly emitting a function or method declaration.
116 pub struct Function<'a> {
117 /// The declaration to emit.
118 pub decl: &'a clean::FnDecl,
119 /// The length of the function header and name. In other words, the number of characters in the
120 /// function declaration up to but not including the parentheses.
122 /// Used to determine line-wrapping.
123 pub header_len: usize,
124 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
126 /// Whether the function is async or not.
127 pub asyncness: hir::IsAsync,
130 /// Wrapper struct for emitting a where-clause from Generics.
131 pub struct WhereClause<'a> {
132 /// The Generics from which to emit a where-clause.
133 pub gens: &'a clean::Generics,
134 /// The number of spaces to indent each line with.
136 /// Whether the where-clause needs to add a comma and newline after the last bound.
137 pub end_newline: bool,
140 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
141 display_fn(move |f| {
142 for (i, item) in items.enumerate() {
146 fmt::Display::fmt(&item, f)?;
152 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
153 display_fn(move |f| {
154 let mut bounds_dup = FxHashSet::default();
157 bounds.iter().filter(|b| bounds_dup.insert(b.print().to_string())).enumerate()
162 fmt::Display::fmt(&bound.print(), f)?;
168 impl clean::GenericParamDef {
169 crate fn print(&self) -> impl fmt::Display + '_ {
170 display_fn(move |f| match self.kind {
171 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
172 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
173 f.write_str(&self.name)?;
175 if !bounds.is_empty() {
177 write!(f, ": {:#}", print_generic_bounds(bounds))?;
179 write!(f, ": {}", print_generic_bounds(bounds))?;
183 if let Some(ref ty) = default {
185 write!(f, " = {:#}", ty.print())?;
187 write!(f, " = {}", ty.print())?;
193 clean::GenericParamDefKind::Const { ref ty, .. } => {
194 f.write_str("const ")?;
195 f.write_str(&self.name)?;
198 write!(f, ": {:#}", ty.print())
200 write!(f, ": {}", ty.print())
207 impl clean::Generics {
208 crate fn print(&self) -> impl fmt::Display + '_ {
209 display_fn(move |f| {
211 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
212 if real_params.is_empty() {
216 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
218 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print())))
224 impl<'a> fmt::Display for WhereClause<'a> {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 let &WhereClause { gens, indent, end_newline } = self;
227 if gens.where_predicates.is_empty() {
230 let mut clause = String::new();
232 clause.push_str(" where");
235 clause.push_str(" <span class=\"where fmt-newline\">where");
237 clause.push_str(" <span class=\"where\">where");
240 for (i, pred) in gens.where_predicates.iter().enumerate() {
244 clause.push_str("<br>");
248 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
251 clause.push_str(&format!(
254 print_generic_bounds(bounds)
257 clause.push_str(&format!(
260 print_generic_bounds(bounds)
264 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
265 clause.push_str(&format!(
270 .map(|b| b.print().to_string())
275 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
277 clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
279 clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
284 if i < gens.where_predicates.len() - 1 || end_newline {
290 // add a space so stripping <br> tags and breaking spaces still renders properly
294 clause.push_str(" ");
299 clause.push_str("</span>");
300 let padding = " ".repeat(indent + 4);
301 clause = clause.replace("<br>", &format!("<br>{}", padding));
302 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
304 clause.insert_str(0, "<br>");
307 write!(f, "{}", clause)
311 impl clean::Lifetime {
312 crate fn print(&self) -> &str {
317 impl clean::Constant {
318 crate fn print(&self) -> impl fmt::Display + '_ {
319 display_fn(move |f| {
321 f.write_str(&self.expr)
323 write!(f, "{}", Escape(&self.expr))
329 impl clean::PolyTrait {
330 fn print(&self) -> impl fmt::Display + '_ {
331 display_fn(move |f| {
332 if !self.generic_params.is_empty() {
337 comma_sep(self.generic_params.iter().map(|g| g.print()))
343 comma_sep(self.generic_params.iter().map(|g| g.print()))
348 write!(f, "{:#}", self.trait_.print())
350 write!(f, "{}", self.trait_.print())
356 impl clean::GenericBound {
357 crate fn print(&self) -> impl fmt::Display + '_ {
358 display_fn(move |f| match self {
359 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
360 clean::GenericBound::TraitBound(ty, modifier) => {
361 let modifier_str = match modifier {
362 hir::TraitBoundModifier::None => "",
363 hir::TraitBoundModifier::Maybe => "?",
364 hir::TraitBoundModifier::MaybeConst => "?const",
367 write!(f, "{}{:#}", modifier_str, ty.print())
369 write!(f, "{}{}", modifier_str, ty.print())
376 impl clean::GenericArgs {
377 fn print(&self) -> impl fmt::Display + '_ {
378 display_fn(move |f| {
380 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
381 if !args.is_empty() || !bindings.is_empty() {
385 f.write_str("<")?;
387 let mut comma = false;
394 write!(f, "{:#}", arg.print())?;
396 write!(f, "{}", arg.print())?;
399 for binding in bindings {
405 write!(f, "{:#}", binding.print())?;
407 write!(f, "{}", binding.print())?;
413 f.write_str(">")?;
417 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
419 let mut comma = false;
426 write!(f, "{:#}", ty.print())?;
428 write!(f, "{}", ty.print())?;
432 if let Some(ref ty) = *output {
434 write!(f, " -> {:#}", ty.print())?;
436 write!(f, " -> {}", ty.print())?;
446 impl clean::PathSegment {
447 crate fn print(&self) -> impl fmt::Display + '_ {
448 display_fn(move |f| {
449 f.write_str(&self.name)?;
451 write!(f, "{:#}", self.args.print())
453 write!(f, "{}", self.args.print())
460 crate fn print(&self) -> impl fmt::Display + '_ {
461 display_fn(move |f| {
466 for (i, seg) in self.segments.iter().enumerate() {
471 write!(f, "{:#}", seg.print())?;
473 write!(f, "{}", seg.print())?;
481 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
483 if !did.is_local() && !cache.access_levels.is_public(did) {
487 let depth = CURRENT_DEPTH.with(|l| l.get());
488 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
489 Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
491 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
495 match cache.extern_locations[&did.krate] {
496 (.., render::Remote(ref s)) => s.to_string(),
497 (.., render::Local) => "../".repeat(depth),
498 (.., render::Unknown) => return None,
503 for component in &fqp[..fqp.len() - 1] {
504 url.push_str(component);
508 ItemType::Module => {
509 url.push_str(fqp.last().unwrap());
510 url.push_str("/index.html");
513 url.push_str(shortty.as_str());
515 url.push_str(fqp.last().unwrap());
516 url.push_str(".html");
519 Some((url, shortty, fqp.to_vec()))
522 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
523 /// rendering function with the necessary arguments for linking to a local path.
525 w: &mut fmt::Formatter<'_>,
531 let last = path.segments.last().unwrap();
534 for seg in &path.segments[..path.segments.len() - 1] {
535 write!(w, "{}::", seg.name)?;
539 write!(w, "{}{:#}", &last.name, last.args.print())?;
541 let path = if use_absolute {
542 if let Some((_, _, fqp)) = href(did) {
543 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
545 last.name.to_string()
548 anchor(did, &last.name).to_string()
550 write!(w, "{}{}", path, last.args.print())?;
556 f: &mut fmt::Formatter<'_>,
557 prim: clean::PrimitiveType,
561 let mut needs_termination = false;
563 match m.primitive_locations.get(&prim) {
564 Some(&def_id) if def_id.is_local() => {
565 let len = CURRENT_DEPTH.with(|s| s.get());
566 let len = if len == 0 { 0 } else { len - 1 };
569 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
573 needs_termination = true;
576 let loc = match m.extern_locations[&def_id.krate] {
577 (ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
578 (ref cname, _, render::Local) => {
579 let len = CURRENT_DEPTH.with(|s| s.get());
580 Some((cname, "../".repeat(len)))
582 (.., render::Unknown) => None,
584 if let Some((cname, root)) = loc {
587 "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
592 needs_termination = true;
598 write!(f, "{}", name)?;
599 if needs_termination {
605 /// Helper to render type parameters
606 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
607 display_fn(move |f| match *param_names {
608 Some(ref params) => {
609 for param in params {
611 fmt::Display::fmt(¶m.print(), f)?;
619 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
620 display_fn(move |f| {
621 if let Some((url, short_ty, fqp)) = href(did) {
624 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
632 write!(f, "{}", text)
637 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
639 clean::Generic(ref name) => f.write_str(name),
640 clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
641 if param_names.is_some() {
642 f.write_str("dyn ")?;
644 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
645 resolved_path(f, did, path, is_generic, use_absolute)?;
646 fmt::Display::fmt(&tybounds(param_names), f)
648 clean::Infer => write!(f, "_"),
649 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
650 clean::BareFunction(ref decl) => {
655 decl.unsafety.print_with_space(),
656 print_abi_with_space(decl.abi),
657 decl.print_generic_params(),
664 decl.unsafety.print_with_space(),
665 print_abi_with_space(decl.abi)
667 primitive_link(f, PrimitiveType::Fn, "fn")?;
668 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
671 clean::Tuple(ref typs) => {
673 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
675 primitive_link(f, PrimitiveType::Tuple, "(")?;
676 // Carry `f.alternate()` into this display w/o branching manually.
677 fmt::Display::fmt(&one.print(), f)?;
678 primitive_link(f, PrimitiveType::Tuple, ",)")
681 primitive_link(f, PrimitiveType::Tuple, "(")?;
682 for (i, item) in many.iter().enumerate() {
686 fmt::Display::fmt(&item.print(), f)?;
688 primitive_link(f, PrimitiveType::Tuple, ")")
692 clean::Slice(ref t) => {
693 primitive_link(f, PrimitiveType::Slice, "[")?;
694 fmt::Display::fmt(&t.print(), f)?;
695 primitive_link(f, PrimitiveType::Slice, "]")
697 clean::Array(ref t, ref n) => {
698 primitive_link(f, PrimitiveType::Array, "[")?;
699 fmt::Display::fmt(&t.print(), f)?;
701 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
703 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)))
706 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
707 clean::RawPointer(m, ref t) => {
709 hir::Mutability::Mut => "mut",
710 hir::Mutability::Not => "const",
713 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
717 clean::PrimitiveType::RawPointer,
718 &format!("*{} {:#}", m, t.print()),
723 clean::PrimitiveType::RawPointer,
724 &format!("*{} {}", m, t.print()),
729 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
730 fmt::Display::fmt(&t.print(), f)
734 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
736 Some(l) => format!("{} ", l.print()),
739 let m = mutability.print_with_space();
740 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
742 clean::Slice(ref bt) => {
743 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
745 clean::Generic(_) => {
749 PrimitiveType::Slice,
750 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()),
755 PrimitiveType::Slice,
756 &format!("{}{}{}[{}]", amp, lt, m, bt.print()),
763 PrimitiveType::Slice,
764 &format!("{}{}{}[", amp, lt, m),
767 write!(f, "{:#}", bt.print())?;
769 write!(f, "{}", bt.print())?;
771 primitive_link(f, PrimitiveType::Slice, "]")
775 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
776 write!(f, "{}{}{}(", amp, lt, m)?;
777 fmt_type(&ty, f, use_absolute)?;
780 clean::Generic(..) => {
781 primitive_link(f, PrimitiveType::Reference, &format!("{}{}{}", amp, lt, m))?;
782 fmt_type(&ty, f, use_absolute)
785 write!(f, "{}{}{}", amp, lt, m)?;
786 fmt_type(&ty, f, use_absolute)
790 clean::ImplTrait(ref bounds) => {
792 write!(f, "impl {:#}", print_generic_bounds(bounds))
794 write!(f, "impl {}", print_generic_bounds(bounds))
797 clean::QPath { ref name, ref self_type, ref trait_ } => {
798 let should_show_cast = match *trait_ {
799 box clean::ResolvedPath { ref path, .. } => {
800 !path.segments.is_empty() && !self_type.is_self_type()
805 if should_show_cast {
806 write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
808 write!(f, "{:#}::", self_type.print())?
811 if should_show_cast {
812 write!(f, "<{} as {}>::", self_type.print(), trait_.print())?
814 write!(f, "{}::", self_type.print())?
818 // It's pretty unsightly to look at `<A as B>::C` in output, and
819 // we've got hyperlinking on our side, so try to avoid longer
820 // notation as much as possible by making `C` a hyperlink to trait
821 // `B` to disambiguate.
823 // FIXME: this is still a lossy conversion and there should probably
824 // be a better way of representing this in general? Most of
825 // the ugliness comes from inlining across crates where
826 // everything comes in as a fully resolved QPath (hard to
828 box clean::ResolvedPath { did, ref param_names, .. } => {
830 Some((ref url, _, ref path)) if !f.alternate() => {
833 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
834 title=\"type {path}::{name}\">{name}</a>",
836 shortty = ItemType::AssocType,
838 path = path.join("::")
841 _ => write!(f, "{}", name)?,
844 // FIXME: `param_names` are not rendered, and this seems bad?
848 _ => write!(f, "{}", name),
855 crate fn print(&self) -> impl fmt::Display + '_ {
856 display_fn(move |f| fmt_type(self, f, false))
861 crate fn print(&self) -> impl fmt::Display + '_ {
862 self.print_inner(true, false)
865 fn print_inner(&self, link_trait: bool, use_absolute: bool) -> impl fmt::Display + '_ {
866 display_fn(move |f| {
868 write!(f, "impl{:#} ", self.generics.print())?;
870 write!(f, "impl{} ", self.generics.print())?;
873 if let Some(ref ty) = self.trait_ {
874 if self.polarity == Some(clean::ImplPolarity::Negative) {
879 fmt::Display::fmt(&ty.print(), f)?;
882 clean::ResolvedPath {
883 param_names: None, path, is_generic: false, ..
885 let last = path.segments.last().unwrap();
886 fmt::Display::fmt(&last.name, f)?;
887 fmt::Display::fmt(&last.args.print(), f)?;
895 if let Some(ref ty) = self.blanket_impl {
896 fmt_type(ty, f, use_absolute)?;
898 fmt_type(&self.for_, f, use_absolute)?;
902 &WhereClause { gens: &self.generics, indent: 0, end_newline: true },
910 // The difference from above is that trait is not hyperlinked.
911 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
912 f.from_display(i.print_inner(false, use_absolute))
915 impl clean::Arguments {
916 crate fn print(&self) -> impl fmt::Display + '_ {
917 display_fn(move |f| {
918 for (i, input) in self.values.iter().enumerate() {
919 if !input.name.is_empty() {
920 write!(f, "{}: ", input.name)?;
923 write!(f, "{:#}", input.type_.print())?;
925 write!(f, "{}", input.type_.print())?;
927 if i + 1 < self.values.len() {
936 impl clean::FnRetTy {
937 crate fn print(&self) -> impl fmt::Display + '_ {
938 display_fn(move |f| match self {
939 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
940 clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
941 clean::Return(ty) => write!(f, " -> {}", ty.print()),
942 clean::DefaultReturn => Ok(()),
947 impl clean::BareFunctionDecl {
948 fn print_generic_params(&self) -> impl fmt::Display + '_ {
949 comma_sep(self.generic_params.iter().map(|g| g.print()))
954 crate fn print(&self) -> impl fmt::Display + '_ {
955 display_fn(move |f| {
956 let ellipsis = if self.c_variadic { ", ..." } else { "" };
960 "({args:#}{ellipsis}){arrow:#}",
961 args = self.inputs.print(),
963 arrow = self.output.print()
968 "({args}{ellipsis}){arrow}",
969 args = self.inputs.print(),
971 arrow = self.output.print()
979 crate fn print(&self) -> impl fmt::Display + '_ {
980 display_fn(move |f| {
981 let &Function { decl, header_len, indent, asyncness } = self;
982 let amp = if f.alternate() { "&" } else { "&" };
983 let mut args = String::new();
984 let mut args_plain = String::new();
985 for (i, input) in decl.inputs.values.iter().enumerate() {
987 args.push_str("<br>");
990 if let Some(selfty) = input.to_self() {
992 clean::SelfValue => {
993 args.push_str("self");
994 args_plain.push_str("self");
996 clean::SelfBorrowed(Some(ref lt), mtbl) => {
997 args.push_str(&format!(
1001 mtbl.print_with_space()
1003 args_plain.push_str(&format!(
1006 mtbl.print_with_space()
1009 clean::SelfBorrowed(None, mtbl) => {
1010 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1011 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1013 clean::SelfExplicit(ref typ) => {
1015 args.push_str(&format!("self: {:#}", typ.print()));
1017 args.push_str(&format!("self: {}", typ.print()));
1019 args_plain.push_str(&format!("self: {:#}", typ.print()));
1024 args.push_str(" <br>");
1025 args_plain.push_str(" ");
1027 if !input.name.is_empty() {
1028 args.push_str(&format!("{}: ", input.name));
1029 args_plain.push_str(&format!("{}: ", input.name));
1033 args.push_str(&format!("{:#}", input.type_.print()));
1035 args.push_str(&input.type_.print().to_string());
1037 args_plain.push_str(&format!("{:#}", input.type_.print()));
1039 if i + 1 < decl.inputs.values.len() {
1041 args_plain.push(',');
1045 let mut args_plain = format!("({})", args_plain);
1047 if decl.c_variadic {
1048 args.push_str(",<br> ...");
1049 args_plain.push_str(", ...");
1052 let output = if let hir::IsAsync::Async = asyncness {
1053 Cow::Owned(decl.sugared_async_return_type())
1055 Cow::Borrowed(&decl.output)
1058 let arrow_plain = format!("{:#}", &output.print());
1059 let arrow = if f.alternate() {
1060 format!("{:#}", &output.print())
1062 output.print().to_string()
1065 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1066 let output = if declaration_len > 80 {
1067 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1068 let close_pad = format!("<br>{}", " ".repeat(indent));
1070 "({args}{close}){arrow}",
1071 args = args.replace("<br>", &full_pad),
1076 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1080 write!(f, "{}", output.replace("<br>", "\n"))
1082 write!(f, "{}", output)
1088 impl clean::Visibility {
1089 crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1090 display_fn(move |f| match *self {
1091 clean::Public => f.write_str("pub "),
1092 clean::Inherited => Ok(()),
1093 clean::Visibility::Crate => write!(f, "pub(crate) "),
1094 clean::Visibility::Restricted(did, ref path) => {
1095 f.write_str("pub(")?;
1096 if path.segments.len() != 1
1097 || (path.segments[0].name != "self" && path.segments[0].name != "super")
1099 f.write_str("in ")?;
1101 resolved_path(f, did, path, true, false)?;
1108 crate trait PrintWithSpace {
1109 fn print_with_space(&self) -> &str;
1112 impl PrintWithSpace for hir::Unsafety {
1113 fn print_with_space(&self) -> &str {
1115 hir::Unsafety::Unsafe => "unsafe ",
1116 hir::Unsafety::Normal => "",
1121 impl PrintWithSpace for hir::Constness {
1122 fn print_with_space(&self) -> &str {
1124 hir::Constness::Const => "const ",
1125 hir::Constness::NotConst => "",
1130 impl PrintWithSpace for hir::IsAsync {
1131 fn print_with_space(&self) -> &str {
1133 hir::IsAsync::Async => "async ",
1134 hir::IsAsync::NotAsync => "",
1139 impl PrintWithSpace for hir::Mutability {
1140 fn print_with_space(&self) -> &str {
1142 hir::Mutability::Not => "",
1143 hir::Mutability::Mut => "mut ",
1148 impl clean::Import {
1149 crate fn print(&self) -> impl fmt::Display + '_ {
1150 display_fn(move |f| match *self {
1151 clean::Import::Simple(ref name, ref src) => {
1152 if *name == src.path.last_name() {
1153 write!(f, "use {};", src.print())
1155 write!(f, "use {} as {};", src.print(), *name)
1158 clean::Import::Glob(ref src) => {
1159 if src.path.segments.is_empty() {
1162 write!(f, "use {}::*;", src.print())
1169 impl clean::ImportSource {
1170 crate fn print(&self) -> impl fmt::Display + '_ {
1171 display_fn(move |f| match self.did {
1172 Some(did) => resolved_path(f, did, &self.path, true, false),
1174 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1175 write!(f, "{}::", seg.name)?;
1177 let name = self.path.last_name();
1178 if let hir::def::Res::PrimTy(p) = self.path.res {
1179 primitive_link(f, PrimitiveType::from(p), name)?;
1181 write!(f, "{}", name)?;
1189 impl clean::TypeBinding {
1190 crate fn print(&self) -> impl fmt::Display + '_ {
1191 display_fn(move |f| {
1192 f.write_str(&self.name)?;
1194 clean::TypeBindingKind::Equality { ref ty } => {
1196 write!(f, " = {:#}", ty.print())?;
1198 write!(f, " = {}", ty.print())?;
1201 clean::TypeBindingKind::Constraint { ref bounds } => {
1202 if !bounds.is_empty() {
1204 write!(f, ": {:#}", print_generic_bounds(bounds))?;
1206 write!(f, ": {}", print_generic_bounds(bounds))?;
1216 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1217 display_fn(move |f| {
1218 let quot = if f.alternate() { "\"" } else { """ };
1220 Abi::Rust => Ok(()),
1221 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1226 crate fn print_default_space<'a>(v: bool) -> &'a str {
1227 if v { "default " } else { "" }
1230 impl clean::GenericArg {
1231 crate fn print(&self) -> impl fmt::Display + '_ {
1232 display_fn(move |f| match self {
1233 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1234 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1235 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1240 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1241 WithFormatter(Cell::new(Some(f)))
1244 struct WithFormatter<F>(Cell<Option<F>>);
1246 impl<F> fmt::Display for WithFormatter<F>
1248 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 (self.0.take()).unwrap()(f)