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 with_formatter<T: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result>(&mut self, t: T) {
103 self.from_display(display_fn(move |f| (t)(f)));
106 crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
108 write!(self, "{}", t);
110 write!(self, "{:#}", t);
115 /// Helper to render an optional visibility with a space after it (if the
116 /// visibility is preset)
117 #[derive(Copy, Clone)]
118 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
119 /// Similarly to VisSpace, this structure is used to render a function style with a
121 #[derive(Copy, Clone)]
122 pub struct UnsafetySpace(pub hir::Unsafety);
123 /// Similarly to VisSpace, this structure is used to render a function constness
124 /// with a space after it.
125 #[derive(Copy, Clone)]
126 pub struct ConstnessSpace(pub hir::Constness);
127 /// Similarly to VisSpace, this structure is used to render a function asyncness
128 /// with a space after it.
129 #[derive(Copy, Clone)]
130 pub struct AsyncSpace(pub hir::IsAsync);
131 /// Similar to VisSpace, but used for mutability
132 #[derive(Copy, Clone)]
133 pub struct MutableSpace(pub clean::Mutability);
134 /// Wrapper struct for emitting type parameter bounds.
135 pub struct GenericBounds<'a>(pub &'a [clean::GenericBound]);
136 pub struct AbiSpace(pub Abi);
137 pub struct DefaultSpace(pub bool);
139 /// Wrapper struct for properly emitting a function or method declaration.
140 pub struct Function<'a> {
141 /// The declaration to emit.
142 pub decl: &'a clean::FnDecl,
143 /// The length of the function header and name. In other words, the number of characters in the
144 /// function declaration up to but not including the parentheses.
146 /// Used to determine line-wrapping.
147 pub header_len: usize,
148 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
150 /// Whether the function is async or not.
151 pub asyncness: hir::IsAsync,
154 /// Wrapper struct for emitting a where-clause from Generics.
155 pub struct WhereClause<'a>{
156 /// The Generics from which to emit a where-clause.
157 pub gens: &'a clean::Generics,
158 /// The number of spaces to indent each line with.
160 /// Whether the where-clause needs to add a comma and newline after the last bound.
161 pub end_newline: bool,
164 impl<'a> VisSpace<'a> {
165 pub fn get(self) -> &'a Option<clean::Visibility> {
166 let VisSpace(v) = self; v
171 pub fn get(&self) -> hir::Unsafety {
172 let UnsafetySpace(v) = *self; v
176 impl ConstnessSpace {
177 pub fn get(&self) -> hir::Constness {
178 let ConstnessSpace(v) = *self; v
182 fn comma_sep<T: fmt::Display>(items: &[T]) -> impl fmt::Display + '_ {
183 display_fn(move |f| {
184 for (i, item) in items.iter().enumerate() {
185 if i != 0 { write!(f, ", ")?; }
186 fmt::Display::fmt(item, f)?;
192 impl<'a> fmt::Display for GenericBounds<'a> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 let mut bounds_dup = FxHashSet::default();
195 let &GenericBounds(bounds) = self;
197 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.to_string())).enumerate() {
201 fmt::Display::fmt(bound, f)?;
207 impl fmt::Display for clean::GenericParamDef {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
211 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
212 f.write_str(&self.name)?;
214 if !bounds.is_empty() {
216 write!(f, ": {:#}", GenericBounds(bounds))?;
218 write!(f, ": {}", GenericBounds(bounds))?;
222 if let Some(ref ty) = default {
224 write!(f, " = {:#}", ty)?;
226 write!(f, " = {}", ty)?;
232 clean::GenericParamDefKind::Const { ref ty, .. } => {
233 f.write_str("const ")?;
234 f.write_str(&self.name)?;
237 write!(f, ": {:#}", ty)
239 write!(f, ": {}", ty)
246 impl fmt::Display for clean::Generics {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 let real_params = self.params
250 .filter(|p| !p.is_synthetic_type_param())
251 .collect::<Vec<_>>();
252 if real_params.is_empty() {
256 write!(f, "<{:#}>", comma_sep(&real_params))
258 write!(f, "<{}>", comma_sep(&real_params))
263 impl<'a> fmt::Display for WhereClause<'a> {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 let &WhereClause { gens, indent, end_newline } = self;
266 if gens.where_predicates.is_empty() {
269 let mut clause = String::new();
271 clause.push_str(" where");
274 clause.push_str(" <span class=\"where fmt-newline\">where");
276 clause.push_str(" <span class=\"where\">where");
279 for (i, pred) in gens.where_predicates.iter().enumerate() {
283 clause.push_str("<br>");
287 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
290 clause.push_str(&format!("{:#}: {:#}", ty, GenericBounds(bounds)));
292 clause.push_str(&format!("{}: {}", ty, GenericBounds(bounds)));
295 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
296 clause.push_str(&format!("{}: {}",
299 .map(|b| b.to_string())
303 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
305 clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
307 clause.push_str(&format!("{} == {}", lhs, rhs));
312 if i < gens.where_predicates.len() - 1 || end_newline {
318 // add a space so stripping <br> tags and breaking spaces still renders properly
322 clause.push_str(" ");
327 clause.push_str("</span>");
328 let padding = " ".repeat(indent + 4);
329 clause = clause.replace("<br>", &format!("<br>{}", padding));
330 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
332 clause.insert_str(0, "<br>");
335 write!(f, "{}", clause)
339 impl fmt::Display for clean::Lifetime {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 f.write_str(self.get_ref())?;
346 impl fmt::Display for clean::Constant {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 fmt::Display::fmt(&self.expr, f)
352 impl fmt::Display for clean::PolyTrait {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 if !self.generic_params.is_empty() {
356 write!(f, "for<{:#}> ", comma_sep(&self.generic_params))?;
358 write!(f, "for<{}> ", comma_sep(&self.generic_params))?;
362 write!(f, "{:#}", self.trait_)
364 write!(f, "{}", self.trait_)
369 impl fmt::Display for clean::GenericBound {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 clean::GenericBound::Outlives(ref lt) => {
375 clean::GenericBound::TraitBound(ref ty, modifier) => {
376 let modifier_str = match modifier {
377 hir::TraitBoundModifier::None => "",
378 hir::TraitBoundModifier::Maybe => "?",
381 write!(f, "{}{:#}", modifier_str, *ty)
383 write!(f, "{}{}", modifier_str, *ty)
390 impl fmt::Display for clean::GenericArgs {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
394 if !args.is_empty() || !bindings.is_empty() {
398 f.write_str("<")?;
400 let mut comma = false;
407 write!(f, "{:#}", *arg)?;
409 write!(f, "{}", *arg)?;
412 for binding in bindings {
418 write!(f, "{:#}", *binding)?;
420 write!(f, "{}", *binding)?;
426 f.write_str(">")?;
430 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
432 let mut comma = false;
439 write!(f, "{:#}", *ty)?;
441 write!(f, "{}", *ty)?;
445 if let Some(ref ty) = *output {
447 write!(f, " -> {:#}", ty)?;
449 write!(f, " -> {}", ty)?;
458 impl fmt::Display for clean::PathSegment {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 f.write_str(&self.name)?;
462 write!(f, "{:#}", self.args)
464 write!(f, "{}", self.args)
469 impl fmt::Display for clean::Path {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 for (i, seg) in self.segments.iter().enumerate() {
480 write!(f, "{:#}", seg)?;
482 write!(f, "{}", seg)?;
489 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
491 if !did.is_local() && !cache.access_levels.is_public(did) {
495 let depth = CURRENT_DEPTH.with(|l| l.get());
496 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
497 Some(&(ref fqp, shortty)) => {
498 (fqp, shortty, "../".repeat(depth))
501 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
502 (fqp, shortty, match cache.extern_locations[&did.krate] {
503 (.., render::Remote(ref s)) => s.to_string(),
504 (.., render::Local) => "../".repeat(depth),
505 (.., render::Unknown) => return None,
509 for component in &fqp[..fqp.len() - 1] {
510 url.push_str(component);
514 ItemType::Module => {
515 url.push_str(fqp.last().unwrap());
516 url.push_str("/index.html");
519 url.push_str(shortty.css_class());
521 url.push_str(fqp.last().unwrap());
522 url.push_str(".html");
525 Some((url, shortty, fqp.to_vec()))
528 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
529 /// rendering function with the necessary arguments for linking to a local path.
530 fn resolved_path(w: &mut fmt::Formatter<'_>, did: DefId, path: &clean::Path,
531 print_all: bool, use_absolute: bool) -> fmt::Result {
532 let last = path.segments.last().unwrap();
535 for seg in &path.segments[..path.segments.len() - 1] {
536 write!(w, "{}::", seg.name)?;
540 write!(w, "{}{:#}", &last.name, last.args)?;
542 let path = if use_absolute {
543 if let Some((_, _, fqp)) = href(did) {
545 fqp[..fqp.len() - 1].join("::"),
546 anchor(did, fqp.last().unwrap()))
548 last.name.to_string()
551 anchor(did, &last.name).to_string()
553 write!(w, "{}{}", path, last.args)?;
558 fn primitive_link(f: &mut fmt::Formatter<'_>,
559 prim: clean::PrimitiveType,
560 name: &str) -> fmt::Result {
562 let mut needs_termination = false;
564 match m.primitive_locations.get(&prim) {
565 Some(&def_id) if def_id.is_local() => {
566 let len = CURRENT_DEPTH.with(|s| s.get());
567 let len = if len == 0 {0} else {len - 1};
568 write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
571 needs_termination = true;
574 let loc = match m.extern_locations[&def_id.krate] {
575 (ref cname, _, render::Remote(ref s)) => {
576 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 {
585 write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
589 needs_termination = true;
595 write!(f, "{}", name)?;
596 if needs_termination {
602 /// Helper to render type parameters
603 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
604 display_fn(move |f| {
606 Some(ref params) => {
607 for param in params {
609 fmt::Display::fmt(param, f)?;
618 pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
619 display_fn(move |f| {
620 if let Some((url, short_ty, fqp)) = href(did) {
621 write!(f, r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
622 short_ty, url, short_ty, fqp.join("::"), text)
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) => {
634 clean::ResolvedPath{ did, ref param_names, ref path, is_generic } => {
635 if param_names.is_some() {
636 f.write_str("dyn ")?;
638 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
639 resolved_path(f, did, path, is_generic, use_absolute)?;
640 fmt::Display::fmt(&tybounds(param_names), f)
642 clean::Infer => write!(f, "_"),
643 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
644 clean::BareFunction(ref decl) => {
646 write!(f, "{}{:#}fn{:#}{:#}",
647 UnsafetySpace(decl.unsafety),
649 comma_sep(&decl.generic_params),
652 write!(f, "{}{}", UnsafetySpace(decl.unsafety), AbiSpace(decl.abi))?;
653 primitive_link(f, PrimitiveType::Fn, "fn")?;
654 write!(f, "{}{}", comma_sep(&decl.generic_params), decl.decl)
657 clean::Tuple(ref typs) => {
659 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
661 primitive_link(f, PrimitiveType::Tuple, "(")?;
662 // Carry `f.alternate()` into this display w/o branching manually.
663 fmt::Display::fmt(one, f)?;
664 primitive_link(f, PrimitiveType::Tuple, ",)")
667 primitive_link(f, PrimitiveType::Tuple, "(")?;
668 fmt::Display::fmt(&comma_sep(many), f)?;
669 primitive_link(f, PrimitiveType::Tuple, ")")
673 clean::Slice(ref t) => {
674 primitive_link(f, PrimitiveType::Slice, "[")?;
675 fmt::Display::fmt(t, f)?;
676 primitive_link(f, PrimitiveType::Slice, "]")
678 clean::Array(ref t, ref n) => {
679 primitive_link(f, PrimitiveType::Array, "[")?;
680 fmt::Display::fmt(t, f)?;
681 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
683 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
684 clean::CVarArgs => primitive_link(f, PrimitiveType::CVarArgs, "..."),
685 clean::RawPointer(m, ref t) => {
687 clean::Immutable => "const",
688 clean::Mutable => "mut",
691 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
693 primitive_link(f, clean::PrimitiveType::RawPointer,
694 &format!("*{} {:#}", m, t))
696 primitive_link(f, clean::PrimitiveType::RawPointer,
697 &format!("*{} {}", m, t))
701 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
702 fmt::Display::fmt(t, f)
706 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
708 Some(ref l) => format!("{} ", *l),
711 let m = MutableSpace(mutability);
712 let amp = if f.alternate() {
718 clean::Slice(ref bt) => { // `BorrowedRef{ ... Slice(T) }` is `&[T]`
720 clean::Generic(_) => {
722 primitive_link(f, PrimitiveType::Slice,
723 &format!("{}{}{}[{:#}]", amp, lt, m, **bt))
725 primitive_link(f, PrimitiveType::Slice,
726 &format!("{}{}{}[{}]", amp, lt, m, **bt))
730 primitive_link(f, PrimitiveType::Slice,
731 &format!("{}{}{}[", amp, lt, m))?;
733 write!(f, "{:#}", **bt)?;
735 write!(f, "{}", **bt)?;
737 primitive_link(f, PrimitiveType::Slice, "]")
741 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
742 write!(f, "{}{}{}(", amp, lt, m)?;
743 fmt_type(&ty, f, use_absolute)?;
746 clean::Generic(..) => {
747 primitive_link(f, PrimitiveType::Reference,
748 &format!("{}{}{}", amp, lt, m))?;
749 fmt_type(&ty, f, use_absolute)
752 write!(f, "{}{}{}", amp, lt, m)?;
753 fmt_type(&ty, f, use_absolute)
757 clean::ImplTrait(ref bounds) => {
759 write!(f, "impl {:#}", GenericBounds(bounds))
761 write!(f, "impl {}", GenericBounds(bounds))
764 clean::QPath { ref name, ref self_type, ref trait_ } => {
765 let should_show_cast = match *trait_ {
766 box clean::ResolvedPath { ref path, .. } => {
767 !path.segments.is_empty() && !self_type.is_self_type()
772 if should_show_cast {
773 write!(f, "<{:#} as {:#}>::", self_type, trait_)?
775 write!(f, "{:#}::", self_type)?
778 if should_show_cast {
779 write!(f, "<{} as {}>::", self_type, trait_)?
781 write!(f, "{}::", self_type)?
785 // It's pretty unsightly to look at `<A as B>::C` in output, and
786 // we've got hyperlinking on our side, so try to avoid longer
787 // notation as much as possible by making `C` a hyperlink to trait
788 // `B` to disambiguate.
790 // FIXME: this is still a lossy conversion and there should probably
791 // be a better way of representing this in general? Most of
792 // the ugliness comes from inlining across crates where
793 // everything comes in as a fully resolved QPath (hard to
795 box clean::ResolvedPath { did, ref param_names, .. } => {
797 Some((ref url, _, ref path)) if !f.alternate() => {
799 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
800 title=\"type {path}::{name}\">{name}</a>",
802 shortty = ItemType::AssocType,
804 path = path.join("::"))?;
806 _ => write!(f, "{}", name)?,
809 // FIXME: `param_names` are not rendered, and this seems bad?
814 write!(f, "{}", name)
821 impl fmt::Display for clean::Type {
822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823 fmt_type(self, f, false)
827 fn fmt_impl(i: &clean::Impl,
828 f: &mut fmt::Formatter<'_>,
830 use_absolute: bool) -> fmt::Result {
832 write!(f, "impl{:#} ", i.generics)?;
834 write!(f, "impl{} ", i.generics)?;
837 if let Some(ref ty) = i.trait_ {
838 if i.polarity == Some(clean::ImplPolarity::Negative) {
843 fmt::Display::fmt(ty, f)?;
846 clean::ResolvedPath { param_names: None, ref path, is_generic: false, .. } => {
847 let last = path.segments.last().unwrap();
848 fmt::Display::fmt(&last.name, f)?;
849 fmt::Display::fmt(&last.args, f)?;
857 if let Some(ref ty) = i.blanket_impl {
858 fmt_type(ty, f, use_absolute)?;
860 fmt_type(&i.for_, f, use_absolute)?;
863 fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?;
867 impl fmt::Display for clean::Impl {
868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
869 fmt_impl(self, f, true, false)
873 // The difference from above is that trait is not hyperlinked.
874 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
876 use_absolute: bool) {
877 f.with_formatter(|f| fmt_impl(i, f, false, use_absolute))
880 impl fmt::Display for clean::Arguments {
881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 for (i, input) in self.values.iter().enumerate() {
883 if !input.name.is_empty() {
884 write!(f, "{}: ", input.name)?;
887 write!(f, "{:#}", input.type_)?;
889 write!(f, "{}", input.type_)?;
891 if i + 1 < self.values.len() { write!(f, ", ")?; }
897 impl fmt::Display for clean::FunctionRetTy {
898 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
901 clean::Return(ref ty) if f.alternate() => write!(f, " -> {:#}", ty),
902 clean::Return(ref ty) => write!(f, " -> {}", ty),
903 clean::DefaultReturn => Ok(()),
908 impl fmt::Display for clean::FnDecl {
909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
911 write!(f, "({args:#}){arrow:#}", args = self.inputs, arrow = self.output)
913 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
918 impl<'a> fmt::Display for Function<'a> {
919 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
920 let &Function { decl, header_len, indent, asyncness } = self;
921 let amp = if f.alternate() { "&" } else { "&" };
922 let mut args = String::new();
923 let mut args_plain = String::new();
924 for (i, input) in decl.inputs.values.iter().enumerate() {
926 args.push_str("<br>");
929 if let Some(selfty) = input.to_self() {
931 clean::SelfValue => {
932 args.push_str("self");
933 args_plain.push_str("self");
935 clean::SelfBorrowed(Some(ref lt), mtbl) => {
936 args.push_str(&format!("{}{} {}self", amp, *lt, MutableSpace(mtbl)));
937 args_plain.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
939 clean::SelfBorrowed(None, mtbl) => {
940 args.push_str(&format!("{}{}self", amp, MutableSpace(mtbl)));
941 args_plain.push_str(&format!("&{}self", MutableSpace(mtbl)));
943 clean::SelfExplicit(ref typ) => {
945 args.push_str(&format!("self: {:#}", *typ));
947 args.push_str(&format!("self: {}", *typ));
949 args_plain.push_str(&format!("self: {:#}", *typ));
954 args.push_str(" <br>");
955 args_plain.push_str(" ");
957 if !input.name.is_empty() {
958 args.push_str(&format!("{}: ", input.name));
959 args_plain.push_str(&format!("{}: ", input.name));
963 args.push_str(&format!("{:#}", input.type_));
965 args.push_str(&input.type_.to_string());
967 args_plain.push_str(&format!("{:#}", input.type_));
969 if i + 1 < decl.inputs.values.len() {
971 args_plain.push(',');
975 let args_plain = format!("({})", args_plain);
977 let output = if let hir::IsAsync::Async = asyncness {
978 Cow::Owned(decl.sugared_async_return_type())
980 Cow::Borrowed(&decl.output)
983 let arrow_plain = format!("{:#}", &output);
984 let arrow = if f.alternate() {
985 format!("{:#}", &output)
990 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
991 let output = if declaration_len > 80 {
992 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
993 let close_pad = format!("<br>{}", " ".repeat(indent));
994 format!("({args}{close}){arrow}",
995 args = args.replace("<br>", &full_pad),
999 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1003 write!(f, "{}", output.replace("<br>", "\n"))
1005 write!(f, "{}", output)
1010 impl<'a> fmt::Display for VisSpace<'a> {
1011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013 Some(clean::Public) => f.write_str("pub "),
1014 Some(clean::Inherited) | None => Ok(()),
1015 Some(clean::Visibility::Crate) => write!(f, "pub(crate) "),
1016 Some(clean::Visibility::Restricted(did, ref path)) => {
1017 f.write_str("pub(")?;
1018 if path.segments.len() != 1
1019 || (path.segments[0].name != "self" && path.segments[0].name != "super")
1021 f.write_str("in ")?;
1023 resolved_path(f, did, path, true, false)?;
1030 impl fmt::Display for UnsafetySpace {
1031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 hir::Unsafety::Unsafe => write!(f, "unsafe "),
1034 hir::Unsafety::Normal => Ok(())
1039 impl fmt::Display for ConstnessSpace {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042 hir::Constness::Const => write!(f, "const "),
1043 hir::Constness::NotConst => Ok(())
1048 impl fmt::Display for AsyncSpace {
1049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051 hir::IsAsync::Async => write!(f, "async "),
1052 hir::IsAsync::NotAsync => Ok(()),
1057 impl fmt::Display for clean::Import {
1058 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1060 clean::Import::Simple(ref name, ref src) => {
1061 if *name == src.path.last_name() {
1062 write!(f, "use {};", *src)
1064 write!(f, "use {} as {};", *src, *name)
1067 clean::Import::Glob(ref src) => {
1068 if src.path.segments.is_empty() {
1071 write!(f, "use {}::*;", *src)
1078 impl fmt::Display for clean::ImportSource {
1079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 Some(did) => resolved_path(f, did, &self.path, true, false),
1083 for (i, seg) in self.path.segments.iter().enumerate() {
1087 write!(f, "{}", seg.name)?;
1095 impl fmt::Display for clean::TypeBinding {
1096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097 f.write_str(&self.name)?;
1099 clean::TypeBindingKind::Equality { ref ty } => {
1101 write!(f, " = {:#}", ty)?;
1103 write!(f, " = {}", ty)?;
1106 clean::TypeBindingKind::Constraint { ref bounds } => {
1107 if !bounds.is_empty() {
1109 write!(f, ": {:#}", GenericBounds(bounds))?;
1111 write!(f, ": {}", GenericBounds(bounds))?;
1120 impl fmt::Display for MutableSpace {
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123 MutableSpace(clean::Immutable) => Ok(()),
1124 MutableSpace(clean::Mutable) => write!(f, "mut "),
1129 impl fmt::Display for AbiSpace {
1130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131 let quot = if f.alternate() { "\"" } else { """ };
1133 Abi::Rust => Ok(()),
1134 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1139 impl fmt::Display for DefaultSpace {
1140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142 write!(f, "default ")
1149 crate fn display_fn(
1150 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1151 ) -> impl fmt::Display {
1152 WithFormatter(Cell::new(Some(f)))
1155 struct WithFormatter<F>(Cell<Option<F>>);
1157 impl<F> fmt::Display for WithFormatter<F>
1158 where F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161 (self.0.take()).unwrap()(f)