format.rs 24.9 KB
Newer Older
1
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12
//! HTML formatting module
//!
13
//! This module contains a large number of `fmt::Display` implementations for
14 15 16 17
//! various types in `rustdoc::clean`. These implementations all currently
//! assume that HTML output is desired, although it may be possible to redesign
//! them in the future to instead emit any format desired.

18
use std::fmt;
A
Alex Crichton 已提交
19
use std::iter::repeat;
20

21
use syntax::abi::Abi;
22
use syntax::ast;
23
use syntax::ast_util;
24 25

use clean;
26
use html::item_type::ItemType;
27
use html::render;
28
use html::render::{cache, CURRENT_LOCATION_KEY};
29

30 31
/// Helper to render an optional visibility with a space after it (if the
/// visibility is preset)
32
#[derive(Copy, Clone)]
33
pub struct VisSpace(pub Option<ast::Visibility>);
34
/// Similarly to VisSpace, this structure is used to render a function style with a
35
/// space after it.
36
#[derive(Copy, Clone)]
N
Niko Matsakis 已提交
37
pub struct UnsafetySpace(pub ast::Unsafety);
38 39
/// Similarly to VisSpace, this structure is used to render a function constness
/// with a space after it.
N
Niko Matsakis 已提交
40
#[derive(Copy, Clone)]
41
pub struct ConstnessSpace(pub ast::Constness);
42
/// Wrapper struct for properly emitting a method declaration.
43
pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl);
44
/// Similar to VisSpace, but used for mutability
45
#[derive(Copy, Clone)]
46
pub struct MutableSpace(pub clean::Mutability);
47
/// Similar to VisSpace, but used for mutability
48
#[derive(Copy, Clone)]
49
pub struct RawMutableSpace(pub clean::Mutability);
50 51 52
/// Wrapper struct for emitting a where clause from Generics.
pub struct WhereClause<'a>(pub &'a clean::Generics);
/// Wrapper struct for emitting type parameter bounds.
53
pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
54 55
/// Wrapper struct for emitting a comma-separated list of items
pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
56
pub struct AbiSpace(pub Abi);
57

58
impl VisSpace {
59
    pub fn get(&self) -> Option<ast::Visibility> {
60 61 62 63
        let VisSpace(v) = *self; v
    }
}

N
Niko Matsakis 已提交
64 65 66
impl UnsafetySpace {
    pub fn get(&self) -> ast::Unsafety {
        let UnsafetySpace(v) = *self; v
67 68 69
    }
}

70 71 72 73 74 75
impl ConstnessSpace {
    pub fn get(&self) -> ast::Constness {
        let ConstnessSpace(v) = *self; v
    }
}

76
impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
77 78 79 80 81 82 83 84 85
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, item) in self.0.iter().enumerate() {
            if i != 0 { try!(write!(f, ", ")); }
            try!(write!(f, "{}", item));
        }
        Ok(())
    }
}

86
impl<'a> fmt::Display for TyParamBounds<'a> {
87 88 89 90
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let &TyParamBounds(bounds) = self;
        for (i, bound) in bounds.iter().enumerate() {
            if i > 0 {
91
                try!(f.write_str(" + "));
92 93 94 95 96 97 98
            }
            try!(write!(f, "{}", *bound));
        }
        Ok(())
    }
}

99
impl fmt::Display for clean::Generics {
100
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101
        if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
102
        try!(f.write_str("&lt;"));
103

104
        for (i, life) in self.lifetimes.iter().enumerate() {
A
Alex Crichton 已提交
105
            if i > 0 {
106
                try!(f.write_str(", "));
A
Alex Crichton 已提交
107
            }
A
Alex Crichton 已提交
108
            try!(write!(f, "{}", *life));
109 110
        }

111 112
        if !self.type_params.is_empty() {
            if !self.lifetimes.is_empty() {
113
                try!(f.write_str(", "));
A
Alex Crichton 已提交
114
            }
115
            for (i, tp) in self.type_params.iter().enumerate() {
A
Alex Crichton 已提交
116
                if i > 0 {
117
                    try!(f.write_str(", "))
A
Alex Crichton 已提交
118
                }
119
                try!(f.write_str(&tp.name));
120

121
                if !tp.bounds.is_empty() {
122
                    try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
123
                }
124 125 126 127 128

                match tp.default {
                    Some(ref ty) => { try!(write!(f, " = {}", ty)); },
                    None => {}
                };
129 130
            }
        }
131
        try!(f.write_str("&gt;"));
A
Alex Crichton 已提交
132
        Ok(())
133 134 135
    }
}

136
impl<'a> fmt::Display for WhereClause<'a> {
137 138
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let &WhereClause(gens) = self;
139
        if gens.where_predicates.is_empty() {
140 141
            return Ok(());
        }
142
        try!(f.write_str(" <span class='where'>where "));
143 144
        for (i, pred) in gens.where_predicates.iter().enumerate() {
            if i > 0 {
145
                try!(f.write_str(", "));
146
            }
147
            match pred {
J
Jared Roesch 已提交
148
                &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
149
                    let bounds = bounds;
150
                    try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
J
Jared Roesch 已提交
151
                }
152 153 154 155 156
                &clean::WherePredicate::RegionPredicate { ref lifetime,
                                                          ref bounds } => {
                    try!(write!(f, "{}: ", lifetime));
                    for (i, lifetime) in bounds.iter().enumerate() {
                        if i > 0 {
157
                            try!(f.write_str(" + "));
158 159 160 161
                        }

                        try!(write!(f, "{}", lifetime));
                    }
J
Jared Roesch 已提交
162
                }
163 164
                &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
                    try!(write!(f, "{} == {}", lhs, rhs));
165 166
                }
            }
167
        }
168
        try!(f.write_str("</span>"));
169 170 171 172
        Ok(())
    }
}

173
impl fmt::Display for clean::Lifetime {
174
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175
        try!(f.write_str(self.get_ref()));
A
Alex Crichton 已提交
176
        Ok(())
177 178 179
    }
}

180
impl fmt::Display for clean::PolyTrait {
181
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182
        if !self.lifetimes.is_empty() {
183
            try!(f.write_str("for&lt;"));
184 185
            for (i, lt) in self.lifetimes.iter().enumerate() {
                if i > 0 {
186
                    try!(f.write_str(", "));
187 188 189
                }
                try!(write!(f, "{}", lt));
            }
190
            try!(f.write_str("&gt; "));
191 192 193 194 195
        }
        write!(f, "{}", self.trait_)
    }
}

196
impl fmt::Display for clean::TyParamBound {
197 198
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
199 200 201
            clean::RegionBound(ref lt) => {
                write!(f, "{}", *lt)
            }
N
Nick Cameron 已提交
202 203 204 205 206 207
            clean::TraitBound(ref ty, modifier) => {
                let modifier_str = match modifier {
                    ast::TraitBoundModifier::None => "",
                    ast::TraitBoundModifier::Maybe => "?",
                };
                write!(f, "{}{}", modifier_str, *ty)
208 209 210 211 212
            }
        }
    }
}

213
impl fmt::Display for clean::PathParameters {
214
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215
        match *self {
216 217 218
            clean::PathParameters::AngleBracketed {
                ref lifetimes, ref types, ref bindings
            } => {
219
                if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
220
                    try!(f.write_str("&lt;"));
221
                    let mut comma = false;
222
                    for lifetime in lifetimes {
223
                        if comma {
224
                            try!(f.write_str(", "));
225 226 227
                        }
                        comma = true;
                        try!(write!(f, "{}", *lifetime));
A
Alex Crichton 已提交
228
                    }
229
                    for ty in types {
230
                        if comma {
231
                            try!(f.write_str(", "));
232 233 234 235
                        }
                        comma = true;
                        try!(write!(f, "{}", *ty));
                    }
236
                    for binding in bindings {
237 238 239 240 241 242
                        if comma {
                            try!(f.write_str(", "));
                        }
                        comma = true;
                        try!(write!(f, "{}", *binding));
                    }
243
                    try!(f.write_str("&gt;"));
244
                }
245 246
            }
            clean::PathParameters::Parenthesized { ref inputs, ref output } => {
247
                try!(f.write_str("("));
248
                let mut comma = false;
249
                for ty in inputs {
A
Alex Crichton 已提交
250
                    if comma {
251
                        try!(f.write_str(", "));
A
Alex Crichton 已提交
252
                    }
253
                    comma = true;
A
Alex Crichton 已提交
254
                    try!(write!(f, "{}", *ty));
255
                }
256
                try!(f.write_str(")"));
257
                if let Some(ref ty) = *output {
258
                    try!(f.write_str(" -&gt; "));
259 260 261 262 263 264 265 266
                    try!(write!(f, "{}", ty));
                }
            }
        }
        Ok(())
    }
}

267
impl fmt::Display for clean::PathSegment {
268
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269
        try!(f.write_str(&self.name));
270 271 272 273
        write!(f, "{}", self.params)
    }
}

274
impl fmt::Display for clean::Path {
275 276
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.global {
277
            try!(f.write_str("::"))
278 279 280 281
        }

        for (i, seg) in self.segments.iter().enumerate() {
            if i > 0 {
282
                try!(f.write_str("::"))
283
            }
284
            try!(write!(f, "{}", seg));
285
        }
A
Alex Crichton 已提交
286
        Ok(())
287 288 289
    }
}

290 291 292 293 294 295 296 297 298 299 300
pub fn href(did: ast::DefId) -> Option<(String, ItemType, Vec<String>)> {
    let cache = cache();
    let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
    let &(ref fqp, shortty) = match cache.paths.get(&did) {
        Some(p) => p,
        None => return None,
    };
    let mut url = if ast_util::is_local(did) || cache.inlined.contains(&did) {
        repeat("../").take(loc.len()).collect::<String>()
    } else {
        match cache.extern_locations[&did.krate] {
301 302 303
            (_, render::Remote(ref s)) => s.to_string(),
            (_, render::Local) => repeat("../").take(loc.len()).collect(),
            (_, render::Unknown) => return None,
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        }
    };
    for component in &fqp[..fqp.len() - 1] {
        url.push_str(component);
        url.push_str("/");
    }
    match shortty {
        ItemType::Module => {
            url.push_str(fqp.last().unwrap());
            url.push_str("/index.html");
        }
        _ => {
            url.push_str(shortty.to_static_str());
            url.push_str(".");
            url.push_str(fqp.last().unwrap());
            url.push_str(".html");
        }
    }
    Some((url, shortty, fqp.to_vec()))
}

325 326
/// Used when rendering a `ResolvedPath` structure. This invokes the `path`
/// rendering function with the necessary arguments for linking to a local path.
327
fn resolved_path(w: &mut fmt::Formatter, did: ast::DefId, path: &clean::Path,
A
Alex Crichton 已提交
328
                 print_all: bool) -> fmt::Result {
329
    let last = path.segments.last().unwrap();
330
    let rel_root = match &*path.segments[0].name {
R
Richo Healey 已提交
331
        "self" => Some("./".to_string()),
332 333
        _ => None,
    };
A
Alex Crichton 已提交
334

335 336 337
    if print_all {
        let amt = path.segments.len() - 1;
        match rel_root {
338
            Some(mut root) => {
339
                for seg in &path.segments[..amt] {
340
                    if "super" == seg.name || "self" == seg.name {
341 342
                        try!(write!(w, "{}::", seg.name));
                    } else {
343
                        root.push_str(&seg.name);
344 345 346
                        root.push_str("/");
                        try!(write!(w, "<a class='mod'
                                            href='{}index.html'>{}</a>::",
347
                                      root,
348
                                      seg.name));
A
Alex Crichton 已提交
349
                    }
350
                }
A
Alex Crichton 已提交
351
            }
352
            None => {
353
                for seg in &path.segments[..amt] {
354
                    try!(write!(w, "{}::", seg.name));
355
                }
356 357 358
            }
        }
    }
A
Alex Crichton 已提交
359

360 361
    match href(did) {
        Some((url, shortty, fqp)) => {
362
            try!(write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
363
                          shortty, url, fqp.join("::"), last.name));
364
        }
365
        _ => try!(write!(w, "{}", last.name)),
366
    }
367
    try!(write!(w, "{}", last.params));
368
    Ok(())
369 370
}

371
fn primitive_link(f: &mut fmt::Formatter,
372
                  prim: clean::PrimitiveType,
373
                  name: &str) -> fmt::Result {
374
    let m = cache();
375
    let mut needs_termination = false;
376
    match m.primitive_locations.get(&prim) {
377
        Some(&ast::LOCAL_CRATE) => {
378 379
            let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
            let len = if len == 0 {0} else {len - 1};
380
            try!(write!(f, "<a href='{}primitive.{}.html'>",
A
Alex Crichton 已提交
381
                        repeat("../").take(len).collect::<String>(),
382 383 384 385
                        prim.to_url_str()));
            needs_termination = true;
        }
        Some(&cnum) => {
386
            let path = &m.paths[&ast::DefId {
387 388
                krate: cnum,
                node: ast::CRATE_NODE_ID,
P
P1start 已提交
389
            }];
390
            let loc = match m.extern_locations[&cnum] {
391 392
                (_, render::Remote(ref s)) => Some(s.to_string()),
                (_, render::Local) => {
393
                    let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
A
Alex Crichton 已提交
394
                    Some(repeat("../").take(len).collect::<String>())
395
                }
396
                (_, render::Unknown) => None,
397 398
            };
            match loc {
399 400 401
                Some(root) => {
                    try!(write!(f, "<a href='{}{}/primitive.{}.html'>",
                                root,
A
Aaron Turon 已提交
402
                                path.0.first().unwrap(),
403
                                prim.to_url_str()));
404 405 406 407 408 409 410 411 412 413 414 415 416 417
                    needs_termination = true;
                }
                None => {}
            }
        }
        None => {}
    }
    try!(write!(f, "{}", name));
    if needs_termination {
        try!(write!(f, "</a>"));
    }
    Ok(())
}

418
/// Helper to render type parameters
A
Alex Crichton 已提交
419
fn tybounds(w: &mut fmt::Formatter,
420
            typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
421 422
    match *typarams {
        Some(ref params) => {
423
            for param in params {
A
Alex Crichton 已提交
424
                try!(write!(w, " + "));
A
Alex Crichton 已提交
425
                try!(write!(w, "{}", *param));
426
            }
A
Alex Crichton 已提交
427
            Ok(())
428
        }
A
Alex Crichton 已提交
429
        None => Ok(())
430 431 432
    }
}

433
impl fmt::Display for clean::Type {
434 435
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
436
            clean::Generic(ref name) => {
437
                f.write_str(name)
438
            }
439 440 441
            clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
                // Paths like T::Output and Self::Output should be rendered with all segments
                try!(resolved_path(f, did, path, is_generic));
442
                tybounds(f, typarams)
443
            }
444
            clean::Infer => write!(f, "_"),
445
            clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
446
            clean::BareFunction(ref decl) => {
A
Alex Crichton 已提交
447
                write!(f, "{}{}fn{}{}",
N
Niko Matsakis 已提交
448
                       UnsafetySpace(decl.unsafety),
449
                       match &*decl.abi {
450 451
                           "" => " extern ".to_string(),
                           "\"Rust\"" => "".to_string(),
A
Alex Crichton 已提交
452
                           s => format!(" extern {} ", s)
453 454
                       },
                       decl.generics,
A
Alex Crichton 已提交
455
                       decl.decl)
456 457
            }
            clean::Tuple(ref typs) => {
458
                primitive_link(f, clean::PrimitiveTuple,
459
                               &*match &**typs {
460
                                    [ref one] => format!("({},)", one),
461 462
                                    many => format!("({})", CommaSep(&many)),
                               })
463
            }
464
            clean::Vector(ref t) => {
465
                primitive_link(f, clean::Slice, &format!("[{}]", **t))
466
            }
467
            clean::FixedVector(ref t, ref s) => {
468
                primitive_link(f, clean::PrimitiveType::Array,
469
                               &format!("[{}; {}]", **t, *s))
A
Alex Crichton 已提交
470
            }
471
            clean::Bottom => f.write_str("!"),
472
            clean::RawPointer(m, ref t) => {
473 474
                primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
                               &format!("*{}{}", RawMutableSpace(m), **t))
475 476
            }
            clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
477 478
                let lt = match *l {
                    Some(ref l) => format!("{} ", *l),
479
                    _ => "".to_string(),
480
                };
481 482 483 484 485 486
                let m = MutableSpace(mutability);
                match **ty {
                    clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
                        match **bt {
                            clean::Generic(_) =>
                                primitive_link(f, clean::Slice,
487
                                    &format!("&amp;{}{}[{}]", lt, m, **bt)),
488 489
                            _ => {
                                try!(primitive_link(f, clean::Slice,
490
                                    &format!("&amp;{}{}[", lt, m)));
491 492 493 494 495 496 497 498 499
                                try!(write!(f, "{}", **bt));
                                primitive_link(f, clean::Slice, "]")
                            }
                        }
                    }
                    _ => {
                        write!(f, "&amp;{}{}{}", lt, m, **ty)
                    }
                }
500
            }
501 502 503 504 505 506 507 508 509
            clean::PolyTraitRef(ref bounds) => {
                for (i, bound) in bounds.iter().enumerate() {
                    if i != 0 {
                        try!(write!(f, " + "));
                    }
                    try!(write!(f, "{}", *bound));
                }
                Ok(())
            }
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
            // It's pretty unsightly to look at `<A as B>::C` in output, and
            // we've got hyperlinking on our side, so try to avoid longer
            // notation as much as possible by making `C` a hyperlink to trait
            // `B` to disambiguate.
            //
            // FIXME: this is still a lossy conversion and there should probably
            //        be a better way of representing this in general? Most of
            //        the ugliness comes from inlining across crates where
            //        everything comes in as a fully resolved QPath (hard to
            //        look at).
            clean::QPath {
                ref name,
                ref self_type,
                trait_: box clean::ResolvedPath { did, ref typarams, .. },
            } => {
                try!(write!(f, "{}::", self_type));
                let path = clean::Path::singleton(name.clone());
                try!(resolved_path(f, did, &path, false));

                // FIXME: `typarams` are not rendered, and this seems bad?
                drop(typarams);
                Ok(())
            }
T
Tom Jakubowski 已提交
533 534 535
            clean::QPath { ref name, ref self_type, ref trait_ } => {
                write!(f, "&lt;{} as {}&gt;::{}", self_type, trait_, name)
            }
E
Eduard Burtescu 已提交
536
            clean::Unique(..) => {
S
Steve Klabnik 已提交
537
                panic!("should have been cleaned")
A
Alex Crichton 已提交
538
            }
539 540 541 542
        }
    }
}

W
William Throwe 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555
impl fmt::Display for clean::Impl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "impl{} ", self.generics));
        if let Some(ref ty) = self.trait_ {
            try!(write!(f, "{}{} for ",
                        if self.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" },
                        *ty));
        }
        try!(write!(f, "{}{}", self.for_, WhereClause(&self.generics)));
        Ok(())
    }
}

556
impl fmt::Display for clean::Arguments {
557 558
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, input) in self.values.iter().enumerate() {
A
Alex Crichton 已提交
559
            if i > 0 { try!(write!(f, ", ")); }
560
            if !input.name.is_empty() {
A
Alex Crichton 已提交
561
                try!(write!(f, "{}: ", input.name));
562
            }
A
Alex Crichton 已提交
563
            try!(write!(f, "{}", input.type_));
564 565 566 567 568
        }
        Ok(())
    }
}

569
impl fmt::Display for clean::FunctionRetTy {
570 571 572 573
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
            clean::Return(ref ty) => write!(f, " -&gt; {}", ty),
574
            clean::DefaultReturn => Ok(()),
575 576 577 578 579
            clean::NoReturn => write!(f, " -&gt; !")
        }
    }
}

580
impl fmt::Display for clean::FnDecl {
581
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
582
        write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
K
klutzy 已提交
583 584 585
    }
}

586
impl<'a> fmt::Display for Method<'a> {
587 588
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Method(selfty, d) = *self;
589
        let mut args = String::new();
590 591 592
        match *selfty {
            clean::SelfStatic => {},
            clean::SelfValue => args.push_str("self"),
593
            clean::SelfBorrowed(Some(ref lt), mtbl) => {
594
                args.push_str(&format!("&amp;{} {}self", *lt, MutableSpace(mtbl)));
595
            }
596
            clean::SelfBorrowed(None, mtbl) => {
597
                args.push_str(&format!("&amp;{}self", MutableSpace(mtbl)));
598
            }
599
            clean::SelfExplicit(ref typ) => {
600
                args.push_str(&format!("self: {}", *typ));
601
            }
602
        }
603
        for (i, input) in d.inputs.values.iter().enumerate() {
604 605
            if i > 0 || !args.is_empty() { args.push_str(", "); }
            if !input.name.is_empty() {
606
                args.push_str(&format!("{}: ", input.name));
607
            }
608
            args.push_str(&format!("{}", input.type_));
609
        }
610
        write!(f, "({args}){arrow}", args = args, arrow = d.output)
611 612 613
    }
}

614
impl fmt::Display for VisSpace {
615 616
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.get() {
A
Alex Crichton 已提交
617
            Some(ast::Public) => write!(f, "pub "),
A
Alex Crichton 已提交
618
            Some(ast::Inherited) | None => Ok(())
619 620 621
        }
    }
}
622

623
impl fmt::Display for UnsafetySpace {
624 625
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.get() {
N
Niko Matsakis 已提交
626 627
            ast::Unsafety::Unsafe => write!(f, "unsafe "),
            ast::Unsafety::Normal => Ok(())
628 629 630
        }
    }
}
A
Alex Crichton 已提交
631

632 633 634 635 636 637 638 639 640
impl fmt::Display for ConstnessSpace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.get() {
            ast::Constness::Const => write!(f, "const "),
            ast::Constness::NotConst => Ok(())
        }
    }
}

641
impl fmt::Display for clean::Import {
642 643
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
A
Alex Crichton 已提交
644
            clean::SimpleImport(ref name, ref src) => {
645
                if *name == src.path.segments.last().unwrap().name {
A
Alex Crichton 已提交
646
                    write!(f, "use {};", *src)
A
Alex Crichton 已提交
647
                } else {
648
                    write!(f, "use {} as {};", *src, *name)
A
Alex Crichton 已提交
649 650 651
                }
            }
            clean::GlobImport(ref src) => {
A
Alex Crichton 已提交
652
                write!(f, "use {}::*;", *src)
A
Alex Crichton 已提交
653 654
            }
            clean::ImportList(ref src, ref names) => {
655
                try!(write!(f, "use {}::{{", *src));
A
Alex Crichton 已提交
656
                for (i, n) in names.iter().enumerate() {
A
Alex Crichton 已提交
657
                    if i > 0 {
A
Alex Crichton 已提交
658
                        try!(write!(f, ", "));
A
Alex Crichton 已提交
659
                    }
A
Alex Crichton 已提交
660
                    try!(write!(f, "{}", *n));
A
Alex Crichton 已提交
661
                }
662
                write!(f, "}};")
A
Alex Crichton 已提交
663 664 665 666 667
            }
        }
    }
}

668
impl fmt::Display for clean::ImportSource {
669 670
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.did {
A
Alex Crichton 已提交
671
            Some(did) => resolved_path(f, did, &self.path, true),
A
Alex Crichton 已提交
672
            _ => {
673
                for (i, seg) in self.path.segments.iter().enumerate() {
A
Alex Crichton 已提交
674
                    if i > 0 {
A
Alex Crichton 已提交
675
                        try!(write!(f, "::"))
A
Alex Crichton 已提交
676
                    }
A
Alex Crichton 已提交
677
                    try!(write!(f, "{}", seg.name));
A
Alex Crichton 已提交
678
                }
A
Alex Crichton 已提交
679
                Ok(())
A
Alex Crichton 已提交
680 681 682 683 684
            }
        }
    }
}

685
impl fmt::Display for clean::ViewListIdent {
686 687
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.source {
688
            Some(did) => {
689
                let path = clean::Path::singleton(self.name.clone());
690
                try!(resolved_path(f, did, &path, false));
A
Alex Crichton 已提交
691
            }
692 693 694 695 696
            _ => try!(write!(f, "{}", self.name)),
        }

        if let Some(ref name) = self.rename {
            try!(write!(f, " as {}", name));
A
Alex Crichton 已提交
697
        }
698
        Ok(())
A
Alex Crichton 已提交
699 700
    }
}
701

702
impl fmt::Display for clean::TypeBinding {
703 704 705 706 707
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}={}", self.name, self.ty)
    }
}

708
impl fmt::Display for MutableSpace {
709 710 711 712 713 714 715
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MutableSpace(clean::Immutable) => Ok(()),
            MutableSpace(clean::Mutable) => write!(f, "mut "),
        }
    }
}
716

717
impl fmt::Display for RawMutableSpace {
718 719 720 721 722 723 724 725
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            RawMutableSpace(clean::Immutable) => write!(f, "const "),
            RawMutableSpace(clean::Mutable) => write!(f, "mut "),
        }
    }
}

726 727 728 729 730 731 732 733 734
impl fmt::Display for AbiSpace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            Abi::Rust => Ok(()),
            Abi::C => write!(f, "extern "),
            abi => write!(f, "extern {} ", abi),
        }
    }
}