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::hir::def_id::DefId;
13 use rustc::util::nodemap::FxHashSet;
14 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);
26 where F: FnOnce(&mut Buffer),
28 fn print(self, buffer: &mut Buffer) {
33 impl Print for String {
34 fn print(self, buffer: &mut Buffer) {
35 buffer.write_str(&self);
39 impl Print for &'_ str {
40 fn print(self, buffer: &mut Buffer) {
41 buffer.write_str(self);
45 #[derive(Debug, Clone)]
52 crate fn empty_from(v: &Buffer) -> Buffer {
55 buffer: String::new(),
59 crate fn html() -> Buffer {
62 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);
111 /// Wrapper struct for properly emitting a function or method declaration.
112 pub struct Function<'a> {
113 /// The declaration to emit.
114 pub decl: &'a clean::FnDecl,
115 /// The length of the function header and name. In other words, the number of characters in the
116 /// function declaration up to but not including the parentheses.
118 /// Used to determine line-wrapping.
119 pub header_len: usize,
120 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
122 /// Whether the function is async or not.
123 pub asyncness: hir::IsAsync,
126 /// Wrapper struct for emitting a where-clause from Generics.
127 pub struct WhereClause<'a>{
128 /// The Generics from which to emit a where-clause.
129 pub gens: &'a clean::Generics,
130 /// The number of spaces to indent each line with.
132 /// Whether the where-clause needs to add a comma and newline after the last bound.
133 pub end_newline: bool,
136 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item=T>) -> impl fmt::Display {
137 display_fn(move |f| {
138 for (i, item) in items.enumerate() {
139 if i != 0 { write!(f, ", ")?; }
140 fmt::Display::fmt(&item, f)?;
146 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
147 display_fn(move |f| {
148 let mut bounds_dup = FxHashSet::default();
150 for (i, bound) in bounds.iter().filter(|b| {
151 bounds_dup.insert(b.print().to_string())
156 fmt::Display::fmt(&bound.print(), f)?;
162 impl clean::GenericParamDef {
163 crate fn print(&self) -> impl fmt::Display + '_ {
164 display_fn(move |f| {
166 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
167 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
168 f.write_str(&self.name)?;
170 if !bounds.is_empty() {
172 write!(f, ": {:#}", print_generic_bounds(bounds))?;
174 write!(f, ": {}", print_generic_bounds(bounds))?;
178 if let Some(ref ty) = default {
180 write!(f, " = {:#}", ty.print())?;
182 write!(f, " = {}", ty.print())?;
188 clean::GenericParamDefKind::Const { ref ty, .. } => {
189 f.write_str("const ")?;
190 f.write_str(&self.name)?;
193 write!(f, ": {:#}", ty.print())
195 write!(f, ": {}", ty.print())
203 impl clean::Generics {
204 crate fn print(&self) -> impl fmt::Display + '_ {
205 display_fn(move |f| {
206 let real_params = self.params
208 .filter(|p| !p.is_synthetic_type_param())
209 .collect::<Vec<_>>();
210 if real_params.is_empty() {
214 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
216 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print())))
222 impl<'a> fmt::Display for WhereClause<'a> {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 let &WhereClause { gens, indent, end_newline } = self;
225 if gens.where_predicates.is_empty() {
228 let mut clause = String::new();
230 clause.push_str(" where");
233 clause.push_str(" <span class=\"where fmt-newline\">where");
235 clause.push_str(" <span class=\"where\">where");
238 for (i, pred) in gens.where_predicates.iter().enumerate() {
242 clause.push_str("<br>");
246 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
249 clause.push_str(&format!("{:#}: {:#}",
250 ty.print(), print_generic_bounds(bounds)));
252 clause.push_str(&format!("{}: {}",
253 ty.print(), print_generic_bounds(bounds)));
256 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
257 clause.push_str(&format!("{}: {}",
260 .map(|b| b.print().to_string())
264 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
266 clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
268 clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
273 if i < gens.where_predicates.len() - 1 || end_newline {
279 // add a space so stripping <br> tags and breaking spaces still renders properly
283 clause.push_str(" ");
288 clause.push_str("</span>");
289 let padding = " ".repeat(indent + 4);
290 clause = clause.replace("<br>", &format!("<br>{}", padding));
291 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
293 clause.insert_str(0, "<br>");
296 write!(f, "{}", clause)
300 impl clean::Lifetime {
301 crate fn print(&self) -> &str {
306 impl clean::Constant {
307 crate fn print(&self) -> &str {
312 impl clean::PolyTrait {
313 fn print(&self) -> impl fmt::Display + '_ {
314 display_fn(move |f| {
315 if !self.generic_params.is_empty() {
317 write!(f, "for<{:#}> ",
318 comma_sep(self.generic_params.iter().map(|g| g.print())))?;
320 write!(f, "for<{}> ",
321 comma_sep(self.generic_params.iter().map(|g| g.print())))?;
325 write!(f, "{:#}", self.trait_.print())
327 write!(f, "{}", self.trait_.print())
333 impl clean::GenericBound {
334 crate fn print(&self) -> impl fmt::Display + '_ {
335 display_fn(move |f| {
337 clean::GenericBound::Outlives(lt) => {
338 write!(f, "{}", lt.print())
340 clean::GenericBound::TraitBound(ty, modifier) => {
341 let modifier_str = match modifier {
342 hir::TraitBoundModifier::None => "",
343 hir::TraitBoundModifier::Maybe => "?",
346 write!(f, "{}{:#}", modifier_str, ty.print())
348 write!(f, "{}{}", modifier_str, ty.print())
356 impl clean::GenericArgs {
357 fn print(&self) -> impl fmt::Display + '_ {
358 display_fn(move |f| {
360 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
361 if !args.is_empty() || !bindings.is_empty() {
365 f.write_str("<")?;
367 let mut comma = false;
374 write!(f, "{:#}", arg.print())?;
376 write!(f, "{}", arg.print())?;
379 for binding in bindings {
385 write!(f, "{:#}", binding.print())?;
387 write!(f, "{}", binding.print())?;
393 f.write_str(">")?;
397 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
399 let mut comma = false;
406 write!(f, "{:#}", ty.print())?;
408 write!(f, "{}", ty.print())?;
412 if let Some(ref ty) = *output {
414 write!(f, " -> {:#}", ty.print())?;
416 write!(f, " -> {}", ty.print())?;
426 impl clean::PathSegment {
427 crate fn print(&self) -> impl fmt::Display + '_ {
428 display_fn(move |f| {
429 f.write_str(&self.name)?;
431 write!(f, "{:#}", self.args.print())
433 write!(f, "{}", self.args.print())
440 crate fn print(&self) -> impl fmt::Display + '_ {
441 display_fn(move |f| {
446 for (i, seg) in self.segments.iter().enumerate() {
451 write!(f, "{:#}", seg.print())?;
453 write!(f, "{}", seg.print())?;
461 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
463 if !did.is_local() && !cache.access_levels.is_public(did) {
467 let depth = CURRENT_DEPTH.with(|l| l.get());
468 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
469 Some(&(ref fqp, shortty)) => {
470 (fqp, shortty, "../".repeat(depth))
473 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
474 (fqp, shortty, match cache.extern_locations[&did.krate] {
475 (.., render::Remote(ref s)) => s.to_string(),
476 (.., render::Local) => "../".repeat(depth),
477 (.., render::Unknown) => return None,
481 for component in &fqp[..fqp.len() - 1] {
482 url.push_str(component);
486 ItemType::Module => {
487 url.push_str(fqp.last().unwrap());
488 url.push_str("/index.html");
491 url.push_str(shortty.as_str());
493 url.push_str(fqp.last().unwrap());
494 url.push_str(".html");
497 Some((url, shortty, fqp.to_vec()))
500 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
501 /// rendering function with the necessary arguments for linking to a local path.
502 fn resolved_path(w: &mut fmt::Formatter<'_>, did: DefId, path: &clean::Path,
503 print_all: bool, use_absolute: bool) -> fmt::Result {
504 let last = path.segments.last().unwrap();
507 for seg in &path.segments[..path.segments.len() - 1] {
508 write!(w, "{}::", seg.name)?;
512 write!(w, "{}{:#}", &last.name, last.args.print())?;
514 let path = if use_absolute {
515 if let Some((_, _, fqp)) = href(did) {
517 fqp[..fqp.len() - 1].join("::"),
518 anchor(did, fqp.last().unwrap()))
520 last.name.to_string()
523 anchor(did, &last.name).to_string()
525 write!(w, "{}{}", path, last.args.print())?;
530 fn primitive_link(f: &mut fmt::Formatter<'_>,
531 prim: clean::PrimitiveType,
532 name: &str) -> fmt::Result {
534 let mut needs_termination = false;
536 match m.primitive_locations.get(&prim) {
537 Some(&def_id) if def_id.is_local() => {
538 let len = CURRENT_DEPTH.with(|s| s.get());
539 let len = if len == 0 {0} else {len - 1};
540 write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
543 needs_termination = true;
546 let loc = match m.extern_locations[&def_id.krate] {
547 (ref cname, _, render::Remote(ref s)) => {
548 Some((cname, s.to_string()))
550 (ref cname, _, render::Local) => {
551 let len = CURRENT_DEPTH.with(|s| s.get());
552 Some((cname, "../".repeat(len)))
554 (.., render::Unknown) => None,
556 if let Some((cname, root)) = loc {
557 write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
561 needs_termination = true;
567 write!(f, "{}", name)?;
568 if needs_termination {
574 /// Helper to render type parameters
575 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
576 display_fn(move |f| {
578 Some(ref params) => {
579 for param in params {
581 fmt::Display::fmt(¶m.print(), f)?;
590 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
591 display_fn(move |f| {
592 if let Some((url, short_ty, fqp)) = href(did) {
593 write!(f, r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
594 short_ty, url, short_ty, fqp.join("::"), text)
596 write!(f, "{}", text)
601 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
603 clean::Generic(ref name) => {
606 clean::ResolvedPath{ did, ref param_names, ref path, is_generic } => {
607 if param_names.is_some() {
608 f.write_str("dyn ")?;
610 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
611 resolved_path(f, did, path, is_generic, use_absolute)?;
612 fmt::Display::fmt(&tybounds(param_names), f)
614 clean::Infer => write!(f, "_"),
615 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
616 clean::BareFunction(ref decl) => {
618 write!(f, "{}{:#}fn{:#}{:#}",
619 decl.unsafety.print_with_space(),
620 print_abi_with_space(decl.abi),
621 decl.print_generic_params(),
625 decl.unsafety.print_with_space(), print_abi_with_space(decl.abi))?;
626 primitive_link(f, PrimitiveType::Fn, "fn")?;
627 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
630 clean::Tuple(ref typs) => {
632 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
634 primitive_link(f, PrimitiveType::Tuple, "(")?;
635 // Carry `f.alternate()` into this display w/o branching manually.
636 fmt::Display::fmt(&one.print(), f)?;
637 primitive_link(f, PrimitiveType::Tuple, ",)")
640 primitive_link(f, PrimitiveType::Tuple, "(")?;
641 for (i, item) in many.iter().enumerate() {
642 if i != 0 { write!(f, ", ")?; }
643 fmt::Display::fmt(&item.print(), f)?;
645 primitive_link(f, PrimitiveType::Tuple, ")")
649 clean::Slice(ref t) => {
650 primitive_link(f, PrimitiveType::Slice, "[")?;
651 fmt::Display::fmt(&t.print(), f)?;
652 primitive_link(f, PrimitiveType::Slice, "]")
654 clean::Array(ref t, ref n) => {
655 primitive_link(f, PrimitiveType::Array, "[")?;
656 fmt::Display::fmt(&t.print(), f)?;
657 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
659 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
660 clean::RawPointer(m, ref t) => {
662 clean::Immutable => "const",
663 clean::Mutable => "mut",
666 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
668 primitive_link(f, clean::PrimitiveType::RawPointer,
669 &format!("*{} {:#}", m, t.print()))
671 primitive_link(f, clean::PrimitiveType::RawPointer,
672 &format!("*{} {}", m, t.print()))
676 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
677 fmt::Display::fmt(&t.print(), f)
681 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
683 Some(l) => format!("{} ", l.print()),
686 let m = mutability.print_with_space();
687 let amp = if f.alternate() {
693 clean::Slice(ref bt) => { // `BorrowedRef{ ... Slice(T) }` is `&[T]`
695 clean::Generic(_) => {
697 primitive_link(f, PrimitiveType::Slice,
698 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()))
700 primitive_link(f, PrimitiveType::Slice,
701 &format!("{}{}{}[{}]", amp, lt, m, bt.print()))
705 primitive_link(f, PrimitiveType::Slice,
706 &format!("{}{}{}[", amp, lt, m))?;
708 write!(f, "{:#}", bt.print())?;
710 write!(f, "{}", bt.print())?;
712 primitive_link(f, PrimitiveType::Slice, "]")
716 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
717 write!(f, "{}{}{}(", amp, lt, m)?;
718 fmt_type(&ty, f, use_absolute)?;
721 clean::Generic(..) => {
722 primitive_link(f, PrimitiveType::Reference,
723 &format!("{}{}{}", amp, lt, m))?;
724 fmt_type(&ty, f, use_absolute)
727 write!(f, "{}{}{}", amp, lt, m)?;
728 fmt_type(&ty, f, use_absolute)
732 clean::ImplTrait(ref bounds) => {
734 write!(f, "impl {:#}", print_generic_bounds(bounds))
736 write!(f, "impl {}", print_generic_bounds(bounds))
739 clean::QPath { ref name, ref self_type, ref trait_ } => {
740 let should_show_cast = match *trait_ {
741 box clean::ResolvedPath { ref path, .. } => {
742 !path.segments.is_empty() && !self_type.is_self_type()
747 if should_show_cast {
748 write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
750 write!(f, "{:#}::", self_type.print())?
753 if should_show_cast {
754 write!(f, "<{} as {}>::", self_type.print(), trait_.print())?
756 write!(f, "{}::", self_type.print())?
760 // It's pretty unsightly to look at `<A as B>::C` in output, and
761 // we've got hyperlinking on our side, so try to avoid longer
762 // notation as much as possible by making `C` a hyperlink to trait
763 // `B` to disambiguate.
765 // FIXME: this is still a lossy conversion and there should probably
766 // be a better way of representing this in general? Most of
767 // the ugliness comes from inlining across crates where
768 // everything comes in as a fully resolved QPath (hard to
770 box clean::ResolvedPath { did, ref param_names, .. } => {
772 Some((ref url, _, ref path)) if !f.alternate() => {
774 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
775 title=\"type {path}::{name}\">{name}</a>",
777 shortty = ItemType::AssocType,
779 path = path.join("::"))?;
781 _ => write!(f, "{}", name)?,
784 // FIXME: `param_names` are not rendered, and this seems bad?
789 write!(f, "{}", name)
797 crate fn print(&self) -> impl fmt::Display + '_ {
798 display_fn(move |f| {
799 fmt_type(self, f, false)
805 crate fn print(&self) -> impl fmt::Display + '_ {
806 self.print_inner(true, false)
813 ) -> impl fmt::Display + '_ {
814 display_fn(move |f| {
816 write!(f, "impl{:#} ", self.generics.print())?;
818 write!(f, "impl{} ", self.generics.print())?;
821 if let Some(ref ty) = self.trait_ {
822 if self.polarity == Some(clean::ImplPolarity::Negative) {
827 fmt::Display::fmt(&ty.print(), f)?;
830 clean::ResolvedPath { param_names: None, path, is_generic: false, .. } => {
831 let last = path.segments.last().unwrap();
832 fmt::Display::fmt(&last.name, f)?;
833 fmt::Display::fmt(&last.args.print(), f)?;
841 if let Some(ref ty) = self.blanket_impl {
842 fmt_type(ty, f, use_absolute)?;
844 fmt_type(&self.for_, f, use_absolute)?;
847 fmt::Display::fmt(&WhereClause {
848 gens: &self.generics,
857 // The difference from above is that trait is not hyperlinked.
858 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
860 use_absolute: bool) {
861 f.from_display(i.print_inner(false, use_absolute))
864 impl clean::Arguments {
865 crate fn print(&self) -> impl fmt::Display + '_ {
866 display_fn(move |f| {
867 for (i, input) in self.values.iter().enumerate() {
868 if !input.name.is_empty() {
869 write!(f, "{}: ", input.name)?;
872 write!(f, "{:#}", input.type_.print())?;
874 write!(f, "{}", input.type_.print())?;
876 if i + 1 < self.values.len() { write!(f, ", ")?; }
883 impl clean::FunctionRetTy {
884 crate fn print(&self) -> impl fmt::Display + '_ {
885 display_fn(move |f| {
887 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
888 clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
889 clean::Return(ty) => write!(f, " -> {}", ty.print()),
890 clean::DefaultReturn => Ok(()),
896 impl clean::BareFunctionDecl {
897 fn print_generic_params(&self) -> impl fmt::Display + '_ {
898 comma_sep(self.generic_params.iter().map(|g| g.print()))
903 crate fn print(&self) -> impl fmt::Display + '_ {
904 display_fn(move |f| {
905 let ellipsis = if self.c_variadic { ", ..." } else { "" };
908 "({args:#}{ellipsis}){arrow:#}",
909 args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
912 "({args}{ellipsis}){arrow}",
913 args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
921 crate fn print(&self) -> impl fmt::Display + '_ {
922 display_fn(move |f| {
923 let &Function { decl, header_len, indent, asyncness } = self;
924 let amp = if f.alternate() { "&" } else { "&" };
925 let mut args = String::new();
926 let mut args_plain = String::new();
927 for (i, input) in decl.inputs.values.iter().enumerate() {
929 args.push_str("<br>");
932 if let Some(selfty) = input.to_self() {
934 clean::SelfValue => {
935 args.push_str("self");
936 args_plain.push_str("self");
938 clean::SelfBorrowed(Some(ref lt), mtbl) => {
940 &format!("{}{} {}self", amp, lt.print(), mtbl.print_with_space()));
942 &format!("&{} {}self", lt.print(), mtbl.print_with_space()));
944 clean::SelfBorrowed(None, mtbl) => {
945 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
946 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
948 clean::SelfExplicit(ref typ) => {
950 args.push_str(&format!("self: {:#}", typ.print()));
952 args.push_str(&format!("self: {}", typ.print()));
954 args_plain.push_str(&format!("self: {:#}", typ.print()));
959 args.push_str(" <br>");
960 args_plain.push_str(" ");
962 if !input.name.is_empty() {
963 args.push_str(&format!("{}: ", input.name));
964 args_plain.push_str(&format!("{}: ", input.name));
968 args.push_str(&format!("{:#}", input.type_.print()));
970 args.push_str(&input.type_.print().to_string());
972 args_plain.push_str(&format!("{:#}", input.type_.print()));
974 if i + 1 < decl.inputs.values.len() {
976 args_plain.push(',');
980 let mut args_plain = format!("({})", args_plain);
983 args.push_str(",<br> ...");
984 args_plain.push_str(", ...");
987 let output = if let hir::IsAsync::Async = asyncness {
988 Cow::Owned(decl.sugared_async_return_type())
990 Cow::Borrowed(&decl.output)
993 let arrow_plain = format!("{:#}", &output.print());
994 let arrow = if f.alternate() {
995 format!("{:#}", &output.print())
997 output.print().to_string()
1000 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1001 let output = if declaration_len > 80 {
1002 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1003 let close_pad = format!("<br>{}", " ".repeat(indent));
1004 format!("({args}{close}){arrow}",
1005 args = args.replace("<br>", &full_pad),
1009 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1013 write!(f, "{}", output.replace("<br>", "\n"))
1015 write!(f, "{}", output)
1021 impl clean::Visibility {
1022 crate fn print_with_space(&self) -> impl fmt::Display + '_ {
1023 display_fn(move |f| {
1025 clean::Public => f.write_str("pub "),
1026 clean::Inherited => Ok(()),
1027 clean::Visibility::Crate => write!(f, "pub(crate) "),
1028 clean::Visibility::Restricted(did, ref path) => {
1029 f.write_str("pub(")?;
1030 if path.segments.len() != 1
1031 || (path.segments[0].name != "self" && path.segments[0].name != "super")
1033 f.write_str("in ")?;
1035 resolved_path(f, did, path, true, false)?;
1043 crate trait PrintWithSpace {
1044 fn print_with_space(&self) -> &str;
1047 impl PrintWithSpace for hir::Unsafety {
1048 fn print_with_space(&self) -> &str {
1050 hir::Unsafety::Unsafe => "unsafe ",
1051 hir::Unsafety::Normal => ""
1056 impl PrintWithSpace for hir::Constness {
1057 fn print_with_space(&self) -> &str {
1059 hir::Constness::Const => "const ",
1060 hir::Constness::NotConst => ""
1065 impl PrintWithSpace for hir::IsAsync {
1066 fn print_with_space(&self) -> &str {
1068 hir::IsAsync::Async => "async ",
1069 hir::IsAsync::NotAsync => "",
1074 impl clean::Import {
1075 crate fn print(&self) -> impl fmt::Display + '_ {
1076 display_fn(move |f| {
1078 clean::Import::Simple(ref name, ref src) => {
1079 if *name == src.path.last_name() {
1080 write!(f, "use {};", src.print())
1082 write!(f, "use {} as {};", src.print(), *name)
1085 clean::Import::Glob(ref src) => {
1086 if src.path.segments.is_empty() {
1089 write!(f, "use {}::*;", src.print())
1097 impl clean::ImportSource {
1098 crate fn print(&self) -> impl fmt::Display + '_ {
1099 display_fn(move |f| {
1101 Some(did) => resolved_path(f, did, &self.path, true, false),
1103 for (i, seg) in self.path.segments.iter().enumerate() {
1107 write!(f, "{}", seg.name)?;
1116 impl clean::TypeBinding {
1117 crate fn print(&self) -> impl fmt::Display + '_ {
1118 display_fn(move |f| {
1119 f.write_str(&self.name)?;
1121 clean::TypeBindingKind::Equality { ref ty } => {
1123 write!(f, " = {:#}", ty.print())?;
1125 write!(f, " = {}", ty.print())?;
1128 clean::TypeBindingKind::Constraint { ref bounds } => {
1129 if !bounds.is_empty() {
1131 write!(f, ": {:#}", print_generic_bounds(bounds))?;
1133 write!(f, ": {}", print_generic_bounds(bounds))?;
1143 impl clean::Mutability {
1144 crate fn print_with_space(&self) -> &str {
1146 clean::Immutable => "",
1147 clean::Mutable => "mut ",
1152 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1153 display_fn(move |f| {
1154 let quot = if f.alternate() { "\"" } else { """ };
1156 Abi::Rust => Ok(()),
1157 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1162 crate fn print_default_space<'a>(v: bool) -> &'a str {
1170 impl clean::GenericArg {
1171 crate fn print(&self) -> impl fmt::Display + '_ {
1172 display_fn(move |f| {
1174 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1175 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1176 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1182 crate fn display_fn(
1183 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1184 ) -> impl fmt::Display {
1185 WithFormatter(Cell::new(Some(f)))
1188 struct WithFormatter<F>(Cell<Option<F>>);
1190 impl<F> fmt::Display for WithFormatter<F>
1191 where F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194 (self.0.take()).unwrap()(f)