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