]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/format.rs
Linkify extern crates on rustdoc pages
[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     let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
300     let &(ref fqp, shortty) = match cache.paths.get(&did) {
301         Some(p) => p,
302         None => return None,
303     };
304     let mut url = if did.is_local() || cache.inlined.contains(&did) {
305         repeat("../").take(loc.len()).collect::<String>()
306     } else {
307         if !cache.access_levels.is_doc_reachable(did) {
308             return None
309         }
310         match cache.extern_locations[&did.krate] {
311             (_, render::Remote(ref s)) => s.to_string(),
312             (_, render::Local) => repeat("../").take(loc.len()).collect(),
313             (_, render::Unknown) => return None,
314         }
315     };
316     for component in &fqp[..fqp.len() - 1] {
317         url.push_str(component);
318         url.push_str("/");
319     }
320     match shortty {
321         ItemType::Module => {
322             url.push_str(fqp.last().unwrap());
323             url.push_str("/index.html");
324         }
325         _ => {
326             url.push_str(shortty.to_static_str());
327             url.push_str(".");
328             url.push_str(fqp.last().unwrap());
329             url.push_str(".html");
330         }
331     }
332     Some((url, shortty, fqp.to_vec()))
333 }
334
335 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
336 /// rendering function with the necessary arguments for linking to a local path.
337 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
338                  print_all: bool) -> fmt::Result {
339     let last = path.segments.last().unwrap();
340     let rel_root = match &*path.segments[0].name {
341         "self" => Some("./".to_string()),
342         _ => None,
343     };
344
345     if print_all {
346         let amt = path.segments.len() - 1;
347         match rel_root {
348             Some(mut root) => {
349                 for seg in &path.segments[..amt] {
350                     if "super" == seg.name || "self" == seg.name {
351                         write!(w, "{}::", seg.name)?;
352                     } else {
353                         root.push_str(&seg.name);
354                         root.push_str("/");
355                         write!(w, "<a class='mod'
356                                        href='{}index.html'>{}</a>::",
357                                  root,
358                                  seg.name)?;
359                     }
360                 }
361             }
362             None => {
363                 for seg in &path.segments[..amt] {
364                     write!(w, "{}::", seg.name)?;
365                 }
366             }
367         }
368     }
369     write!(w, "{}{}", HRef::new(did, &last.name), last.params)?;
370     Ok(())
371 }
372
373 fn primitive_link(f: &mut fmt::Formatter,
374                   prim: clean::PrimitiveType,
375                   name: &str) -> fmt::Result {
376     let m = cache();
377     let mut needs_termination = false;
378     match m.primitive_locations.get(&prim) {
379         Some(&LOCAL_CRATE) => {
380             let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
381             let len = if len == 0 {0} else {len - 1};
382             write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
383                    repeat("../").take(len).collect::<String>(),
384                    prim.to_url_str())?;
385             needs_termination = true;
386         }
387         Some(&cnum) => {
388             let path = &m.paths[&DefId {
389                 krate: cnum,
390                 index: CRATE_DEF_INDEX,
391             }];
392             let loc = match m.extern_locations[&cnum] {
393                 (_, render::Remote(ref s)) => Some(s.to_string()),
394                 (_, render::Local) => {
395                     let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
396                     Some(repeat("../").take(len).collect::<String>())
397                 }
398                 (_, render::Unknown) => None,
399             };
400             match loc {
401                 Some(root) => {
402                     write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
403                            root,
404                            path.0.first().unwrap(),
405                            prim.to_url_str())?;
406                     needs_termination = true;
407                 }
408                 None => {}
409             }
410         }
411         None => {}
412     }
413     write!(f, "{}", name)?;
414     if needs_termination {
415         write!(f, "</a>")?;
416     }
417     Ok(())
418 }
419
420 /// Helper to render type parameters
421 fn tybounds(w: &mut fmt::Formatter,
422             typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
423     match *typarams {
424         Some(ref params) => {
425             for param in params {
426                 write!(w, " + ")?;
427                 write!(w, "{}", *param)?;
428             }
429             Ok(())
430         }
431         None => Ok(())
432     }
433 }
434
435 impl<'a> HRef<'a> {
436     pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
437         HRef { did: did, text: text }
438     }
439 }
440
441 impl<'a> fmt::Display for HRef<'a> {
442     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443         match href(self.did) {
444             Some((url, shortty, fqp)) => {
445                 write!(f, "<a class='{}' href='{}' title='{}'>{}</a>",
446                        shortty, url, fqp.join("::"), self.text)
447             }
448             _ => write!(f, "{}", self.text),
449         }
450     }
451 }
452
453 impl fmt::Display for clean::Type {
454     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
455         match *self {
456             clean::Generic(ref name) => {
457                 f.write_str(name)
458             }
459             clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
460                 // Paths like T::Output and Self::Output should be rendered with all segments
461                 resolved_path(f, did, path, is_generic)?;
462                 tybounds(f, typarams)
463             }
464             clean::Infer => write!(f, "_"),
465             clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
466             clean::BareFunction(ref decl) => {
467                 write!(f, "{}{}fn{}{}",
468                        UnsafetySpace(decl.unsafety),
469                        match &*decl.abi {
470                            "" => " extern ".to_string(),
471                            "\"Rust\"" => "".to_string(),
472                            s => format!(" extern {} ", s)
473                        },
474                        decl.generics,
475                        decl.decl)
476             }
477             clean::Tuple(ref typs) => {
478                 match &**typs {
479                     [] => primitive_link(f, clean::PrimitiveTuple, "()"),
480                     [ref one] => {
481                         primitive_link(f, clean::PrimitiveTuple, "(")?;
482                         write!(f, "{},", one)?;
483                         primitive_link(f, clean::PrimitiveTuple, ")")
484                     }
485                     many => {
486                         primitive_link(f, clean::PrimitiveTuple, "(")?;
487                         write!(f, "{}", CommaSep(&many))?;
488                         primitive_link(f, clean::PrimitiveTuple, ")")
489                     }
490                 }
491             }
492             clean::Vector(ref t) => {
493                 primitive_link(f, clean::Slice, &format!("["))?;
494                 write!(f, "{}", t)?;
495                 primitive_link(f, clean::Slice, &format!("]"))
496             }
497             clean::FixedVector(ref t, ref s) => {
498                 primitive_link(f, clean::PrimitiveType::Array, "[")?;
499                 write!(f, "{}", t)?;
500                 primitive_link(f, clean::PrimitiveType::Array,
501                                &format!("; {}]", *s))
502             }
503             clean::Bottom => f.write_str("!"),
504             clean::RawPointer(m, ref t) => {
505                 match **t {
506                     clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
507                         primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
508                                        &format!("*{}{}", RawMutableSpace(m), t))
509                     }
510                     _ => {
511                         primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
512                                        &format!("*{}", RawMutableSpace(m)))?;
513                         write!(f, "{}", t)
514                     }
515                 }
516             }
517             clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
518                 let lt = match *l {
519                     Some(ref l) => format!("{} ", *l),
520                     _ => "".to_string(),
521                 };
522                 let m = MutableSpace(mutability);
523                 match **ty {
524                     clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
525                         match **bt {
526                             clean::Generic(_) =>
527                                 primitive_link(f, clean::Slice,
528                                     &format!("&amp;{}{}[{}]", lt, m, **bt)),
529                             _ => {
530                                 primitive_link(f, clean::Slice, &format!("&amp;{}{}[", lt, m))?;
531                                 write!(f, "{}", **bt)?;
532                                 primitive_link(f, clean::Slice, "]")
533                             }
534                         }
535                     }
536                     _ => {
537                         write!(f, "&amp;{}{}{}", lt, m, **ty)
538                     }
539                 }
540             }
541             clean::PolyTraitRef(ref bounds) => {
542                 for (i, bound) in bounds.iter().enumerate() {
543                     if i != 0 {
544                         write!(f, " + ")?;
545                     }
546                     write!(f, "{}", *bound)?;
547                 }
548                 Ok(())
549             }
550             // It's pretty unsightly to look at `<A as B>::C` in output, and
551             // we've got hyperlinking on our side, so try to avoid longer
552             // notation as much as possible by making `C` a hyperlink to trait
553             // `B` to disambiguate.
554             //
555             // FIXME: this is still a lossy conversion and there should probably
556             //        be a better way of representing this in general? Most of
557             //        the ugliness comes from inlining across crates where
558             //        everything comes in as a fully resolved QPath (hard to
559             //        look at).
560             clean::QPath {
561                 ref name,
562                 ref self_type,
563                 trait_: box clean::ResolvedPath { did, ref typarams, .. },
564             } => {
565                 write!(f, "{}::", self_type)?;
566                 let path = clean::Path::singleton(name.clone());
567                 resolved_path(f, did, &path, false)?;
568
569                 // FIXME: `typarams` are not rendered, and this seems bad?
570                 drop(typarams);
571                 Ok(())
572             }
573             clean::QPath { ref name, ref self_type, ref trait_ } => {
574                 write!(f, "&lt;{} as {}&gt;::{}", self_type, trait_, name)
575             }
576             clean::Unique(..) => {
577                 panic!("should have been cleaned")
578             }
579         }
580     }
581 }
582
583 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
584     write!(f, "impl{} ", i.generics)?;
585     if let Some(ref ty) = i.trait_ {
586         write!(f, "{}",
587                if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
588         if link_trait {
589             write!(f, "{}", *ty)?;
590         } else {
591             write!(f, "{}", ty.trait_name().unwrap())?;
592         }
593         write!(f, " for ")?;
594     }
595     write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
596     Ok(())
597 }
598
599 impl fmt::Display for clean::Impl {
600     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601         fmt_impl(self, f, true)
602     }
603 }
604
605 // The difference from above is that trait is not hyperlinked.
606 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
607     fmt_impl(i, f, false)
608 }
609
610 impl fmt::Display for clean::Arguments {
611     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
612         for (i, input) in self.values.iter().enumerate() {
613             if i > 0 { write!(f, ", ")?; }
614             if !input.name.is_empty() {
615                 write!(f, "{}: ", input.name)?;
616             }
617             write!(f, "{}", input.type_)?;
618         }
619         Ok(())
620     }
621 }
622
623 impl fmt::Display for clean::FunctionRetTy {
624     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625         match *self {
626             clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
627             clean::Return(ref ty) => write!(f, " -&gt; {}", ty),
628             clean::DefaultReturn => Ok(()),
629             clean::NoReturn => write!(f, " -&gt; !")
630         }
631     }
632 }
633
634 impl fmt::Display for clean::FnDecl {
635     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
636         if self.variadic {
637             write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
638         } else {
639             write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
640         }
641     }
642 }
643
644 impl<'a> fmt::Display for Method<'a> {
645     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646         let Method(selfty, d) = *self;
647         let mut args = String::new();
648         match *selfty {
649             clean::SelfStatic => {},
650             clean::SelfValue => args.push_str("self"),
651             clean::SelfBorrowed(Some(ref lt), mtbl) => {
652                 args.push_str(&format!("&amp;{} {}self", *lt, MutableSpace(mtbl)));
653             }
654             clean::SelfBorrowed(None, mtbl) => {
655                 args.push_str(&format!("&amp;{}self", MutableSpace(mtbl)));
656             }
657             clean::SelfExplicit(ref typ) => {
658                 args.push_str(&format!("self: {}", *typ));
659             }
660         }
661         for (i, input) in d.inputs.values.iter().enumerate() {
662             if i > 0 || !args.is_empty() { args.push_str(", "); }
663             if !input.name.is_empty() {
664                 args.push_str(&format!("{}: ", input.name));
665             }
666             args.push_str(&format!("{}", input.type_));
667         }
668         write!(f, "({args}){arrow}", args = args, arrow = d.output)
669     }
670 }
671
672 impl<'a> fmt::Display for VisSpace<'a> {
673     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674         match *self.get() {
675             Some(clean::Public) => write!(f, "pub "),
676             Some(clean::Inherited) | None => Ok(())
677         }
678     }
679 }
680
681 impl fmt::Display for UnsafetySpace {
682     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683         match self.get() {
684             hir::Unsafety::Unsafe => write!(f, "unsafe "),
685             hir::Unsafety::Normal => Ok(())
686         }
687     }
688 }
689
690 impl fmt::Display for ConstnessSpace {
691     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
692         match self.get() {
693             hir::Constness::Const => write!(f, "const "),
694             hir::Constness::NotConst => Ok(())
695         }
696     }
697 }
698
699 impl fmt::Display for clean::Import {
700     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701         match *self {
702             clean::SimpleImport(ref name, ref src) => {
703                 if *name == src.path.last_name() {
704                     write!(f, "use {};", *src)
705                 } else {
706                     write!(f, "use {} as {};", *src, *name)
707                 }
708             }
709             clean::GlobImport(ref src) => {
710                 write!(f, "use {}::*;", *src)
711             }
712             clean::ImportList(ref src, ref names) => {
713                 write!(f, "use {}::{{", *src)?;
714                 for (i, n) in names.iter().enumerate() {
715                     if i > 0 {
716                         write!(f, ", ")?;
717                     }
718                     write!(f, "{}", *n)?;
719                 }
720                 write!(f, "}};")
721             }
722         }
723     }
724 }
725
726 impl fmt::Display for clean::ImportSource {
727     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
728         match self.did {
729             Some(did) => resolved_path(f, did, &self.path, true),
730             _ => {
731                 for (i, seg) in self.path.segments.iter().enumerate() {
732                     if i > 0 {
733                         write!(f, "::")?
734                     }
735                     write!(f, "{}", seg.name)?;
736                 }
737                 Ok(())
738             }
739         }
740     }
741 }
742
743 impl fmt::Display for clean::ViewListIdent {
744     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
745         match self.source {
746             Some(did) => {
747                 let path = clean::Path::singleton(self.name.clone());
748                 resolved_path(f, did, &path, false)?;
749             }
750             _ => write!(f, "{}", self.name)?,
751         }
752
753         if let Some(ref name) = self.rename {
754             write!(f, " as {}", name)?;
755         }
756         Ok(())
757     }
758 }
759
760 impl fmt::Display for clean::TypeBinding {
761     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762         write!(f, "{}={}", self.name, self.ty)
763     }
764 }
765
766 impl fmt::Display for MutableSpace {
767     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
768         match *self {
769             MutableSpace(clean::Immutable) => Ok(()),
770             MutableSpace(clean::Mutable) => write!(f, "mut "),
771         }
772     }
773 }
774
775 impl fmt::Display for RawMutableSpace {
776     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777         match *self {
778             RawMutableSpace(clean::Immutable) => write!(f, "const "),
779             RawMutableSpace(clean::Mutable) => write!(f, "mut "),
780         }
781     }
782 }
783
784 impl fmt::Display for AbiSpace {
785     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
786         match self.0 {
787             Abi::Rust => Ok(()),
788             Abi::C => write!(f, "extern "),
789             abi => write!(f, "extern {} ", abi),
790         }
791     }
792 }