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