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.
11 use rustc::hir::def_id::DefId;
12 use rustc_target::spec::abi::Abi;
15 use clean::{self, PrimitiveType};
16 use core::DocAccessLevels;
17 use html::item_type::ItemType;
18 use html::render::{self, cache, CURRENT_LOCATION_KEY};
20 /// Helper to render an optional visibility with a space after it (if the
21 /// visibility is preset)
22 #[derive(Copy, Clone)]
23 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
24 /// Similarly to VisSpace, this structure is used to render a function style with a
26 #[derive(Copy, Clone)]
27 pub struct UnsafetySpace(pub hir::Unsafety);
28 /// Similarly to VisSpace, this structure is used to render a function constness
29 /// with a space after it.
30 #[derive(Copy, Clone)]
31 pub struct ConstnessSpace(pub hir::Constness);
32 /// Similarly to VisSpace, this structure is used to render a function asyncness
33 /// with a space after it.
34 #[derive(Copy, Clone)]
35 pub struct AsyncSpace(pub hir::IsAsync);
36 /// Similar to VisSpace, but used for mutability
37 #[derive(Copy, Clone)]
38 pub struct MutableSpace(pub clean::Mutability);
39 /// Similar to VisSpace, but used for mutability
40 #[derive(Copy, Clone)]
41 pub struct RawMutableSpace(pub clean::Mutability);
42 /// Wrapper struct for emitting type parameter bounds.
43 pub struct GenericBounds<'a>(pub &'a [clean::GenericBound]);
44 /// Wrapper struct for emitting a comma-separated list of items
45 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
46 pub struct AbiSpace(pub Abi);
48 /// Wrapper struct for properly emitting a function or method declaration.
49 pub struct Function<'a> {
50 /// The declaration to emit.
51 pub decl: &'a clean::FnDecl,
52 /// The length of the function's "name", used to determine line-wrapping.
54 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
56 /// Whether the function is async or not.
57 pub asyncness: hir::IsAsync,
60 /// Wrapper struct for emitting a where clause from Generics.
61 pub struct WhereClause<'a>{
62 /// The Generics from which to emit a where clause.
63 pub gens: &'a clean::Generics,
64 /// The number of spaces to indent each line with.
66 /// Whether the where clause needs to add a comma and newline after the last bound.
67 pub end_newline: bool,
75 impl<'a> VisSpace<'a> {
76 pub fn get(self) -> &'a Option<clean::Visibility> {
77 let VisSpace(v) = self; v
82 pub fn get(&self) -> hir::Unsafety {
83 let UnsafetySpace(v) = *self; v
88 pub fn get(&self) -> hir::Constness {
89 let ConstnessSpace(v) = *self; v
93 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95 for (i, item) in self.0.iter().enumerate() {
96 if i != 0 { write!(f, ", ")?; }
97 fmt::Display::fmt(item, f)?;
103 impl<'a> fmt::Display for GenericBounds<'a> {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 let &GenericBounds(bounds) = self;
106 for (i, bound) in bounds.iter().enumerate() {
110 fmt::Display::fmt(bound, f)?;
116 impl fmt::Display for clean::GenericParamDef {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
120 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
121 f.write_str(&self.name)?;
123 if !bounds.is_empty() {
125 write!(f, ": {:#}", GenericBounds(bounds))?;
127 write!(f, ": {}", GenericBounds(bounds))?;
131 if let Some(ref ty) = default {
133 write!(f, " = {:#}", ty)?;
135 write!(f, " = {}", ty)?;
145 impl fmt::Display for clean::Generics {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 let real_params = self.params
149 .filter(|p| !p.is_synthetic_type_param())
150 .collect::<Vec<_>>();
151 if real_params.is_empty() {
155 write!(f, "<{:#}>", CommaSep(&real_params))
157 write!(f, "<{}>", CommaSep(&real_params))
162 impl<'a> fmt::Display for WhereClause<'a> {
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 let &WhereClause { gens, indent, end_newline } = self;
165 if gens.where_predicates.is_empty() {
168 let mut clause = String::new();
170 clause.push_str(" where");
173 clause.push_str(" <span class=\"where fmt-newline\">where");
175 clause.push_str(" <span class=\"where\">where");
178 for (i, pred) in gens.where_predicates.iter().enumerate() {
182 clause.push_str("<br>");
186 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
189 clause.push_str(&format!("{:#}: {:#}", ty, GenericBounds(bounds)));
191 clause.push_str(&format!("{}: {}", ty, GenericBounds(bounds)));
194 &clean::WherePredicate::RegionPredicate { ref lifetime,
196 clause.push_str(&format!("{}: ", lifetime));
197 for (i, lifetime) in bounds.iter().enumerate() {
199 clause.push_str(" + ");
202 clause.push_str(&lifetime.to_string());
205 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
207 clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
209 clause.push_str(&format!("{} == {}", lhs, rhs));
214 if i < gens.where_predicates.len() - 1 || end_newline {
220 // add a space so stripping <br> tags and breaking spaces still renders properly
224 clause.push_str(" ");
229 clause.push_str("</span>");
230 let padding = " ".repeat(indent + 4);
231 clause = clause.replace("<br>", &format!("<br>{}", padding));
232 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
234 clause.insert_str(0, "<br>");
237 write!(f, "{}", clause)
241 impl fmt::Display for clean::Lifetime {
242 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
243 f.write_str(self.get_ref())?;
248 impl fmt::Display for clean::PolyTrait {
249 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250 if !self.generic_params.is_empty() {
252 write!(f, "for<{:#}> ", CommaSep(&self.generic_params))?;
254 write!(f, "for<{}> ", CommaSep(&self.generic_params))?;
258 write!(f, "{:#}", self.trait_)
260 write!(f, "{}", self.trait_)
265 impl fmt::Display for clean::GenericBound {
266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
268 clean::GenericBound::Outlives(ref lt) => {
271 clean::GenericBound::TraitBound(ref ty, modifier) => {
272 let modifier_str = match modifier {
273 hir::TraitBoundModifier::None => "",
274 hir::TraitBoundModifier::Maybe => "?",
277 write!(f, "{}{:#}", modifier_str, *ty)
279 write!(f, "{}{}", modifier_str, *ty)
286 impl fmt::Display for clean::GenericArgs {
287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
289 clean::GenericArgs::AngleBracketed {
290 ref lifetimes, ref types, ref bindings
292 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
296 f.write_str("<")?;
298 let mut comma = false;
299 for lifetime in lifetimes {
304 write!(f, "{}", *lifetime)?;
312 write!(f, "{:#}", *ty)?;
314 write!(f, "{}", *ty)?;
317 for binding in bindings {
323 write!(f, "{:#}", *binding)?;
325 write!(f, "{}", *binding)?;
331 f.write_str(">")?;
335 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
337 let mut comma = false;
344 write!(f, "{:#}", *ty)?;
346 write!(f, "{}", *ty)?;
350 if let Some(ref ty) = *output {
352 write!(f, " -> {:#}", ty)?;
354 write!(f, " -> {}", ty)?;
363 impl fmt::Display for clean::PathSegment {
364 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
365 f.write_str(&self.name)?;
367 write!(f, "{:#}", self.args)
369 write!(f, "{}", self.args)
374 impl fmt::Display for clean::Path {
375 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
380 for (i, seg) in self.segments.iter().enumerate() {
385 write!(f, "{:#}", seg)?;
387 write!(f, "{}", seg)?;
394 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
396 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
400 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
401 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
402 Some(&(ref fqp, shortty)) => {
403 (fqp, shortty, "../".repeat(loc.len()))
406 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
407 (fqp, shortty, match cache.extern_locations[&did.krate] {
408 (.., render::Remote(ref s)) => s.to_string(),
409 (.., render::Local) => "../".repeat(loc.len()),
410 (.., render::Unknown) => return None,
414 for component in &fqp[..fqp.len() - 1] {
415 url.push_str(component);
419 ItemType::Module => {
420 url.push_str(fqp.last().unwrap());
421 url.push_str("/index.html");
424 url.push_str(shortty.css_class());
426 url.push_str(fqp.last().unwrap());
427 url.push_str(".html");
430 Some((url, shortty, fqp.to_vec()))
433 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
434 /// rendering function with the necessary arguments for linking to a local path.
435 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
436 print_all: bool, use_absolute: bool) -> fmt::Result {
437 let last = path.segments.last().unwrap();
440 for seg in &path.segments[..path.segments.len() - 1] {
441 write!(w, "{}::", seg.name)?;
445 write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.args)?;
447 let path = if use_absolute {
449 Some((_, _, fqp)) => {
451 fqp[..fqp.len() - 1].join("::"),
452 HRef::new(did, fqp.last().unwrap()))
454 None => HRef::new(did, &last.name).to_string(),
457 HRef::new(did, &last.name).to_string()
459 write!(w, "{}{}", path, last.args)?;
464 fn primitive_link(f: &mut fmt::Formatter,
465 prim: clean::PrimitiveType,
466 name: &str) -> fmt::Result {
468 let mut needs_termination = false;
470 match m.primitive_locations.get(&prim) {
471 Some(&def_id) if def_id.is_local() => {
472 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
473 let len = if len == 0 {0} else {len - 1};
474 write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
477 needs_termination = true;
480 let loc = match m.extern_locations[&def_id.krate] {
481 (ref cname, _, render::Remote(ref s)) => {
482 Some((cname, s.to_string()))
484 (ref cname, _, render::Local) => {
485 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
486 Some((cname, "../".repeat(len)))
488 (.., render::Unknown) => None,
490 if let Some((cname, root)) = loc {
491 write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
495 needs_termination = true;
501 write!(f, "{}", name)?;
502 if needs_termination {
508 /// Helper to render type parameters
509 fn tybounds(w: &mut fmt::Formatter,
510 typarams: &Option<Vec<clean::GenericBound>>) -> fmt::Result {
512 Some(ref params) => {
513 for param in params {
515 fmt::Display::fmt(param, w)?;
524 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
525 HRef { did: did, text: text }
529 impl<'a> fmt::Display for HRef<'a> {
530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531 match href(self.did) {
532 Some((url, shortty, fqp)) => if !f.alternate() {
533 write!(f, "<a class=\"{}\" href=\"{}\" title=\"{} {}\">{}</a>",
534 shortty, url, shortty, fqp.join("::"), self.text)
536 write!(f, "{}", self.text)
538 _ => write!(f, "{}", self.text),
543 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt::Result {
545 clean::Generic(ref name) => {
548 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
549 if typarams.is_some() {
550 f.write_str("dyn ")?;
552 // Paths like T::Output and Self::Output should be rendered with all segments
553 resolved_path(f, did, path, is_generic, use_absolute)?;
554 tybounds(f, typarams)
556 clean::Infer => write!(f, "_"),
557 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
558 clean::BareFunction(ref decl) => {
560 write!(f, "{}{:#}fn{:#}{:#}",
561 UnsafetySpace(decl.unsafety),
563 CommaSep(&decl.generic_params),
566 write!(f, "{}{}", UnsafetySpace(decl.unsafety), AbiSpace(decl.abi))?;
567 primitive_link(f, PrimitiveType::Fn, "fn")?;
568 write!(f, "{}{}", CommaSep(&decl.generic_params), decl.decl)
571 clean::Tuple(ref typs) => {
573 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
575 primitive_link(f, PrimitiveType::Tuple, "(")?;
576 //carry f.alternate() into this display w/o branching manually
577 fmt::Display::fmt(one, f)?;
578 primitive_link(f, PrimitiveType::Tuple, ",)")
581 primitive_link(f, PrimitiveType::Tuple, "(")?;
582 fmt::Display::fmt(&CommaSep(many), f)?;
583 primitive_link(f, PrimitiveType::Tuple, ")")
587 clean::Slice(ref t) => {
588 primitive_link(f, PrimitiveType::Slice, "[")?;
589 fmt::Display::fmt(t, f)?;
590 primitive_link(f, PrimitiveType::Slice, "]")
592 clean::Array(ref t, ref n) => {
593 primitive_link(f, PrimitiveType::Array, "[")?;
594 fmt::Display::fmt(t, f)?;
595 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
597 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
598 clean::RawPointer(m, ref t) => {
600 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
602 primitive_link(f, clean::PrimitiveType::RawPointer,
603 &format!("*{}{:#}", RawMutableSpace(m), t))
605 primitive_link(f, clean::PrimitiveType::RawPointer,
606 &format!("*{}{}", RawMutableSpace(m), t))
610 primitive_link(f, clean::PrimitiveType::RawPointer,
611 &format!("*{}", RawMutableSpace(m)))?;
612 fmt::Display::fmt(t, f)
616 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
618 Some(ref l) => format!("{} ", *l),
621 let m = MutableSpace(mutability);
622 let amp = if f.alternate() {
628 clean::Slice(ref bt) => { // BorrowedRef{ ... Slice(T) } is &[T]
630 clean::Generic(_) => {
632 primitive_link(f, PrimitiveType::Slice,
633 &format!("{}{}{}[{:#}]", amp, lt, m, **bt))
635 primitive_link(f, PrimitiveType::Slice,
636 &format!("{}{}{}[{}]", amp, lt, m, **bt))
640 primitive_link(f, PrimitiveType::Slice,
641 &format!("{}{}{}[", amp, lt, m))?;
643 write!(f, "{:#}", **bt)?;
645 write!(f, "{}", **bt)?;
647 primitive_link(f, PrimitiveType::Slice, "]")
651 clean::ResolvedPath { typarams: Some(ref v), .. } if !v.is_empty() => {
652 write!(f, "{}{}{}(", amp, lt, m)?;
653 fmt_type(&ty, f, use_absolute)?;
656 clean::Generic(..) => {
657 primitive_link(f, PrimitiveType::Reference,
658 &format!("{}{}{}", amp, lt, m))?;
659 fmt_type(&ty, f, use_absolute)
662 write!(f, "{}{}{}", amp, lt, m)?;
663 fmt_type(&ty, f, use_absolute)
667 clean::ImplTrait(ref bounds) => {
668 write!(f, "impl {}", GenericBounds(bounds))
670 clean::QPath { ref name, ref self_type, ref trait_ } => {
671 let should_show_cast = match *trait_ {
672 box clean::ResolvedPath { ref path, .. } => {
673 !path.segments.is_empty() && !self_type.is_self_type()
678 if should_show_cast {
679 write!(f, "<{:#} as {:#}>::", self_type, trait_)?
681 write!(f, "{:#}::", self_type)?
684 if should_show_cast {
685 write!(f, "<{} as {}>::", self_type, trait_)?
687 write!(f, "{}::", self_type)?
691 // It's pretty unsightly to look at `<A as B>::C` in output, and
692 // we've got hyperlinking on our side, so try to avoid longer
693 // notation as much as possible by making `C` a hyperlink to trait
694 // `B` to disambiguate.
696 // FIXME: this is still a lossy conversion and there should probably
697 // be a better way of representing this in general? Most of
698 // the ugliness comes from inlining across crates where
699 // everything comes in as a fully resolved QPath (hard to
701 box clean::ResolvedPath { did, ref typarams, .. } => {
703 Some((ref url, _, ref path)) if !f.alternate() => {
705 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
706 title=\"type {path}::{name}\">{name}</a>",
708 shortty = ItemType::AssociatedType,
710 path = path.join("::"))?;
712 _ => write!(f, "{}", name)?,
715 // FIXME: `typarams` are not rendered, and this seems bad?
720 write!(f, "{}", name)
724 clean::Unique(..) => {
725 panic!("should have been cleaned")
730 impl fmt::Display for clean::Type {
731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
732 fmt_type(self, f, false)
736 fn fmt_impl(i: &clean::Impl,
737 f: &mut fmt::Formatter,
739 use_absolute: bool) -> fmt::Result {
741 write!(f, "impl{:#} ", i.generics)?;
743 write!(f, "impl{} ", i.generics)?;
746 if let Some(ref ty) = i.trait_ {
747 if i.polarity == Some(clean::ImplPolarity::Negative) {
752 fmt::Display::fmt(ty, f)?;
755 clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => {
756 let last = path.segments.last().unwrap();
757 fmt::Display::fmt(&last.name, f)?;
758 fmt::Display::fmt(&last.args, f)?;
766 if let Some(ref ty) = i.blanket_impl {
767 fmt_type(ty, f, use_absolute)?;
769 fmt_type(&i.for_, f, use_absolute)?;
772 fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?;
776 impl fmt::Display for clean::Impl {
777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
778 fmt_impl(self, f, true, false)
782 // The difference from above is that trait is not hyperlinked.
783 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
784 f: &mut fmt::Formatter,
785 use_absolute: bool) -> fmt::Result {
786 fmt_impl(i, f, false, use_absolute)
789 impl fmt::Display for clean::Arguments {
790 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
791 for (i, input) in self.values.iter().enumerate() {
792 if !input.name.is_empty() {
793 write!(f, "{}: ", input.name)?;
796 write!(f, "{:#}", input.type_)?;
798 write!(f, "{}", input.type_)?;
800 if i + 1 < self.values.len() { write!(f, ", ")?; }
806 impl fmt::Display for clean::FunctionRetTy {
807 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
809 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
810 clean::Return(ref ty) if f.alternate() => write!(f, " -> {:#}", ty),
811 clean::Return(ref ty) => write!(f, " -> {}", ty),
812 clean::DefaultReturn => Ok(()),
817 impl fmt::Display for clean::FnDecl {
818 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
821 write!(f, "({args:#}, ...){arrow:#}", args = self.inputs, arrow = self.output)
823 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
827 write!(f, "({args:#}){arrow:#}", args = self.inputs, arrow = self.output)
829 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
835 impl<'a> fmt::Display for Function<'a> {
836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 let &Function { decl, name_len, indent, asyncness } = self;
838 let amp = if f.alternate() { "&" } else { "&" };
839 let mut args = String::new();
840 let mut args_plain = String::new();
841 for (i, input) in decl.inputs.values.iter().enumerate() {
843 args.push_str("<br>");
846 if let Some(selfty) = input.to_self() {
848 clean::SelfValue => {
849 args.push_str("self");
850 args_plain.push_str("self");
852 clean::SelfBorrowed(Some(ref lt), mtbl) => {
853 args.push_str(&format!("{}{} {}self", amp, *lt, MutableSpace(mtbl)));
854 args_plain.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
856 clean::SelfBorrowed(None, mtbl) => {
857 args.push_str(&format!("{}{}self", amp, MutableSpace(mtbl)));
858 args_plain.push_str(&format!("&{}self", MutableSpace(mtbl)));
860 clean::SelfExplicit(ref typ) => {
862 args.push_str(&format!("self: {:#}", *typ));
864 args.push_str(&format!("self: {}", *typ));
866 args_plain.push_str(&format!("self: {:#}", *typ));
871 args.push_str(" <br>");
872 args_plain.push_str(" ");
874 if !input.name.is_empty() {
875 args.push_str(&format!("{}: ", input.name));
876 args_plain.push_str(&format!("{}: ", input.name));
880 args.push_str(&format!("{:#}", input.type_));
882 args.push_str(&input.type_.to_string());
884 args_plain.push_str(&format!("{:#}", input.type_));
886 if i + 1 < decl.inputs.values.len() {
888 args_plain.push(',');
893 args.push_str(",<br> ...");
894 args_plain.push_str(", ...");
897 let output = if let hir::IsAsync::Async = asyncness {
898 Cow::Owned(decl.sugared_async_return_type())
900 Cow::Borrowed(&decl.output)
903 let arrow_plain = format!("{:#}", &output);
904 let arrow = if f.alternate() {
905 format!("{:#}", &output)
910 let pad = " ".repeat(name_len);
911 let plain = format!("{pad}({args}){arrow}",
914 arrow = arrow_plain);
916 let output = if plain.len() > 80 {
917 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
918 let close_pad = format!("<br>{}", " ".repeat(indent));
919 format!("({args}{close}){arrow}",
920 args = args.replace("<br>", &full_pad),
924 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
928 write!(f, "{}", output.replace("<br>", "\n"))
930 write!(f, "{}", output)
935 impl<'a> fmt::Display for VisSpace<'a> {
936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
938 Some(clean::Public) => f.write_str("pub "),
939 Some(clean::Inherited) | None => Ok(()),
940 Some(clean::Visibility::Crate) => write!(f, "pub(crate) "),
941 Some(clean::Visibility::Restricted(did, ref path)) => {
942 f.write_str("pub(")?;
943 if path.segments.len() != 1
944 || (path.segments[0].name != "self" && path.segments[0].name != "super")
948 resolved_path(f, did, path, true, false)?;
955 impl fmt::Display for UnsafetySpace {
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
958 hir::Unsafety::Unsafe => write!(f, "unsafe "),
959 hir::Unsafety::Normal => Ok(())
964 impl fmt::Display for ConstnessSpace {
965 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
967 hir::Constness::Const => write!(f, "const "),
968 hir::Constness::NotConst => Ok(())
973 impl fmt::Display for AsyncSpace {
974 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976 hir::IsAsync::Async => write!(f, "async "),
977 hir::IsAsync::NotAsync => Ok(()),
982 impl fmt::Display for clean::Import {
983 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
985 clean::Import::Simple(ref name, ref src) => {
986 if *name == src.path.last_name() {
987 write!(f, "use {};", *src)
989 write!(f, "use {} as {};", *src, *name)
992 clean::Import::Glob(ref src) => {
993 if src.path.segments.is_empty() {
996 write!(f, "use {}::*;", *src)
1003 impl fmt::Display for clean::ImportSource {
1004 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1006 Some(did) => resolved_path(f, did, &self.path, true, false),
1008 for (i, seg) in self.path.segments.iter().enumerate() {
1012 write!(f, "{}", seg.name)?;
1020 impl fmt::Display for clean::TypeBinding {
1021 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1023 write!(f, "{} = {:#}", self.name, self.ty)
1025 write!(f, "{} = {}", self.name, self.ty)
1030 impl fmt::Display for MutableSpace {
1031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1033 MutableSpace(clean::Immutable) => Ok(()),
1034 MutableSpace(clean::Mutable) => write!(f, "mut "),
1039 impl fmt::Display for RawMutableSpace {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1042 RawMutableSpace(clean::Immutable) => write!(f, "const "),
1043 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
1048 impl fmt::Display for AbiSpace {
1049 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1050 let quot = if f.alternate() { "\"" } else { """ };
1052 Abi::Rust => Ok(()),
1053 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),