1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! HTML formatting module
13 //! This module contains a large number of `fmt::Display` implementations for
14 //! various types in `rustdoc::clean`. These implementations all currently
15 //! assume that HTML output is desired, although it may be possible to redesign
16 //! them in the future to instead emit any format desired.
19 use std::iter::repeat;
21 use rustc::hir::def_id::DefId;
25 use clean::{self, PrimitiveType};
26 use core::DocAccessLevels;
27 use html::item_type::ItemType;
28 use html::escape::Escape;
30 use html::render::{cache, CURRENT_LOCATION_KEY};
32 /// Helper to render an optional visibility with a space after it (if the
33 /// visibility is preset)
34 #[derive(Copy, Clone)]
35 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
36 /// Similarly to VisSpace, this structure is used to render a function style with a
38 #[derive(Copy, Clone)]
39 pub struct UnsafetySpace(pub hir::Unsafety);
40 /// Similarly to VisSpace, this structure is used to render a function constness
41 /// with a space after it.
42 #[derive(Copy, Clone)]
43 pub struct ConstnessSpace(pub hir::Constness);
44 /// Similar to VisSpace, but used for mutability
45 #[derive(Copy, Clone)]
46 pub struct MutableSpace(pub clean::Mutability);
47 /// Similar to VisSpace, but used for mutability
48 #[derive(Copy, Clone)]
49 pub struct RawMutableSpace(pub clean::Mutability);
50 /// Wrapper struct for emitting type parameter bounds.
51 pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
52 /// Wrapper struct for emitting a comma-separated list of items
53 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
54 pub struct AbiSpace(pub Abi);
56 /// Wrapper struct for properly emitting a method declaration.
57 pub struct Method<'a> {
58 /// The declaration to emit.
59 pub decl: &'a clean::FnDecl,
60 /// The length of the function's "name", used to determine line-wrapping.
62 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
66 /// Wrapper struct for emitting a where clause from Generics.
67 pub struct WhereClause<'a>{
68 /// The Generics from which to emit a where clause.
69 pub gens: &'a clean::Generics,
70 /// The number of spaces to indent each line with.
72 /// Whether the where clause needs to add a comma and newline after the last bound.
73 pub end_newline: bool,
81 impl<'a> VisSpace<'a> {
82 pub fn get(self) -> &'a Option<clean::Visibility> {
83 let VisSpace(v) = self; v
88 pub fn get(&self) -> hir::Unsafety {
89 let UnsafetySpace(v) = *self; v
94 pub fn get(&self) -> hir::Constness {
95 let ConstnessSpace(v) = *self; v
99 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 for (i, item) in self.0.iter().enumerate() {
102 if i != 0 { write!(f, ", ")?; }
103 fmt::Display::fmt(item, f)?;
109 impl<'a, T: fmt::Debug> fmt::Debug for CommaSep<'a, T> {
110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 for (i, item) in self.0.iter().enumerate() {
112 if i != 0 { write!(f, ", ")?; }
113 fmt::Debug::fmt(item, f)?;
119 impl<'a> fmt::Display for TyParamBounds<'a> {
120 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121 let &TyParamBounds(bounds) = self;
122 for (i, bound) in bounds.iter().enumerate() {
126 fmt::Display::fmt(bound, f)?;
132 impl fmt::Display for clean::Generics {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
138 f.write_str("<")?;
141 for (i, life) in self.lifetimes.iter().enumerate() {
145 write!(f, "{}", *life)?;
148 if !self.type_params.is_empty() {
149 if !self.lifetimes.is_empty() {
152 for (i, tp) in self.type_params.iter().enumerate() {
156 f.write_str(&tp.name)?;
158 if !tp.bounds.is_empty() {
160 write!(f, ": {:#}", TyParamBounds(&tp.bounds))?;
162 write!(f, ": {}", TyParamBounds(&tp.bounds))?;
166 if let Some(ref ty) = tp.default {
168 write!(f, " = {:#}", ty)?;
170 write!(f, " = {}", ty)?;
178 f.write_str(">")?;
184 impl<'a> fmt::Display for WhereClause<'a> {
185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 let &WhereClause { gens, indent, end_newline } = self;
187 if gens.where_predicates.is_empty() {
190 let mut clause = String::new();
192 clause.push_str(" where");
195 clause.push_str(" <span class=\"where fmt-newline\">where");
197 clause.push_str(" <span class=\"where\">where");
200 for (i, pred) in gens.where_predicates.iter().enumerate() {
204 clause.push_str("<br>");
208 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
211 clause.push_str(&format!("{:#}: {:#}", ty, TyParamBounds(bounds)));
213 clause.push_str(&format!("{}: {}", ty, TyParamBounds(bounds)));
216 &clean::WherePredicate::RegionPredicate { ref lifetime,
218 clause.push_str(&format!("{}: ", lifetime));
219 for (i, lifetime) in bounds.iter().enumerate() {
221 clause.push_str(" + ");
224 clause.push_str(&format!("{}", lifetime));
227 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
229 clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
231 clause.push_str(&format!("{} == {}", lhs, rhs));
236 if i < gens.where_predicates.len() - 1 || end_newline {
242 //add a space so stripping <br> tags and breaking spaces still renders properly
246 clause.push_str(" ");
251 clause.push_str("</span>");
252 let padding = repeat(" ").take(indent + 4).collect::<String>();
253 clause = clause.replace("<br>", &format!("<br>{}", padding));
254 clause.insert_str(0, &repeat(" ").take(indent.saturating_sub(1))
255 .collect::<String>());
257 clause.insert_str(0, "<br>");
260 write!(f, "{}", clause)
264 impl fmt::Display for clean::Lifetime {
265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
266 f.write_str(self.get_ref())?;
271 impl fmt::Display for clean::PolyTrait {
272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
273 if !self.lifetimes.is_empty() {
275 f.write_str("for<")?;
277 f.write_str("for<")?;
279 for (i, lt) in self.lifetimes.iter().enumerate() {
283 write!(f, "{}", lt)?;
288 f.write_str("> ")?;
292 write!(f, "{:#}", self.trait_)
294 write!(f, "{}", self.trait_)
299 impl fmt::Display for clean::TyParamBound {
300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302 clean::RegionBound(ref lt) => {
305 clean::TraitBound(ref ty, modifier) => {
306 let modifier_str = match modifier {
307 hir::TraitBoundModifier::None => "",
308 hir::TraitBoundModifier::Maybe => "?",
311 write!(f, "{}{:#}", modifier_str, *ty)
313 write!(f, "{}{}", modifier_str, *ty)
320 impl fmt::Display for clean::PathParameters {
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
323 clean::PathParameters::AngleBracketed {
324 ref lifetimes, ref types, ref bindings
326 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
330 f.write_str("<")?;
332 let mut comma = false;
333 for lifetime in lifetimes {
338 write!(f, "{}", *lifetime)?;
346 write!(f, "{:#}", *ty)?;
348 write!(f, "{}", *ty)?;
351 for binding in bindings {
357 write!(f, "{:#}", *binding)?;
359 write!(f, "{}", *binding)?;
365 f.write_str(">")?;
369 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
371 let mut comma = false;
378 write!(f, "{:#}", *ty)?;
380 write!(f, "{}", *ty)?;
384 if let Some(ref ty) = *output {
386 write!(f, " -> {:#}", ty)?;
388 write!(f, " -> {}", ty)?;
397 impl fmt::Display for clean::PathSegment {
398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399 f.write_str(&self.name)?;
401 write!(f, "{:#}", self.params)
403 write!(f, "{}", self.params)
408 impl fmt::Display for clean::Path {
409 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414 for (i, seg) in self.segments.iter().enumerate() {
419 write!(f, "{:#}", seg)?;
421 write!(f, "{}", seg)?;
428 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
430 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
434 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
435 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
436 Some(&(ref fqp, shortty)) => {
437 (fqp, shortty, repeat("../").take(loc.len()).collect())
439 None => match cache.external_paths.get(&did) {
440 Some(&(ref fqp, shortty)) => {
441 (fqp, shortty, match cache.extern_locations[&did.krate] {
442 (.., render::Remote(ref s)) => s.to_string(),
443 (.., render::Local) => repeat("../").take(loc.len()).collect(),
444 (.., render::Unknown) => return None,
450 for component in &fqp[..fqp.len() - 1] {
451 url.push_str(component);
455 ItemType::Module => {
456 url.push_str(fqp.last().unwrap());
457 url.push_str("/index.html");
460 url.push_str(shortty.css_class());
462 url.push_str(fqp.last().unwrap());
463 url.push_str(".html");
466 Some((url, shortty, fqp.to_vec()))
469 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
470 /// rendering function with the necessary arguments for linking to a local path.
471 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
472 print_all: bool, use_absolute: bool, is_not_debug: bool) -> fmt::Result {
473 let empty = clean::PathSegment {
475 params: clean::PathParameters::Parenthesized {
480 let last = path.segments.last()
482 let rel_root = if path.segments.is_empty() {
485 match &*path.segments[0].name {
486 "self" => Some("./".to_string()),
492 let amt = path.segments.len() - 1;
495 for seg in &path.segments[..amt] {
496 if "super" == seg.name || "self" == seg.name || w.alternate() {
497 write!(w, "{}::", seg.name)?;
499 root.push_str(&seg.name);
502 write!(w, "<a class=\"mod\" href=\"{}index.html\">{}</a>::",
506 write!(w, "{}::", seg.name)?;
512 for seg in &path.segments[..amt] {
513 write!(w, "{}::", seg.name)?;
520 write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?;
522 write!(w, "{:?}{}", HRef::new(did, &last.name), last.params)?;
526 let path = if use_absolute {
528 Some((_, _, fqp)) => format!("{}::{}",
529 fqp[..fqp.len()-1].join("::"),
530 HRef::new(did, fqp.last()
531 .unwrap_or(&String::new()))),
532 None => format!("{}", HRef::new(did, &last.name)),
535 format!("{}", HRef::new(did, &last.name))
537 write!(w, "{}{}", path, last.params)?;
539 let path = if use_absolute {
541 Some((_, _, fqp)) => format!("{:?}::{:?}",
542 fqp[..fqp.len()-1].join("::"),
543 HRef::new(did, fqp.last()
544 .unwrap_or(&String::new()))),
545 None => format!("{:?}", HRef::new(did, &last.name)),
548 format!("{:?}", HRef::new(did, &last.name))
550 write!(w, "{}{}", path, last.params)?;
556 fn primitive_link(f: &mut fmt::Formatter,
557 prim: clean::PrimitiveType,
558 name: &str) -> fmt::Result {
560 let mut needs_termination = false;
562 match m.primitive_locations.get(&prim) {
563 Some(&def_id) if def_id.is_local() => {
564 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
565 let len = if len == 0 {0} else {len - 1};
566 write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
567 repeat("../").take(len).collect::<String>(),
569 needs_termination = true;
572 let loc = match m.extern_locations[&def_id.krate] {
573 (ref cname, _, render::Remote(ref s)) => {
574 Some((cname, s.to_string()))
576 (ref cname, _, render::Local) => {
577 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
578 Some((cname, repeat("../").take(len).collect::<String>()))
580 (.., render::Unknown) => None,
582 if let Some((cname, root)) = loc {
583 write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
587 needs_termination = true;
593 write!(f, "{}", name)?;
594 if needs_termination {
600 /// Helper to render type parameters
601 fn tybounds(w: &mut fmt::Formatter,
602 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
604 Some(ref params) => {
605 for param in params {
607 fmt::Display::fmt(param, w)?;
616 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
617 HRef { did: did, text: text }
621 impl<'a> fmt::Display for HRef<'a> {
622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
623 match href(self.did) {
624 Some((url, shortty, fqp)) => if !f.alternate() {
625 write!(f, "<a class=\"{}\" href=\"{}\" title=\"{} {}\">{}</a>",
626 shortty, url, shortty, fqp.join("::"), self.text)
628 write!(f, "{}", self.text)
630 _ => write!(f, "{}", self.text),
635 impl<'a> fmt::Debug for HRef<'a> {
636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 write!(f, "{}", self.text)
641 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool,
642 is_not_debug: bool) -> fmt::Result {
644 clean::Generic(ref name) => {
647 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
648 // Paths like T::Output and Self::Output should be rendered with all segments
649 resolved_path(f, did, path, is_generic, use_absolute, is_not_debug)?;
650 tybounds(f, typarams)
652 clean::Infer => write!(f, "_"),
653 clean::Primitive(prim) if is_not_debug => primitive_link(f, prim, prim.as_str()),
654 clean::Primitive(prim) => write!(f, "{}", prim.as_str()),
655 clean::BareFunction(ref decl) => {
657 write!(f, "{}{}fn{:#}{:#}",
658 UnsafetySpace(decl.unsafety),
663 write!(f, "{}{}fn{}{}",
664 UnsafetySpace(decl.unsafety),
670 clean::Tuple(ref typs) => {
672 &[] if is_not_debug => primitive_link(f, PrimitiveType::Tuple, "()"),
673 &[] => write!(f, "()"),
674 &[ref one] if is_not_debug => {
675 primitive_link(f, PrimitiveType::Tuple, "(")?;
676 //carry f.alternate() into this display w/o branching manually
677 fmt::Display::fmt(one, f)?;
678 primitive_link(f, PrimitiveType::Tuple, ",)")
680 &[ref one] => write!(f, "({:?},)", one),
681 many if is_not_debug => {
682 primitive_link(f, PrimitiveType::Tuple, "(")?;
683 fmt::Display::fmt(&CommaSep(&many), f)?;
684 primitive_link(f, PrimitiveType::Tuple, ")")
686 many => write!(f, "({:?})", &CommaSep(&many)),
689 clean::Vector(ref t) if is_not_debug => {
690 primitive_link(f, PrimitiveType::Slice, &format!("["))?;
691 fmt::Display::fmt(t, f)?;
692 primitive_link(f, PrimitiveType::Slice, &format!("]"))
694 clean::Vector(ref t) => write!(f, "[{:?}]", t),
695 clean::FixedVector(ref t, ref s) if is_not_debug => {
696 primitive_link(f, PrimitiveType::Array, "[")?;
697 fmt::Display::fmt(t, f)?;
699 primitive_link(f, PrimitiveType::Array,
700 &format!("; {}]", s))
702 primitive_link(f, PrimitiveType::Array,
703 &format!("; {}]", Escape(s)))
706 clean::FixedVector(ref t, ref s) => {
708 write!(f, "[{:?}; {}]", t, s)
710 write!(f, "[{:?}; {}]", t, Escape(s))
713 clean::Never => f.write_str("!"),
714 clean::RawPointer(m, ref t) => {
716 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} if is_not_debug => {
718 primitive_link(f, clean::PrimitiveType::RawPointer,
719 &format!("*{}{:#}", RawMutableSpace(m), t))
721 primitive_link(f, clean::PrimitiveType::RawPointer,
722 &format!("*{}{}", RawMutableSpace(m), t))
725 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
727 write!(f, "*{}{:#?}", RawMutableSpace(m), t)
729 write!(f, "*{}{:?}", RawMutableSpace(m), t)
732 _ if is_not_debug => {
733 primitive_link(f, clean::PrimitiveType::RawPointer,
734 &format!("*{}", RawMutableSpace(m)))?;
735 fmt::Display::fmt(t, f)
738 write!(f, "*{}{:?}", RawMutableSpace(m), t)
742 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
744 Some(ref l) => format!("{} ", *l),
747 let m = MutableSpace(mutability);
749 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
751 clean::Generic(_) if is_not_debug => {
753 primitive_link(f, PrimitiveType::Slice,
754 &format!("&{}{}[{:#}]", lt, m, **bt))
756 primitive_link(f, PrimitiveType::Slice,
757 &format!("&{}{}[{}]", lt, m, **bt))
760 clean::Generic(_) => {
762 write!(f, "&{}{}[{:#?}]", lt, m, **bt)
764 write!(f, "&{}{}[{:?}]", lt, m, **bt)
767 _ if is_not_debug => {
769 primitive_link(f, PrimitiveType::Slice,
770 &format!("&{}{}[", lt, m))?;
771 write!(f, "{:#}", **bt)?;
773 primitive_link(f, PrimitiveType::Slice,
774 &format!("&{}{}[", lt, m))?;
775 write!(f, "{}", **bt)?;
777 primitive_link(f, PrimitiveType::Slice, "]")
781 write!(f, "&{}{}[{:#?}]", lt, m, **bt)
783 write!(f, "&{}{}[{:?}]", lt, m, **bt)
790 write!(f, "&{}{}", lt, m)?;
791 fmt_type(&ty, f, use_absolute, is_not_debug)
794 write!(f, "&{}{}", lt, m)?;
796 write!(f, "&{}{}", lt, m)?;
798 fmt_type(&ty, f, use_absolute, is_not_debug)
803 clean::ImplTrait(ref bounds) => {
805 for (i, bound) in bounds.iter().enumerate() {
810 write!(f, "{:#}", *bound)?;
812 write!(f, "{}", *bound)?;
817 clean::QPath { ref name, ref self_type, ref trait_ } => {
818 let should_show_cast = match *trait_ {
819 box clean::ResolvedPath { .. } => {
820 let path = clean::Path::singleton(name.clone());
821 !path.segments.is_empty() && &format!("{:#}", trait_) != "()" &&
822 &format!("{:#}", self_type) != "Self"
828 if should_show_cast {
829 write!(f, "<{:#} as {:#}>::", self_type, trait_)?
831 write!(f, "{:#}::", self_type)?
834 if should_show_cast {
835 write!(f, "<{:#?} as {:#?}>::", self_type, trait_)?
837 write!(f, "{:#?}::", self_type)?
842 if should_show_cast {
843 write!(f, "<{} as {}>::", self_type, trait_)?
845 write!(f, "{}::", self_type)?
848 if should_show_cast {
849 write!(f, "<{:?} as {:?}>::", self_type, trait_)?
851 write!(f, "{:?}::", self_type)?
856 // It's pretty unsightly to look at `<A as B>::C` in output, and
857 // we've got hyperlinking on our side, so try to avoid longer
858 // notation as much as possible by making `C` a hyperlink to trait
859 // `B` to disambiguate.
861 // FIXME: this is still a lossy conversion and there should probably
862 // be a better way of representing this in general? Most of
863 // the ugliness comes from inlining across crates where
864 // everything comes in as a fully resolved QPath (hard to
866 box clean::ResolvedPath { did, ref typarams, .. } => {
867 let path = clean::Path::singleton(name.clone());
868 resolved_path(f, did, &path, true, use_absolute, is_not_debug)?;
870 // FIXME: `typarams` are not rendered, and this seems bad?
875 write!(f, "{}", name)
879 clean::Unique(..) => {
880 panic!("should have been cleaned")
885 impl fmt::Display for clean::Type {
886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887 fmt_type(self, f, false, true)
891 impl fmt::Debug for clean::Type {
892 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
893 fmt_type(self, f, false, false)
897 fn fmt_impl(i: &clean::Impl,
898 f: &mut fmt::Formatter,
900 use_absolute: bool) -> fmt::Result {
902 write!(f, "impl{:#} ", i.generics)?;
904 write!(f, "impl{} ", i.generics)?;
907 if let Some(ref ty) = i.trait_ {
908 if i.polarity == Some(clean::ImplPolarity::Negative) {
913 fmt::Display::fmt(ty, f)?;
916 clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => {
917 let last = path.segments.last().unwrap();
918 fmt::Display::fmt(&last.name, f)?;
919 fmt::Display::fmt(&last.params, f)?;
927 fmt_type(&i.for_, f, use_absolute, true)?;
929 fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?;
933 impl fmt::Display for clean::Impl {
934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 fmt_impl(self, f, true, false)
939 // The difference from above is that trait is not hyperlinked.
940 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
941 f: &mut fmt::Formatter,
942 use_absolute: bool) -> fmt::Result {
943 fmt_impl(i, f, false, use_absolute)
946 impl fmt::Display for clean::Arguments {
947 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
948 for (i, input) in self.values.iter().enumerate() {
949 if !input.name.is_empty() {
950 write!(f, "{}: ", input.name)?;
953 write!(f, "{:#}", input.type_)?;
955 write!(f, "{}", input.type_)?;
957 if i + 1 < self.values.len() { write!(f, ", ")?; }
963 impl fmt::Display for clean::FunctionRetTy {
964 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
966 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
967 clean::Return(ref ty) if f.alternate() => write!(f, " -> {:#}", ty),
968 clean::Return(ref ty) => write!(f, " -> {}", ty),
969 clean::DefaultReturn => Ok(()),
974 impl fmt::Display for clean::FnDecl {
975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
978 write!(f, "({args:#}, ...){arrow:#}", args = self.inputs, arrow = self.output)
980 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
984 write!(f, "({args:#}){arrow:#}", args = self.inputs, arrow = self.output)
986 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
992 impl<'a> fmt::Display for Method<'a> {
993 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
994 let &Method { decl, name_len, indent } = self;
995 let amp = if f.alternate() { "&" } else { "&" };
996 let mut args = String::new();
997 let mut args_plain = String::new();
998 for (i, input) in decl.inputs.values.iter().enumerate() {
1000 args.push_str("<br>");
1003 if let Some(selfty) = input.to_self() {
1005 clean::SelfValue => {
1006 args.push_str("self");
1007 args_plain.push_str("self");
1009 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1010 args.push_str(&format!("{}{} {}self", amp, *lt, MutableSpace(mtbl)));
1011 args_plain.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
1013 clean::SelfBorrowed(None, mtbl) => {
1014 args.push_str(&format!("{}{}self", amp, MutableSpace(mtbl)));
1015 args_plain.push_str(&format!("&{}self", MutableSpace(mtbl)));
1017 clean::SelfExplicit(ref typ) => {
1019 args.push_str(&format!("self: {:#}", *typ));
1021 args.push_str(&format!("self: {}", *typ));
1023 args_plain.push_str(&format!("self: {:#}", *typ));
1028 args.push_str(" <br>");
1029 args_plain.push_str(" ");
1031 if !input.name.is_empty() {
1032 args.push_str(&format!("{}: ", input.name));
1033 args_plain.push_str(&format!("{}: ", input.name));
1037 args.push_str(&format!("{:#}", input.type_));
1039 args.push_str(&format!("{}", input.type_));
1041 args_plain.push_str(&format!("{:#}", input.type_));
1043 if i + 1 < decl.inputs.values.len() {
1045 args_plain.push(',');
1050 args.push_str(",<br> ...");
1051 args_plain.push_str(", ...");
1054 let arrow_plain = format!("{:#}", decl.output);
1055 let arrow = if f.alternate() {
1056 format!("{:#}", decl.output)
1058 format!("{}", decl.output)
1061 let pad = repeat(" ").take(name_len).collect::<String>();
1062 let plain = format!("{pad}({args}){arrow}",
1065 arrow = arrow_plain);
1067 let output = if plain.len() > 80 {
1068 let full_pad = format!("<br>{}", repeat(" ").take(indent + 4).collect::<String>());
1069 let close_pad = format!("<br>{}", repeat(" ").take(indent).collect::<String>());
1070 format!("({args}{close}){arrow}",
1071 args = args.replace("<br>", &full_pad),
1075 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1079 write!(f, "{}", output.replace("<br>", "\n"))
1081 write!(f, "{}", output)
1086 impl<'a> fmt::Display for VisSpace<'a> {
1087 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1089 Some(clean::Public) => write!(f, "pub "),
1090 Some(clean::Inherited) | None => Ok(())
1095 impl fmt::Display for UnsafetySpace {
1096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1098 hir::Unsafety::Unsafe => write!(f, "unsafe "),
1099 hir::Unsafety::Normal => Ok(())
1104 impl fmt::Display for ConstnessSpace {
1105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1107 hir::Constness::Const => write!(f, "const "),
1108 hir::Constness::NotConst => Ok(())
1113 impl fmt::Display for clean::Import {
1114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1116 clean::Import::Simple(ref name, ref src) => {
1117 if *name == src.path.last_name() {
1118 write!(f, "use {};", *src)
1120 write!(f, "use {} as {};", *src, *name)
1123 clean::Import::Glob(ref src) => {
1124 write!(f, "use {}::*;", *src)
1130 impl fmt::Display for clean::ImportSource {
1131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1133 Some(did) => resolved_path(f, did, &self.path, true, false, true),
1135 for (i, seg) in self.path.segments.iter().enumerate() {
1139 write!(f, "{}", seg.name)?;
1147 impl fmt::Display for clean::TypeBinding {
1148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1150 write!(f, "{} = {:#}", self.name, self.ty)
1152 write!(f, "{} = {}", self.name, self.ty)
1157 impl fmt::Display for MutableSpace {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160 MutableSpace(clean::Immutable) => Ok(()),
1161 MutableSpace(clean::Mutable) => write!(f, "mut "),
1166 impl fmt::Display for RawMutableSpace {
1167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1169 RawMutableSpace(clean::Immutable) => write!(f, "const "),
1170 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
1175 impl fmt::Display for AbiSpace {
1176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1177 let quot = if f.alternate() { "\"" } else { """ };
1179 Abi::Rust => Ok(()),
1180 Abi::C => write!(f, "extern "),
1181 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),