]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Fix BTreeMap example typo
[rust.git] / src / librustdoc / html / format.rs
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.
4 //
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.
10
11 //! HTML formatting module
12 //!
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.
17
18 use std::fmt;
19 use std::iter::repeat;
20
21 use rustc::middle::cstore::LOCAL_CRATE;
22 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
23 use syntax::abi::Abi;
24 use rustc::hir;
25
26 use clean;
27 use core::DocAccessLevels;
28 use html::item_type::ItemType;
29 use html::escape::Escape;
30 use html::render;
31 use html::render::{cache, CURRENT_LOCATION_KEY};
32
33 /// Helper to render an optional visibility with a space after it (if the
34 /// visibility is preset)
35 #[derive(Copy, Clone)]
36 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
37 /// Similarly to VisSpace, this structure is used to render a function style with a
38 /// space after it.
39 #[derive(Copy, Clone)]
40 pub struct UnsafetySpace(pub hir::Unsafety);
41 /// Similarly to VisSpace, this structure is used to render a function constness
42 /// with a space after it.
43 #[derive(Copy, Clone)]
44 pub struct ConstnessSpace(pub hir::Constness);
45 /// Wrapper struct for properly emitting a method declaration.
46 pub struct Method<'a>(pub &'a clean::FnDecl);
47 /// Similar to VisSpace, but used for mutability
48 #[derive(Copy, Clone)]
49 pub struct MutableSpace(pub clean::Mutability);
50 /// Similar to VisSpace, but used for mutability
51 #[derive(Copy, Clone)]
52 pub struct RawMutableSpace(pub clean::Mutability);
53 /// Wrapper struct for emitting a where clause from Generics.
54 pub struct WhereClause<'a>(pub &'a clean::Generics);
55 /// Wrapper struct for emitting type parameter bounds.
56 pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
57 /// Wrapper struct for emitting a comma-separated list of items
58 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
59 pub struct AbiSpace(pub Abi);
60
61 pub struct HRef<'a> {
62     pub did: DefId,
63     pub text: &'a str,
64 }
65
66 impl<'a> VisSpace<'a> {
67     pub fn get(self) -> &'a Option<clean::Visibility> {
68         let VisSpace(v) = self; v
69     }
70 }
71
72 impl UnsafetySpace {
73     pub fn get(&self) -> hir::Unsafety {
74         let UnsafetySpace(v) = *self; v
75     }
76 }
77
78 impl ConstnessSpace {
79     pub fn get(&self) -> hir::Constness {
80         let ConstnessSpace(v) = *self; v
81     }
82 }
83
84 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
85     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86         for (i, item) in self.0.iter().enumerate() {
87             if i != 0 { write!(f, ", ")?; }
88             write!(f, "{}", item)?;
89         }
90         Ok(())
91     }
92 }
93
94 impl<'a> fmt::Display for TyParamBounds<'a> {
95     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96         let &TyParamBounds(bounds) = self;
97         for (i, bound) in bounds.iter().enumerate() {
98             if i > 0 {
99                 f.write_str(" + ")?;
100             }
101             write!(f, "{}", *bound)?;
102         }
103         Ok(())
104     }
105 }
106
107 impl fmt::Display for clean::Generics {
108     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109         if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
110         f.write_str("&lt;")?;
111
112         for (i, life) in self.lifetimes.iter().enumerate() {
113             if i > 0 {
114                 f.write_str(",&nbsp;")?;
115             }
116             write!(f, "{}", *life)?;
117         }
118
119         if !self.type_params.is_empty() {
120             if !self.lifetimes.is_empty() {
121                 f.write_str(",&nbsp;")?;
122             }
123             for (i, tp) in self.type_params.iter().enumerate() {
124                 if i > 0 {
125                     f.write_str(",&nbsp;")?
126                 }
127                 f.write_str(&tp.name)?;
128
129                 if !tp.bounds.is_empty() {
130                     write!(f, ":&nbsp;{}", TyParamBounds(&tp.bounds))?;
131                 }
132
133                 match tp.default {
134                     Some(ref ty) => { write!(f, "&nbsp;=&nbsp;{}", ty)?; },
135                     None => {}
136                 };
137             }
138         }
139         f.write_str("&gt;")?;
140         Ok(())
141     }
142 }
143
144 impl<'a> fmt::Display for WhereClause<'a> {
145     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146         let &WhereClause(gens) = self;
147         if gens.where_predicates.is_empty() {
148             return Ok(());
149         }
150         f.write_str(" <span class='where'>where ")?;
151         for (i, pred) in gens.where_predicates.iter().enumerate() {
152             if i > 0 {
153                 f.write_str(", ")?;
154             }
155             match pred {
156                 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
157                     let bounds = bounds;
158                     write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
159                 }
160                 &clean::WherePredicate::RegionPredicate { ref lifetime,
161                                                           ref bounds } => {
162                     write!(f, "{}: ", lifetime)?;
163                     for (i, lifetime) in bounds.iter().enumerate() {
164                         if i > 0 {
165                             f.write_str(" + ")?;
166                         }
167
168                         write!(f, "{}", lifetime)?;
169                     }
170                 }
171                 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
172                     write!(f, "{} == {}", lhs, rhs)?;
173                 }
174             }
175         }
176         f.write_str("</span>")?;
177         Ok(())
178     }
179 }
180
181 impl fmt::Display for clean::Lifetime {
182     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
183         f.write_str(self.get_ref())?;
184         Ok(())
185     }
186 }
187
188 impl fmt::Display for clean::PolyTrait {
189     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190         if !self.lifetimes.is_empty() {
191             f.write_str("for&lt;")?;
192             for (i, lt) in self.lifetimes.iter().enumerate() {
193                 if i > 0 {
194                     f.write_str(", ")?;
195                 }
196                 write!(f, "{}", lt)?;
197             }
198             f.write_str("&gt; ")?;
199         }
200         write!(f, "{}", self.trait_)
201     }
202 }
203
204 impl fmt::Display for clean::TyParamBound {
205     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206         match *self {
207             clean::RegionBound(ref lt) => {
208                 write!(f, "{}", *lt)
209             }
210             clean::TraitBound(ref ty, modifier) => {
211                 let modifier_str = match modifier {
212                     hir::TraitBoundModifier::None => "",
213                     hir::TraitBoundModifier::Maybe => "?",
214                 };
215                 write!(f, "{}{}", modifier_str, *ty)
216             }
217         }
218     }
219 }
220
221 impl fmt::Display for clean::PathParameters {
222     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223         match *self {
224             clean::PathParameters::AngleBracketed {
225                 ref lifetimes, ref types, ref bindings
226             } => {
227                 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
228                     f.write_str("&lt;")?;
229                     let mut comma = false;
230                     for lifetime in lifetimes {
231                         if comma {
232                             f.write_str(",&nbsp;")?;
233                         }
234                         comma = true;
235                         write!(f, "{}", *lifetime)?;
236                     }
237                     for ty in types {
238                         if comma {
239                             f.write_str(",&nbsp;")?;
240                         }
241                         comma = true;
242                         write!(f, "{}", *ty)?;
243                     }
244                     for binding in bindings {
245                         if comma {
246                             f.write_str(",&nbsp;")?;
247                         }
248                         comma = true;
249                         write!(f, "{}", *binding)?;
250                     }
251                     f.write_str("&gt;")?;
252                 }
253             }
254             clean::PathParameters::Parenthesized { ref inputs, ref output } => {
255                 f.write_str("(")?;
256                 let mut comma = false;
257                 for ty in inputs {
258                     if comma {
259                         f.write_str(", ")?;
260                     }
261                     comma = true;
262                     write!(f, "{}", *ty)?;
263                 }
264                 f.write_str(")")?;
265                 if let Some(ref ty) = *output {
266                     f.write_str(" -&gt; ")?;
267                     write!(f, "{}", ty)?;
268                 }
269             }
270         }
271         Ok(())
272     }
273 }
274
275 impl fmt::Display for clean::PathSegment {
276     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277         f.write_str(&self.name)?;
278         write!(f, "{}", self.params)
279     }
280 }
281
282 impl fmt::Display for clean::Path {
283     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284         if self.global {
285             f.write_str("::")?
286         }
287
288         for (i, seg) in self.segments.iter().enumerate() {
289             if i > 0 {
290                 f.write_str("::")?
291             }
292             write!(f, "{}", seg)?;
293         }
294         Ok(())
295     }
296 }
297
298 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
299     let cache = cache();
300     if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
301         return None
302     }
303
304     let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
305     let &(ref fqp, shortty) = match cache.paths.get(&did) {
306         Some(p) => p,
307         None => return None,
308     };
309
310     let mut url = if did.is_local() || cache.inlined.contains(&did) {
311         repeat("../").take(loc.len()).collect::<String>()
312     } else {
313         match cache.extern_locations[&did.krate] {
314             (_, render::Remote(ref s)) => s.to_string(),
315             (_, render::Local) => repeat("../").take(loc.len()).collect(),
316             (_, render::Unknown) => return None,
317         }
318     };
319     for component in &fqp[..fqp.len() - 1] {
320         url.push_str(component);
321         url.push_str("/");
322     }
323     match shortty {
324         ItemType::Module => {
325             url.push_str(fqp.last().unwrap());
326             url.push_str("/index.html");
327         }
328         _ => {
329             url.push_str(shortty.to_static_str());
330             url.push_str(".");
331             url.push_str(fqp.last().unwrap());
332             url.push_str(".html");
333         }
334     }
335     Some((url, shortty, fqp.to_vec()))
336 }
337
338 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
339 /// rendering function with the necessary arguments for linking to a local path.
340 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
341                  print_all: bool) -> fmt::Result {
342     let last = path.segments.last().unwrap();
343     let rel_root = match &*path.segments[0].name {
344         "self" => Some("./".to_string()),
345         _ => None,
346     };
347
348     if print_all {
349         let amt = path.segments.len() - 1;
350         match rel_root {
351             Some(mut root) => {
352                 for seg in &path.segments[..amt] {
353                     if "super" == seg.name || "self" == seg.name {
354                         write!(w, "{}::", seg.name)?;
355                     } else {
356                         root.push_str(&seg.name);
357                         root.push_str("/");
358                         write!(w, "<a class='mod'
359                                        href='{}index.html'>{}</a>::",
360                                  root,
361                                  seg.name)?;
362                     }
363                 }
364             }
365             None => {
366                 for seg in &path.segments[..amt] {
367                     write!(w, "{}::", seg.name)?;
368                 }
369             }
370         }
371     }
372     write!(w, "{}{}", HRef::new(did, &last.name), last.params)?;
373     Ok(())
374 }
375
376 fn primitive_link(f: &mut fmt::Formatter,
377                   prim: clean::PrimitiveType,
378                   name: &str) -> fmt::Result {
379     let m = cache();
380     let mut needs_termination = false;
381     match m.primitive_locations.get(&prim) {
382         Some(&LOCAL_CRATE) => {
383             let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
384             let len = if len == 0 {0} else {len - 1};
385             write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
386                    repeat("../").take(len).collect::<String>(),
387                    prim.to_url_str())?;
388             needs_termination = true;
389         }
390         Some(&cnum) => {
391             let path = &m.paths[&DefId {
392                 krate: cnum,
393                 index: CRATE_DEF_INDEX,
394             }];
395             let loc = match m.extern_locations[&cnum] {
396                 (_, render::Remote(ref s)) => Some(s.to_string()),
397                 (_, render::Local) => {
398                     let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
399                     Some(repeat("../").take(len).collect::<String>())
400                 }
401                 (_, render::Unknown) => None,
402             };
403             match loc {
404                 Some(root) => {
405                     write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
406                            root,
407                            path.0.first().unwrap(),
408                            prim.to_url_str())?;
409                     needs_termination = true;
410                 }
411                 None => {}
412             }
413         }
414         None => {}
415     }
416     write!(f, "{}", name)?;
417     if needs_termination {
418         write!(f, "</a>")?;
419     }
420     Ok(())
421 }
422
423 /// Helper to render type parameters
424 fn tybounds(w: &mut fmt::Formatter,
425             typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
426     match *typarams {
427         Some(ref params) => {
428             for param in params {
429                 write!(w, " + ")?;
430                 write!(w, "{}", *param)?;
431             }
432             Ok(())
433         }
434         None => Ok(())
435     }
436 }
437
438 impl<'a> HRef<'a> {
439     pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
440         HRef { did: did, text: text }
441     }
442 }
443
444 impl<'a> fmt::Display for HRef<'a> {
445     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446         match href(self.did) {
447             Some((url, shortty, fqp)) => {
448                 write!(f, "<a class='{}' href='{}' title='{}'>{}</a>",
449                        shortty, url, fqp.join("::"), self.text)
450             }
451             _ => write!(f, "{}", self.text),
452         }
453     }
454 }
455
456 impl fmt::Display for clean::Type {
457     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458         match *self {
459             clean::Generic(ref name) => {
460                 f.write_str(name)
461             }
462             clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
463                 // Paths like T::Output and Self::Output should be rendered with all segments
464                 resolved_path(f, did, path, is_generic)?;
465                 tybounds(f, typarams)
466             }
467             clean::Infer => write!(f, "_"),
468             clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
469             clean::BareFunction(ref decl) => {
470                 write!(f, "{}{}fn{}{}",
471                        UnsafetySpace(decl.unsafety),
472                        AbiSpace(decl.abi),
473                        decl.generics,
474                        decl.decl)
475             }
476             clean::Tuple(ref typs) => {
477                 match &**typs {
478                     [] => primitive_link(f, clean::PrimitiveTuple, "()"),
479                     [ref one] => {
480                         primitive_link(f, clean::PrimitiveTuple, "(")?;
481                         write!(f, "{},", one)?;
482                         primitive_link(f, clean::PrimitiveTuple, ")")
483                     }
484                     many => {
485                         primitive_link(f, clean::PrimitiveTuple, "(")?;
486                         write!(f, "{}", CommaSep(&many))?;
487                         primitive_link(f, clean::PrimitiveTuple, ")")
488                     }
489                 }
490             }
491             clean::Vector(ref t) => {
492                 primitive_link(f, clean::Slice, &format!("["))?;
493                 write!(f, "{}", t)?;
494                 primitive_link(f, clean::Slice, &format!("]"))
495             }
496             clean::FixedVector(ref t, ref s) => {
497                 primitive_link(f, clean::PrimitiveType::Array, "[")?;
498                 write!(f, "{}", t)?;
499                 primitive_link(f, clean::PrimitiveType::Array,
500                                &format!("; {}]", Escape(s)))
501             }
502             clean::Bottom => f.write_str("!"),
503             clean::RawPointer(m, ref t) => {
504                 match **t {
505                     clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
506                         primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
507                                        &format!("*{}{}", RawMutableSpace(m), t))
508                     }
509                     _ => {
510                         primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
511                                        &format!("*{}", RawMutableSpace(m)))?;
512                         write!(f, "{}", t)
513                     }
514                 }
515             }
516             clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
517                 let lt = match *l {
518                     Some(ref l) => format!("{} ", *l),
519                     _ => "".to_string(),
520                 };
521                 let m = MutableSpace(mutability);
522                 match **ty {
523                     clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
524                         match **bt {
525                             clean::Generic(_) =>
526                                 primitive_link(f, clean::Slice,
527                                     &format!("&amp;{}{}[{}]", lt, m, **bt)),
528                             _ => {
529                                 primitive_link(f, clean::Slice, &format!("&amp;{}{}[", lt, m))?;
530                                 write!(f, "{}", **bt)?;
531                                 primitive_link(f, clean::Slice, "]")
532                             }
533                         }
534                     }
535                     _ => {
536                         write!(f, "&amp;{}{}{}", lt, m, **ty)
537                     }
538                 }
539             }
540             clean::PolyTraitRef(ref bounds) => {
541                 for (i, bound) in bounds.iter().enumerate() {
542                     if i != 0 {
543                         write!(f, " + ")?;
544                     }
545                     write!(f, "{}", *bound)?;
546                 }
547                 Ok(())
548             }
549             // It's pretty unsightly to look at `<A as B>::C` in output, and
550             // we've got hyperlinking on our side, so try to avoid longer
551             // notation as much as possible by making `C` a hyperlink to trait
552             // `B` to disambiguate.
553             //
554             // FIXME: this is still a lossy conversion and there should probably
555             //        be a better way of representing this in general? Most of
556             //        the ugliness comes from inlining across crates where
557             //        everything comes in as a fully resolved QPath (hard to
558             //        look at).
559             clean::QPath {
560                 ref name,
561                 ref self_type,
562                 trait_: box clean::ResolvedPath { did, ref typarams, .. },
563             } => {
564                 write!(f, "{}::", self_type)?;
565                 let path = clean::Path::singleton(name.clone());
566                 resolved_path(f, did, &path, false)?;
567
568                 // FIXME: `typarams` are not rendered, and this seems bad?
569                 drop(typarams);
570                 Ok(())
571             }
572             clean::QPath { ref name, ref self_type, ref trait_ } => {
573                 write!(f, "&lt;{} as {}&gt;::{}", self_type, trait_, name)
574             }
575             clean::Unique(..) => {
576                 panic!("should have been cleaned")
577             }
578         }
579     }
580 }
581
582 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
583     write!(f, "impl{} ", i.generics)?;
584     if let Some(ref ty) = i.trait_ {
585         write!(f, "{}",
586                if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
587         if link_trait {
588             write!(f, "{}", *ty)?;
589         } else {
590             match *ty {
591                 clean::ResolvedPath{ typarams: None, ref path, is_generic: false, .. } => {
592                     let last = path.segments.last().unwrap();
593                     write!(f, "{}{}", last.name, last.params)?;
594                 }
595                 _ => unreachable!(),
596             }
597         }
598         write!(f, " for ")?;
599     }
600     write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
601     Ok(())
602 }
603
604 impl fmt::Display for clean::Impl {
605     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606         fmt_impl(self, f, true)
607     }
608 }
609
610 // The difference from above is that trait is not hyperlinked.
611 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
612     fmt_impl(i, f, false)
613 }
614
615 impl fmt::Display for clean::Arguments {
616     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617         for (i, input) in self.values.iter().enumerate() {
618             if i > 0 { write!(f, ", ")?; }
619             if !input.name.is_empty() {
620                 write!(f, "{}: ", input.name)?;
621             }
622             write!(f, "{}", input.type_)?;
623         }
624         Ok(())
625     }
626 }
627
628 impl fmt::Display for clean::FunctionRetTy {
629     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630         match *self {
631             clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
632             clean::Return(ref ty) => write!(f, " -&gt; {}", ty),
633             clean::DefaultReturn => Ok(()),
634             clean::NoReturn => write!(f, " -&gt; !")
635         }
636     }
637 }
638
639 impl fmt::Display for clean::FnDecl {
640     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
641         if self.variadic {
642             write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
643         } else {
644             write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
645         }
646     }
647 }
648
649 impl<'a> fmt::Display for Method<'a> {
650     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651         let decl = self.0;
652         let mut args = String::new();
653         for (i, input) in decl.inputs.values.iter().enumerate() {
654             if i > 0 || !args.is_empty() { args.push_str(", "); }
655             if let Some(selfty) = input.to_self() {
656                 match selfty {
657                     clean::SelfValue => args.push_str("self"),
658                     clean::SelfBorrowed(Some(ref lt), mtbl) => {
659                         args.push_str(&format!("&amp;{} {}self", *lt, MutableSpace(mtbl)));
660                     }
661                     clean::SelfBorrowed(None, mtbl) => {
662                         args.push_str(&format!("&amp;{}self", MutableSpace(mtbl)));
663                     }
664                     clean::SelfExplicit(ref typ) => {
665                         args.push_str(&format!("self: {}", *typ));
666                     }
667                 }
668             } else {
669                 if !input.name.is_empty() {
670                     args.push_str(&format!("{}: ", input.name));
671                 }
672                 args.push_str(&format!("{}", input.type_));
673             }
674         }
675         write!(f, "({args}){arrow}", args = args, arrow = decl.output)
676     }
677 }
678
679 impl<'a> fmt::Display for VisSpace<'a> {
680     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
681         match *self.get() {
682             Some(clean::Public) => write!(f, "pub "),
683             Some(clean::Inherited) | None => Ok(())
684         }
685     }
686 }
687
688 impl fmt::Display for UnsafetySpace {
689     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
690         match self.get() {
691             hir::Unsafety::Unsafe => write!(f, "unsafe "),
692             hir::Unsafety::Normal => Ok(())
693         }
694     }
695 }
696
697 impl fmt::Display for ConstnessSpace {
698     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699         match self.get() {
700             hir::Constness::Const => write!(f, "const "),
701             hir::Constness::NotConst => Ok(())
702         }
703     }
704 }
705
706 impl fmt::Display for clean::Import {
707     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
708         match *self {
709             clean::SimpleImport(ref name, ref src) => {
710                 if *name == src.path.last_name() {
711                     write!(f, "use {};", *src)
712                 } else {
713                     write!(f, "use {} as {};", *src, *name)
714                 }
715             }
716             clean::GlobImport(ref src) => {
717                 write!(f, "use {}::*;", *src)
718             }
719             clean::ImportList(ref src, ref names) => {
720                 write!(f, "use {}::{{", *src)?;
721                 for (i, n) in names.iter().enumerate() {
722                     if i > 0 {
723                         write!(f, ", ")?;
724                     }
725                     write!(f, "{}", *n)?;
726                 }
727                 write!(f, "}};")
728             }
729         }
730     }
731 }
732
733 impl fmt::Display for clean::ImportSource {
734     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
735         match self.did {
736             Some(did) => resolved_path(f, did, &self.path, true),
737             _ => {
738                 for (i, seg) in self.path.segments.iter().enumerate() {
739                     if i > 0 {
740                         write!(f, "::")?
741                     }
742                     write!(f, "{}", seg.name)?;
743                 }
744                 Ok(())
745             }
746         }
747     }
748 }
749
750 impl fmt::Display for clean::ViewListIdent {
751     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752         match self.source {
753             Some(did) => {
754                 let path = clean::Path::singleton(self.name.clone());
755                 resolved_path(f, did, &path, false)?;
756             }
757             _ => write!(f, "{}", self.name)?,
758         }
759
760         if let Some(ref name) = self.rename {
761             write!(f, " as {}", name)?;
762         }
763         Ok(())
764     }
765 }
766
767 impl fmt::Display for clean::TypeBinding {
768     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769         write!(f, "{}={}", self.name, self.ty)
770     }
771 }
772
773 impl fmt::Display for MutableSpace {
774     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
775         match *self {
776             MutableSpace(clean::Immutable) => Ok(()),
777             MutableSpace(clean::Mutable) => write!(f, "mut "),
778         }
779     }
780 }
781
782 impl fmt::Display for RawMutableSpace {
783     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
784         match *self {
785             RawMutableSpace(clean::Immutable) => write!(f, "const "),
786             RawMutableSpace(clean::Mutable) => write!(f, "mut "),
787         }
788     }
789 }
790
791 impl fmt::Display for AbiSpace {
792     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
793         match self.0 {
794             Abi::Rust => Ok(()),
795             Abi::C => write!(f, "extern "),
796             abi => write!(f, "extern &quot;{}&quot; ", abi.name()),
797         }
798     }
799 }