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.
13 use rustc::hir::def_id::DefId;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_target::spec::abi::Abi;
17 use crate::clean::{self, PrimitiveType};
18 use crate::html::item_type::ItemType;
19 use crate::html::render::{self, cache, CURRENT_DEPTH};
22 fn print(self, buffer: &mut Buffer);
27 F: FnOnce(&mut Buffer),
29 fn print(self, buffer: &mut Buffer) {
34 impl Print for String {
35 fn print(self, buffer: &mut Buffer) {
36 buffer.write_str(&self);
40 impl Print for &'_ str {
41 fn print(self, buffer: &mut Buffer) {
42 buffer.write_str(self);
46 #[derive(Debug, Clone)]
53 crate fn empty_from(v: &Buffer) -> Buffer {
54 Buffer { for_html: v.for_html, buffer: String::new() }
57 crate fn html() -> Buffer {
58 Buffer { for_html: true, buffer: String::new() }
61 crate fn new() -> Buffer {
62 Buffer { for_html: false, buffer: String::new() }
65 crate fn is_empty(&self) -> bool {
66 self.buffer.is_empty()
69 crate fn into_inner(self) -> String {
73 crate fn insert_str(&mut self, idx: usize, s: &str) {
74 self.buffer.insert_str(idx, s);
77 crate fn push_str(&mut self, s: &str) {
78 self.buffer.push_str(s);
81 // Intended for consumption by write! and writeln! (std::fmt) but without
82 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
84 crate fn write_str(&mut self, s: &str) {
85 self.buffer.push_str(s);
88 // Intended for consumption by write! and writeln! (std::fmt) but without
89 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
91 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
93 self.buffer.write_fmt(v).unwrap();
96 crate fn to_display<T: Print>(mut self, t: T) -> String {
101 crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
103 write!(self, "{}", t);
105 write!(self, "{:#}", t);
109 crate fn is_for_html(&self) -> bool {
114 /// Wrapper struct for properly emitting a function or method declaration.
115 pub struct Function<'a> {
116 /// The declaration to emit.
117 pub decl: &'a clean::FnDecl,
118 /// The length of the function header and name. In other words, the number of characters in the
119 /// function declaration up to but not including the parentheses.
121 /// Used to determine line-wrapping.
122 pub header_len: usize,
123 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
125 /// Whether the function is async or not.
126 pub asyncness: hir::IsAsync,
129 /// Wrapper struct for emitting a where-clause from Generics.
130 pub struct WhereClause<'a> {
131 /// The Generics from which to emit a where-clause.
132 pub gens: &'a clean::Generics,
133 /// The number of spaces to indent each line with.
135 /// Whether the where-clause needs to add a comma and newline after the last bound.
136 pub end_newline: bool,
139 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
140 display_fn(move |f| {
141 for (i, item) in items.enumerate() {
145 fmt::Display::fmt(&item, f)?;
151 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
152 display_fn(move |f| {
153 let mut bounds_dup = FxHashSet::default();
156 bounds.iter().filter(|b| bounds_dup.insert(b.print().to_string())).enumerate()
161 fmt::Display::fmt(&bound.print(), f)?;
167 impl clean::GenericParamDef {
168 crate fn print(&self) -> impl fmt::Display + '_ {
169 display_fn(move |f| match self.kind {
170 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
171 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
172 f.write_str(&self.name)?;
174 if !bounds.is_empty() {
176 write!(f, ": {:#}", print_generic_bounds(bounds))?;
178 write!(f, ": {}", print_generic_bounds(bounds))?;
182 if let Some(ref ty) = default {
184 write!(f, " = {:#}", ty.print())?;
186 write!(f, " = {}", ty.print())?;
192 clean::GenericParamDefKind::Const { ref ty, .. } => {
193 f.write_str("const ")?;
194 f.write_str(&self.name)?;
197 write!(f, ": {:#}", ty.print())
199 write!(f, ": {}", ty.print())
206 impl clean::Generics {
207 crate fn print(&self) -> impl fmt::Display + '_ {
208 display_fn(move |f| {
210 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
211 if real_params.is_empty() {
215 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
217 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print())))
223 impl<'a> fmt::Display for WhereClause<'a> {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 let &WhereClause { gens, indent, end_newline } = self;
226 if gens.where_predicates.is_empty() {
229 let mut clause = String::new();
231 clause.push_str(" where");
234 clause.push_str(" <span class=\"where fmt-newline\">where");
236 clause.push_str(" <span class=\"where\">where");
239 for (i, pred) in gens.where_predicates.iter().enumerate() {
243 clause.push_str("<br>");
247 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
250 clause.push_str(&format!(
253 print_generic_bounds(bounds)
256 clause.push_str(&format!(
259 print_generic_bounds(bounds)
263 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
264 clause.push_str(&format!(
269 .map(|b| b.print().to_string())
274 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
276 clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
278 clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
283 if i < gens.where_predicates.len() - 1 || end_newline {
289 // add a space so stripping <br> tags and breaking spaces still renders properly
293 clause.push_str(" ");
298 clause.push_str("</span>");
299 let padding = " ".repeat(indent + 4);
300 clause = clause.replace("<br>", &format!("<br>{}", padding));
301 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
303 clause.insert_str(0, "<br>");
306 write!(f, "{}", clause)
310 impl clean::Lifetime {
311 crate fn print(&self) -> &str {
316 impl clean::Constant {
317 crate fn print(&self) -> &str {
322 impl clean::PolyTrait {
323 fn print(&self) -> impl fmt::Display + '_ {
324 display_fn(move |f| {
325 if !self.generic_params.is_empty() {
330 comma_sep(self.generic_params.iter().map(|g| g.print()))
336 comma_sep(self.generic_params.iter().map(|g| g.print()))
341 write!(f, "{:#}", self.trait_.print())
343 write!(f, "{}", self.trait_.print())
349 impl clean::GenericBound {
350 crate fn print(&self) -> impl fmt::Display + '_ {
351 display_fn(move |f| match self {
352 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
353 clean::GenericBound::TraitBound(ty, modifier) => {
354 let modifier_str = match modifier {
355 hir::TraitBoundModifier::None => "",
356 hir::TraitBoundModifier::Maybe => "?",
359 write!(f, "{}{:#}", modifier_str, ty.print())
361 write!(f, "{}{}", modifier_str, ty.print())
368 impl clean::GenericArgs {
369 fn print(&self) -> impl fmt::Display + '_ {
370 display_fn(move |f| {
372 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
373 if !args.is_empty() || !bindings.is_empty() {
377 f.write_str("<")?;
379 let mut comma = false;
386 write!(f, "{:#}", arg.print())?;
388 write!(f, "{}", arg.print())?;
391 for binding in bindings {
397 write!(f, "{:#}", binding.print())?;
399 write!(f, "{}", binding.print())?;
405 f.write_str(">")?;
409 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
411 let mut comma = false;
418 write!(f, "{:#}", ty.print())?;
420 write!(f, "{}", ty.print())?;
424 if let Some(ref ty) = *output {
426 write!(f, " -> {:#}", ty.print())?;
428 write!(f, " -> {}", ty.print())?;
438 impl clean::PathSegment {
439 crate fn print(&self) -> impl fmt::Display + '_ {
440 display_fn(move |f| {
441 f.write_str(&self.name)?;
443 write!(f, "{:#}", self.args.print())
445 write!(f, "{}", self.args.print())
452 crate fn print(&self) -> impl fmt::Display + '_ {
453 display_fn(move |f| {
458 for (i, seg) in self.segments.iter().enumerate() {
463 write!(f, "{:#}", seg.print())?;
465 write!(f, "{}", seg.print())?;
473 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
475 if !did.is_local() && !cache.access_levels.is_public(did) {
479 let depth = CURRENT_DEPTH.with(|l| l.get());
480 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
481 Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
483 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
487 match cache.extern_locations[&did.krate] {
488 (.., render::Remote(ref s)) => s.to_string(),
489 (.., render::Local) => "../".repeat(depth),
490 (.., render::Unknown) => return None,
495 for component in &fqp[..fqp.len() - 1] {
496 url.push_str(component);
500 ItemType::Module => {
501 url.push_str(fqp.last().unwrap());
502 url.push_str("/index.html");
505 url.push_str(shortty.as_str());
507 url.push_str(fqp.last().unwrap());
508 url.push_str(".html");
511 Some((url, shortty, fqp.to_vec()))
514 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
515 /// rendering function with the necessary arguments for linking to a local path.
517 w: &mut fmt::Formatter<'_>,
523 let last = path.segments.last().unwrap();
526 for seg in &path.segments[..path.segments.len() - 1] {
527 write!(w, "{}::", seg.name)?;
531 write!(w, "{}{:#}", &last.name, last.args.print())?;
533 let path = if use_absolute {
534 if let Some((_, _, fqp)) = href(did) {
535 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
537 last.name.to_string()
540 anchor(did, &last.name).to_string()
542 write!(w, "{}{}", path, last.args.print())?;
548 f: &mut fmt::Formatter<'_>,
549 prim: clean::PrimitiveType,
553 let mut needs_termination = false;
555 match m.primitive_locations.get(&prim) {
556 Some(&def_id) if def_id.is_local() => {
557 let len = CURRENT_DEPTH.with(|s| s.get());
558 let len = if len == 0 { 0 } else { len - 1 };
561 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
565 needs_termination = true;
568 let loc = match m.extern_locations[&def_id.krate] {
569 (ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
570 (ref cname, _, render::Local) => {
571 let len = CURRENT_DEPTH.with(|s| s.get());
572 Some((cname, "../".repeat(len)))
574 (.., render::Unknown) => None,
576 if let Some((cname, root)) = loc {
579 "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
584 needs_termination = true;
590 write!(f, "{}", name)?;
591 if needs_termination {
597 /// Helper to render type parameters
598 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
599 display_fn(move |f| match *param_names {
600 Some(ref params) => {
601 for param in params {
603 fmt::Display::fmt(¶m.print(), f)?;
611 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
612 display_fn(move |f| {
613 if let Some((url, short_ty, fqp)) = href(did) {
616 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
624 write!(f, "{}", text)
629 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
631 clean::Generic(ref name) => f.write_str(name),
632 clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
633 if param_names.is_some() {
634 f.write_str("dyn ")?;
636 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
637 resolved_path(f, did, path, is_generic, use_absolute)?;
638 fmt::Display::fmt(&tybounds(param_names), f)
640 clean::Infer => write!(f, "_"),
641 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
642 clean::BareFunction(ref decl) => {
647 decl.unsafety.print_with_space(),
648 print_abi_with_space(decl.abi),
649 decl.print_generic_params(),
656 decl.unsafety.print_with_space(),
657 print_abi_with_space(decl.abi)
659 primitive_link(f, PrimitiveType::Fn, "fn")?;
660 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
663 clean::Tuple(ref typs) => {
665 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
667 primitive_link(f, PrimitiveType::Tuple, "(")?;
668 // Carry `f.alternate()` into this display w/o branching manually.
669 fmt::Display::fmt(&one.print(), f)?;
670 primitive_link(f, PrimitiveType::Tuple, ",)")
673 primitive_link(f, PrimitiveType::Tuple, "(")?;
674 for (i, item) in many.iter().enumerate() {
678 fmt::Display::fmt(&item.print(), f)?;
680 primitive_link(f, PrimitiveType::Tuple, ")")
684 clean::Slice(ref t) => {
685 primitive_link(f, PrimitiveType::Slice, "[")?;
686 fmt::Display::fmt(&t.print(), f)?;
687 primitive_link(f, PrimitiveType::Slice, "]")
689 clean::Array(ref t, ref n) => {
690 primitive_link(f, PrimitiveType::Array, "[")?;
691 fmt::Display::fmt(&t.print(), f)?;
692 primitive_link(f, PrimitiveType::Array, &format!("; {}]", 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::FunctionRetTy {
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 (i, seg) in self.path.segments.iter().enumerate() {
1166 write!(f, "{}", seg.name)?;
1174 impl clean::TypeBinding {
1175 crate fn print(&self) -> impl fmt::Display + '_ {
1176 display_fn(move |f| {
1177 f.write_str(&self.name)?;
1179 clean::TypeBindingKind::Equality { ref ty } => {
1181 write!(f, " = {:#}", ty.print())?;
1183 write!(f, " = {}", ty.print())?;
1186 clean::TypeBindingKind::Constraint { ref bounds } => {
1187 if !bounds.is_empty() {
1189 write!(f, ": {:#}", print_generic_bounds(bounds))?;
1191 write!(f, ": {}", print_generic_bounds(bounds))?;
1201 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1202 display_fn(move |f| {
1203 let quot = if f.alternate() { "\"" } else { """ };
1205 Abi::Rust => Ok(()),
1206 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1211 crate fn print_default_space<'a>(v: bool) -> &'a str {
1212 if v { "default " } else { "" }
1215 impl clean::GenericArg {
1216 crate fn print(&self) -> impl fmt::Display + '_ {
1217 display_fn(move |f| match self {
1218 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1219 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1220 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1225 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1226 WithFormatter(Cell::new(Some(f)))
1229 struct WithFormatter<F>(Cell<Option<F>>);
1231 impl<F> fmt::Display for WithFormatter<F>
1233 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 (self.0.take()).unwrap()(f)