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 into_inner(self) -> String {
70 // Intended for consumption by write! and writeln! (std::fmt) but without
71 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
73 crate fn write_str(&mut self, s: &str) {
74 self.buffer.push_str(s);
77 // Intended for consumption by write! and writeln! (std::fmt) but without
78 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
80 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
82 self.buffer.write_fmt(v).unwrap();
85 crate fn to_display<T: Print>(mut self, t: T) -> String {
90 crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
92 write!(self, "{}", t);
94 write!(self, "{:#}", t);
98 crate fn is_for_html(&self) -> bool {
103 /// Wrapper struct for properly emitting a function or method declaration.
104 pub struct Function<'a> {
105 /// The declaration to emit.
106 pub decl: &'a clean::FnDecl,
107 /// The length of the function header and name. In other words, the number of characters in the
108 /// function declaration up to but not including the parentheses.
110 /// Used to determine line-wrapping.
111 pub header_len: usize,
112 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
114 /// Whether the function is async or not.
115 pub asyncness: hir::IsAsync,
118 /// Wrapper struct for emitting a where-clause from Generics.
119 pub struct WhereClause<'a> {
120 /// The Generics from which to emit a where-clause.
121 pub gens: &'a clean::Generics,
122 /// The number of spaces to indent each line with.
124 /// Whether the where-clause needs to add a comma and newline after the last bound.
125 pub end_newline: bool,
128 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
129 display_fn(move |f| {
130 for (i, item) in items.enumerate() {
134 fmt::Display::fmt(&item, f)?;
140 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
141 display_fn(move |f| {
142 let mut bounds_dup = FxHashSet::default();
145 bounds.iter().filter(|b| bounds_dup.insert(b.print().to_string())).enumerate()
150 fmt::Display::fmt(&bound.print(), f)?;
156 impl clean::GenericParamDef {
157 crate fn print(&self) -> impl fmt::Display + '_ {
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)?;
163 if !bounds.is_empty() {
165 write!(f, ": {:#}", print_generic_bounds(bounds))?;
167 write!(f, ": {}", print_generic_bounds(bounds))?;
171 if let Some(ref ty) = default {
173 write!(f, " = {:#}", ty.print())?;
175 write!(f, " = {}", ty.print())?;
181 clean::GenericParamDefKind::Const { ref ty, .. } => {
182 f.write_str("const ")?;
183 f.write_str(&self.name)?;
186 write!(f, ": {:#}", ty.print())
188 write!(f, ": {}", ty.print())
195 impl clean::Generics {
196 crate fn print(&self) -> impl fmt::Display + '_ {
197 display_fn(move |f| {
199 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
200 if real_params.is_empty() {
204 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
206 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print())))
212 impl<'a> fmt::Display for WhereClause<'a> {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 let &WhereClause { gens, indent, end_newline } = self;
215 if gens.where_predicates.is_empty() {
218 let mut clause = String::new();
220 clause.push_str(" where");
223 clause.push_str(" <span class=\"where fmt-newline\">where");
225 clause.push_str(" <span class=\"where\">where");
228 for (i, pred) in gens.where_predicates.iter().enumerate() {
232 clause.push_str("<br>");
236 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
239 clause.push_str(&format!(
242 print_generic_bounds(bounds)
245 clause.push_str(&format!(
248 print_generic_bounds(bounds)
252 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
253 clause.push_str(&format!(
258 .map(|b| b.print().to_string())
263 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
265 clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
267 clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
272 if i < gens.where_predicates.len() - 1 || end_newline {
278 // add a space so stripping <br> tags and breaking spaces still renders properly
282 clause.push_str(" ");
287 clause.push_str("</span>");
288 let padding = " ".repeat(indent + 4);
289 clause = clause.replace("<br>", &format!("<br>{}", padding));
290 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
292 clause.insert_str(0, "<br>");
295 write!(f, "{}", clause)
299 impl clean::Lifetime {
300 crate fn print(&self) -> &str {
305 impl clean::Constant {
306 crate fn print(&self) -> impl fmt::Display + '_ {
307 display_fn(move |f| {
309 f.write_str(&self.expr)
311 write!(f, "{}", Escape(&self.expr))
317 impl clean::PolyTrait {
318 fn print(&self) -> impl fmt::Display + '_ {
319 display_fn(move |f| {
320 if !self.generic_params.is_empty() {
325 comma_sep(self.generic_params.iter().map(|g| g.print()))
331 comma_sep(self.generic_params.iter().map(|g| g.print()))
336 write!(f, "{:#}", self.trait_.print())
338 write!(f, "{}", self.trait_.print())
344 impl clean::GenericBound {
345 crate fn print(&self) -> impl fmt::Display + '_ {
346 display_fn(move |f| match self {
347 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
348 clean::GenericBound::TraitBound(ty, modifier) => {
349 let modifier_str = match modifier {
350 hir::TraitBoundModifier::None => "",
351 hir::TraitBoundModifier::Maybe => "?",
352 hir::TraitBoundModifier::MaybeConst => "?const",
355 write!(f, "{}{:#}", modifier_str, ty.print())
357 write!(f, "{}{}", modifier_str, ty.print())
364 impl clean::GenericArgs {
365 fn print(&self) -> impl fmt::Display + '_ {
366 display_fn(move |f| {
368 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
369 if !args.is_empty() || !bindings.is_empty() {
373 f.write_str("<")?;
375 let mut comma = false;
382 write!(f, "{:#}", arg.print())?;
384 write!(f, "{}", arg.print())?;
387 for binding in bindings {
393 write!(f, "{:#}", binding.print())?;
395 write!(f, "{}", binding.print())?;
401 f.write_str(">")?;
405 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
407 let mut comma = false;
414 write!(f, "{:#}", ty.print())?;
416 write!(f, "{}", ty.print())?;
420 if let Some(ref ty) = *output {
422 write!(f, " -> {:#}", ty.print())?;
424 write!(f, " -> {}", ty.print())?;
434 impl clean::PathSegment {
435 crate fn print(&self) -> impl fmt::Display + '_ {
436 display_fn(move |f| {
437 f.write_str(&self.name)?;
439 write!(f, "{:#}", self.args.print())
441 write!(f, "{}", self.args.print())
448 crate fn print(&self) -> impl fmt::Display + '_ {
449 display_fn(move |f| {
454 for (i, seg) in self.segments.iter().enumerate() {
459 write!(f, "{:#}", seg.print())?;
461 write!(f, "{}", seg.print())?;
469 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
471 if !did.is_local() && !cache.access_levels.is_public(did) {
475 let depth = CURRENT_DEPTH.with(|l| l.get());
476 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
477 Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
479 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
483 match cache.extern_locations[&did.krate] {
484 (.., render::Remote(ref s)) => s.to_string(),
485 (.., render::Local) => "../".repeat(depth),
486 (.., render::Unknown) => return None,
491 for component in &fqp[..fqp.len() - 1] {
492 url.push_str(component);
496 ItemType::Module => {
497 url.push_str(fqp.last().unwrap());
498 url.push_str("/index.html");
501 url.push_str(shortty.as_str());
503 url.push_str(fqp.last().unwrap());
504 url.push_str(".html");
507 Some((url, shortty, fqp.to_vec()))
510 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
511 /// rendering function with the necessary arguments for linking to a local path.
513 w: &mut fmt::Formatter<'_>,
519 let last = path.segments.last().unwrap();
522 for seg in &path.segments[..path.segments.len() - 1] {
523 write!(w, "{}::", seg.name)?;
527 write!(w, "{}{:#}", &last.name, last.args.print())?;
529 let path = if use_absolute {
530 if let Some((_, _, fqp)) = href(did) {
531 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
533 last.name.to_string()
536 anchor(did, &last.name).to_string()
538 write!(w, "{}{}", path, last.args.print())?;
544 f: &mut fmt::Formatter<'_>,
545 prim: clean::PrimitiveType,
549 let mut needs_termination = false;
551 match m.primitive_locations.get(&prim) {
552 Some(&def_id) if def_id.is_local() => {
553 let len = CURRENT_DEPTH.with(|s| s.get());
554 let len = if len == 0 { 0 } else { len - 1 };
557 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
561 needs_termination = true;
564 let loc = match m.extern_locations[&def_id.krate] {
565 (ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
566 (ref cname, _, render::Local) => {
567 let len = CURRENT_DEPTH.with(|s| s.get());
568 Some((cname, "../".repeat(len)))
570 (.., render::Unknown) => None,
572 if let Some((cname, root)) = loc {
575 "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
580 needs_termination = true;
586 write!(f, "{}", name)?;
587 if needs_termination {
593 /// Helper to render type parameters
594 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
595 display_fn(move |f| match *param_names {
596 Some(ref params) => {
597 for param in params {
599 fmt::Display::fmt(¶m.print(), f)?;
607 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
608 display_fn(move |f| {
609 if let Some((url, short_ty, fqp)) = href(did) {
612 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
620 write!(f, "{}", text)
625 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
627 clean::Generic(ref name) => f.write_str(name),
628 clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
629 if param_names.is_some() {
630 f.write_str("dyn ")?;
632 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
633 resolved_path(f, did, path, is_generic, use_absolute)?;
634 fmt::Display::fmt(&tybounds(param_names), f)
636 clean::Infer => write!(f, "_"),
637 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
638 clean::BareFunction(ref decl) => {
643 decl.unsafety.print_with_space(),
644 print_abi_with_space(decl.abi),
645 decl.print_generic_params(),
652 decl.unsafety.print_with_space(),
653 print_abi_with_space(decl.abi)
655 primitive_link(f, PrimitiveType::Fn, "fn")?;
656 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
659 clean::Tuple(ref typs) => {
661 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
663 primitive_link(f, PrimitiveType::Tuple, "(")?;
664 // Carry `f.alternate()` into this display w/o branching manually.
665 fmt::Display::fmt(&one.print(), f)?;
666 primitive_link(f, PrimitiveType::Tuple, ",)")
669 primitive_link(f, PrimitiveType::Tuple, "(")?;
670 for (i, item) in many.iter().enumerate() {
674 fmt::Display::fmt(&item.print(), f)?;
676 primitive_link(f, PrimitiveType::Tuple, ")")
680 clean::Slice(ref t) => {
681 primitive_link(f, PrimitiveType::Slice, "[")?;
682 fmt::Display::fmt(&t.print(), f)?;
683 primitive_link(f, PrimitiveType::Slice, "]")
685 clean::Array(ref t, ref n) => {
686 primitive_link(f, PrimitiveType::Array, "[")?;
687 fmt::Display::fmt(&t.print(), f)?;
689 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
691 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)))
694 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
695 clean::RawPointer(m, ref t) => {
697 hir::Mutability::Mut => "mut",
698 hir::Mutability::Not => "const",
701 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
705 clean::PrimitiveType::RawPointer,
706 &format!("*{} {:#}", m, t.print()),
711 clean::PrimitiveType::RawPointer,
712 &format!("*{} {}", m, t.print()),
717 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
718 fmt::Display::fmt(&t.print(), f)
722 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
724 Some(l) => format!("{} ", l.print()),
727 let m = mutability.print_with_space();
728 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
730 clean::Slice(ref bt) => {
731 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
733 clean::Generic(_) => {
737 PrimitiveType::Slice,
738 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()),
743 PrimitiveType::Slice,
744 &format!("{}{}{}[{}]", amp, lt, m, bt.print()),
751 PrimitiveType::Slice,
752 &format!("{}{}{}[", amp, lt, m),
755 write!(f, "{:#}", bt.print())?;
757 write!(f, "{}", bt.print())?;
759 primitive_link(f, PrimitiveType::Slice, "]")
763 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
764 write!(f, "{}{}{}(", amp, lt, m)?;
765 fmt_type(&ty, f, use_absolute)?;
768 clean::Generic(..) => {
769 primitive_link(f, PrimitiveType::Reference, &format!("{}{}{}", amp, lt, m))?;
770 fmt_type(&ty, f, use_absolute)
773 write!(f, "{}{}{}", amp, lt, m)?;
774 fmt_type(&ty, f, use_absolute)
778 clean::ImplTrait(ref bounds) => {
780 write!(f, "impl {:#}", print_generic_bounds(bounds))
782 write!(f, "impl {}", print_generic_bounds(bounds))
785 clean::QPath { ref name, ref self_type, ref trait_ } => {
786 let should_show_cast = match *trait_ {
787 box clean::ResolvedPath { ref path, .. } => {
788 !path.segments.is_empty() && !self_type.is_self_type()
793 if should_show_cast {
794 write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
796 write!(f, "{:#}::", self_type.print())?
799 if should_show_cast {
800 write!(f, "<{} as {}>::", self_type.print(), trait_.print())?
802 write!(f, "{}::", self_type.print())?
806 // It's pretty unsightly to look at `<A as B>::C` in output, and
807 // we've got hyperlinking on our side, so try to avoid longer
808 // notation as much as possible by making `C` a hyperlink to trait
809 // `B` to disambiguate.
811 // FIXME: this is still a lossy conversion and there should probably
812 // be a better way of representing this in general? Most of
813 // the ugliness comes from inlining across crates where
814 // everything comes in as a fully resolved QPath (hard to
816 box clean::ResolvedPath { did, ref param_names, .. } => {
818 Some((ref url, _, ref path)) if !f.alternate() => {
821 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
822 title=\"type {path}::{name}\">{name}</a>",
824 shortty = ItemType::AssocType,
826 path = path.join("::")
829 _ => write!(f, "{}", name)?,
832 // FIXME: `param_names` are not rendered, and this seems bad?
836 _ => write!(f, "{}", name),
843 crate fn print(&self) -> impl fmt::Display + '_ {
844 display_fn(move |f| fmt_type(self, f, false))
849 crate fn print(&self) -> impl fmt::Display + '_ {
850 self.print_inner(true, false)
853 fn print_inner(&self, link_trait: bool, use_absolute: bool) -> impl fmt::Display + '_ {
854 display_fn(move |f| {
856 write!(f, "impl{:#} ", self.generics.print())?;
858 write!(f, "impl{} ", self.generics.print())?;
861 if let Some(ref ty) = self.trait_ {
862 if self.polarity == Some(clean::ImplPolarity::Negative) {
867 fmt::Display::fmt(&ty.print(), f)?;
870 clean::ResolvedPath {
871 param_names: None, path, is_generic: false, ..
873 let last = path.segments.last().unwrap();
874 fmt::Display::fmt(&last.name, f)?;
875 fmt::Display::fmt(&last.args.print(), f)?;
883 if let Some(ref ty) = self.blanket_impl {
884 fmt_type(ty, f, use_absolute)?;
886 fmt_type(&self.for_, f, use_absolute)?;
890 &WhereClause { gens: &self.generics, indent: 0, end_newline: true },
898 // The difference from above is that trait is not hyperlinked.
899 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
900 f.from_display(i.print_inner(false, use_absolute))
903 impl clean::Arguments {
904 crate fn print(&self) -> impl fmt::Display + '_ {
905 display_fn(move |f| {
906 for (i, input) in self.values.iter().enumerate() {
907 if !input.name.is_empty() {
908 write!(f, "{}: ", input.name)?;
911 write!(f, "{:#}", input.type_.print())?;
913 write!(f, "{}", input.type_.print())?;
915 if i + 1 < self.values.len() {
924 impl clean::FnRetTy {
925 crate fn print(&self) -> impl fmt::Display + '_ {
926 display_fn(move |f| match self {
927 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
928 clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
929 clean::Return(ty) => write!(f, " -> {}", ty.print()),
930 clean::DefaultReturn => Ok(()),
935 impl clean::BareFunctionDecl {
936 fn print_generic_params(&self) -> impl fmt::Display + '_ {
937 comma_sep(self.generic_params.iter().map(|g| g.print()))
942 crate fn print(&self) -> impl fmt::Display + '_ {
943 display_fn(move |f| {
944 let ellipsis = if self.c_variadic { ", ..." } else { "" };
948 "({args:#}{ellipsis}){arrow:#}",
949 args = self.inputs.print(),
951 arrow = self.output.print()
956 "({args}{ellipsis}){arrow}",
957 args = self.inputs.print(),
959 arrow = self.output.print()
967 crate fn print(&self) -> impl fmt::Display + '_ {
968 display_fn(move |f| {
969 let &Function { decl, header_len, indent, asyncness } = self;
970 let amp = if f.alternate() { "&" } else { "&" };
971 let mut args = String::new();
972 let mut args_plain = String::new();
973 for (i, input) in decl.inputs.values.iter().enumerate() {
975 args.push_str("<br>");
978 if let Some(selfty) = input.to_self() {
980 clean::SelfValue => {
981 args.push_str("self");
982 args_plain.push_str("self");
984 clean::SelfBorrowed(Some(ref lt), mtbl) => {
985 args.push_str(&format!(
989 mtbl.print_with_space()
991 args_plain.push_str(&format!(
994 mtbl.print_with_space()
997 clean::SelfBorrowed(None, mtbl) => {
998 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
999 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1001 clean::SelfExplicit(ref typ) => {
1003 args.push_str(&format!("self: {:#}", typ.print()));
1005 args.push_str(&format!("self: {}", typ.print()));
1007 args_plain.push_str(&format!("self: {:#}", typ.print()));
1012 args.push_str(" <br>");
1013 args_plain.push_str(" ");
1015 if !input.name.is_empty() {
1016 args.push_str(&format!("{}: ", input.name));
1017 args_plain.push_str(&format!("{}: ", input.name));
1021 args.push_str(&format!("{:#}", input.type_.print()));
1023 args.push_str(&input.type_.print().to_string());
1025 args_plain.push_str(&format!("{:#}", input.type_.print()));
1027 if i + 1 < decl.inputs.values.len() {
1029 args_plain.push(',');
1033 let mut args_plain = format!("({})", args_plain);
1035 if decl.c_variadic {
1036 args.push_str(",<br> ...");
1037 args_plain.push_str(", ...");
1040 let output = if let hir::IsAsync::Async = asyncness {
1041 Cow::Owned(decl.sugared_async_return_type())
1043 Cow::Borrowed(&decl.output)
1046 let arrow_plain = format!("{:#}", &output.print());
1047 let arrow = if f.alternate() {
1048 format!("{:#}", &output.print())
1050 output.print().to_string()
1053 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1054 let output = if declaration_len > 80 {
1055 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1056 let close_pad = format!("<br>{}", " ".repeat(indent));
1058 "({args}{close}){arrow}",
1059 args = args.replace("<br>", &full_pad),
1064 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1068 write!(f, "{}", output.replace("<br>", "\n"))
1070 write!(f, "{}", output)
1076 impl clean::Visibility {
1077 crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1078 display_fn(move |f| match *self {
1079 clean::Public => f.write_str("pub "),
1080 clean::Inherited => Ok(()),
1081 clean::Visibility::Crate => write!(f, "pub(crate) "),
1082 clean::Visibility::Restricted(did, ref path) => {
1083 f.write_str("pub(")?;
1084 if path.segments.len() != 1
1085 || (path.segments[0].name != "self" && path.segments[0].name != "super")
1087 f.write_str("in ")?;
1089 resolved_path(f, did, path, true, false)?;
1096 crate trait PrintWithSpace {
1097 fn print_with_space(&self) -> &str;
1100 impl PrintWithSpace for hir::Unsafety {
1101 fn print_with_space(&self) -> &str {
1103 hir::Unsafety::Unsafe => "unsafe ",
1104 hir::Unsafety::Normal => "",
1109 impl PrintWithSpace for hir::Constness {
1110 fn print_with_space(&self) -> &str {
1112 hir::Constness::Const => "const ",
1113 hir::Constness::NotConst => "",
1118 impl PrintWithSpace for hir::IsAsync {
1119 fn print_with_space(&self) -> &str {
1121 hir::IsAsync::Async => "async ",
1122 hir::IsAsync::NotAsync => "",
1127 impl PrintWithSpace for hir::Mutability {
1128 fn print_with_space(&self) -> &str {
1130 hir::Mutability::Not => "",
1131 hir::Mutability::Mut => "mut ",
1136 impl clean::Import {
1137 crate fn print(&self) -> impl fmt::Display + '_ {
1138 display_fn(move |f| match *self {
1139 clean::Import::Simple(ref name, ref src) => {
1140 if *name == src.path.last_name() {
1141 write!(f, "use {};", src.print())
1143 write!(f, "use {} as {};", src.print(), *name)
1146 clean::Import::Glob(ref src) => {
1147 if src.path.segments.is_empty() {
1150 write!(f, "use {}::*;", src.print())
1157 impl clean::ImportSource {
1158 crate fn print(&self) -> impl fmt::Display + '_ {
1159 display_fn(move |f| match self.did {
1160 Some(did) => resolved_path(f, did, &self.path, true, false),
1162 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1163 write!(f, "{}::", seg.name)?;
1165 let name = self.path.last_name();
1166 if let hir::def::Res::PrimTy(p) = self.path.res {
1167 primitive_link(f, PrimitiveType::from(p), name)?;
1169 write!(f, "{}", name)?;
1177 impl clean::TypeBinding {
1178 crate fn print(&self) -> impl fmt::Display + '_ {
1179 display_fn(move |f| {
1180 f.write_str(&self.name)?;
1182 clean::TypeBindingKind::Equality { ref ty } => {
1184 write!(f, " = {:#}", ty.print())?;
1186 write!(f, " = {}", ty.print())?;
1189 clean::TypeBindingKind::Constraint { ref bounds } => {
1190 if !bounds.is_empty() {
1192 write!(f, ": {:#}", print_generic_bounds(bounds))?;
1194 write!(f, ": {}", print_generic_bounds(bounds))?;
1204 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1205 display_fn(move |f| {
1206 let quot = if f.alternate() { "\"" } else { """ };
1208 Abi::Rust => Ok(()),
1209 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1214 crate fn print_default_space<'a>(v: bool) -> &'a str {
1215 if v { "default " } else { "" }
1218 impl clean::GenericArg {
1219 crate fn print(&self) -> impl fmt::Display + '_ {
1220 display_fn(move |f| match self {
1221 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1222 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1223 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1228 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1229 WithFormatter(Cell::new(Some(f)))
1232 struct WithFormatter<F>(Cell<Option<F>>);
1234 impl<F> fmt::Display for WithFormatter<F>
1236 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239 (self.0.take()).unwrap()(f)