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