print.rs 88.2 KB
Newer Older
1
use rustc_target::spec::abi::Abi;
2
use syntax::ast;
D
Donato Sciarra 已提交
3
use syntax::source_map::{SourceMap, Spanned};
4
use syntax::parse::ParseSess;
5
use syntax::parse::lexer::comments;
6
use syntax::print::pp::{self, Breaks};
7
use syntax::print::pp::Breaks::{Consistent, Inconsistent};
8
use syntax::print::pprust::PrintState;
9
use syntax::ptr::P;
10
use syntax::symbol::keywords;
11
use syntax::util::parser::{self, AssocOp, Fixity};
12
use syntax_pos::{self, BytePos, FileName};
13

M
Mark Mansi 已提交
14 15 16
use crate::hir;
use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
use crate::hir::{GenericParam, GenericParamKind, GenericArg};
17

18
use std::borrow::Cow;
19
use std::cell::Cell;
20
use std::io::{self, Write, Read};
21 22
use std::iter::Peekable;
use std::vec;
23 24

pub enum AnnNode<'a> {
V
varkor 已提交
25 26 27
    Name(&'a ast::Name),
    Block(&'a hir::Block),
    Item(&'a hir::Item),
L
ljedrz 已提交
28
    SubItem(hir::HirId),
V
varkor 已提交
29 30
    Expr(&'a hir::Expr),
    Pat(&'a hir::Pat),
31 32
}

33 34 35 36 37 38 39 40
pub enum Nested {
    Item(hir::ItemId),
    TraitItem(hir::TraitItemId),
    ImplItem(hir::ImplItemId),
    Body(hir::BodyId),
    BodyArgPat(hir::BodyId, usize)
}

41
pub trait PpAnn {
42
    fn nested(&self, _state: &mut State<'_>, _nested: Nested) -> io::Result<()> {
43 44
        Ok(())
    }
45
    fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
N
Nick Cameron 已提交
46 47
        Ok(())
    }
48
    fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
N
Nick Cameron 已提交
49 50
        Ok(())
    }
51 52 53
    fn try_fetch_item(&self, _: ast::NodeId) -> Option<&hir::Item> {
        None
    }
54 55 56 57
}

pub struct NoAnn;
impl PpAnn for NoAnn {}
58
pub const NO_ANN: &dyn PpAnn = &NoAnn;
59 60

impl PpAnn for hir::Crate {
61 62 63
    fn try_fetch_item(&self, item: ast::NodeId) -> Option<&hir::Item> {
        Some(self.item(item))
    }
64
    fn nested(&self, state: &mut State<'_>, nested: Nested) -> io::Result<()> {
65 66 67 68 69 70 71 72 73
        match nested {
            Nested::Item(id) => state.print_item(self.item(id.id)),
            Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
            Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
            Nested::Body(id) => state.print_expr(&self.body(id).value),
            Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
        }
    }
}
74 75 76

pub struct State<'a> {
    pub s: pp::Printer<'a>,
D
Donato Sciarra 已提交
77
    cm: Option<&'a SourceMap>,
78
    comments: Option<Vec<comments::Comment>>,
79 80
    literals: Peekable<vec::IntoIter<comments::Literal>>,
    cur_cmnt: usize,
81
    boxes: Vec<pp::Breaks>,
M
Manish Goregaokar 已提交
82
    ann: &'a (dyn PpAnn + 'a),
83 84
}

85 86 87 88 89 90 91 92 93 94 95 96 97
impl<'a> PrintState<'a> for State<'a> {
    fn writer(&mut self) -> &mut pp::Printer<'a> {
        &mut self.s
    }

    fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
        &mut self.boxes
    }

    fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
        &mut self.comments
    }

98 99
    fn cur_cmnt(&mut self) -> &mut usize {
        &mut self.cur_cmnt
100 101
    }

102 103 104 105 106 107
    fn cur_lit(&mut self) -> Option<&comments::Literal> {
        self.literals.peek()
    }

    fn bump_lit(&mut self) -> Option<comments::Literal> {
        self.literals.next()
108 109 110
    }
}

111 112 113 114 115 116 117 118 119 120
#[allow(non_upper_case_globals)]
pub const indent_unit: usize = 4;

#[allow(non_upper_case_globals)]
pub const default_columns: usize = 78;


/// Requires you to pass an input filename and reader so that
/// it can scan the input text for comments and literals to
/// copy forward.
D
Donato Sciarra 已提交
121
pub fn print_crate<'a>(cm: &'a SourceMap,
122
                       sess: &ParseSess,
123
                       krate: &hir::Crate,
124
                       filename: FileName,
M
Manish Goregaokar 已提交
125 126 127
                       input: &mut dyn Read,
                       out: Box<dyn Write + 'a>,
                       ann: &'a dyn PpAnn,
N
Nick Cameron 已提交
128 129
                       is_expanded: bool)
                       -> io::Result<()> {
130
    let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
131 132 133 134

    // When printing the AST, we sometimes need to inject `#[no_std]` here.
    // Since you can't compile the HIR, it's not necessary.

J
Jorge Aparicio 已提交
135 136
    s.print_mod(&krate.module, &krate.attrs)?;
    s.print_remaining_comments()?;
137
    s.s.eof()
138 139 140
}

impl<'a> State<'a> {
D
Donato Sciarra 已提交
141
    pub fn new_from_input(cm: &'a SourceMap,
142
                          sess: &ParseSess,
143
                          filename: FileName,
M
Manish Goregaokar 已提交
144 145 146
                          input: &mut dyn Read,
                          out: Box<dyn Write + 'a>,
                          ann: &'a dyn PpAnn,
147
                          is_expanded: bool)
N
Nick Cameron 已提交
148
                          -> State<'a> {
149
        let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
N
Nick Cameron 已提交
150 151 152 153 154 155 156 157 158 159 160 161

        State::new(cm,
                   out,
                   ann,
                   Some(cmnts),
                   // If the code is post expansion, don't use the table of
                   // literals, since it doesn't correspond with the literals
                   // in the AST anymore.
                   if is_expanded {
                       None
                   } else {
                       Some(lits)
162
                   })
163 164
    }

D
Donato Sciarra 已提交
165
    pub fn new(cm: &'a SourceMap,
M
Manish Goregaokar 已提交
166 167
               out: Box<dyn Write + 'a>,
               ann: &'a dyn PpAnn,
168
               comments: Option<Vec<comments::Comment>>,
169
               literals: Option<Vec<comments::Literal>>)
N
Nick Cameron 已提交
170
               -> State<'a> {
171 172 173
        State {
            s: pp::mk_printer(out, default_columns),
            cm: Some(cm),
S
Shotaro Yamada 已提交
174
            comments,
175 176
            literals: literals.unwrap_or_default().into_iter().peekable(),
            cur_cmnt: 0,
177
            boxes: Vec::new(),
178
            ann,
179 180 181 182
        }
    }
}

M
Manish Goregaokar 已提交
183
pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
184
    where F: FnOnce(&mut State<'_>) -> io::Result<()>
185 186 187
{
    let mut wr = Vec::new();
    {
188 189 190 191
        let mut printer = State {
            s: pp::mk_printer(Box::new(&mut wr), default_columns),
            cm: None,
            comments: None,
192 193
            literals: vec![].into_iter().peekable(),
            cur_cmnt: 0,
194
            boxes: Vec::new(),
195
            ann,
196
        };
197
        f(&mut printer).unwrap();
198
        printer.s.eof().unwrap();
199 200 201 202
    }
    String::from_utf8(wr).unwrap()
}

203
pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility, w: S) -> String {
204 205
    to_string(NO_ANN, |s| {
        s.print_visibility(vis)?;
206
        s.s.word(w)
207 208 209 210 211 212
    })
}

impl<'a> State<'a> {
    pub fn cbox(&mut self, u: usize) -> io::Result<()> {
        self.boxes.push(pp::Breaks::Consistent);
213
        self.s.cbox(u)
214 215
    }

N
Nick Cameron 已提交
216
    pub fn nbsp(&mut self) -> io::Result<()> {
217
        self.s.word(" ")
N
Nick Cameron 已提交
218
    }
219

220
    pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
221
        self.s.word(w)?;
222 223 224
        self.nbsp()
    }

225 226
    pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
        let w = w.into();
227
        // outer-box is consistent
J
Jorge Aparicio 已提交
228
        self.cbox(indent_unit)?;
229
        // head-box is inconsistent
J
Jorge Aparicio 已提交
230
        self.ibox(w.len() + 1)?;
231 232
        // keyword that starts the head
        if !w.is_empty() {
J
Jorge Aparicio 已提交
233
            self.word_nbsp(w)?;
234 235 236 237 238
        }
        Ok(())
    }

    pub fn bopen(&mut self) -> io::Result<()> {
239
        self.s.word("{")?;
240 241 242
        self.end() // close the head-box
    }

243
    pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
244 245
        self.bclose_maybe_open(span, indented, true)
    }
L
ljedrz 已提交
246

N
Nick Cameron 已提交
247
    pub fn bclose_maybe_open(&mut self,
248
                             span: syntax_pos::Span,
N
Nick Cameron 已提交
249 250 251
                             indented: usize,
                             close_box: bool)
                             -> io::Result<()> {
252
        self.maybe_print_comment(span.hi())?;
J
Jorge Aparicio 已提交
253
        self.break_offset_if_not_bol(1, -(indented as isize))?;
254
        self.s.word("}")?;
255
        if close_box {
J
Jorge Aparicio 已提交
256
            self.end()?; // close the outer-box
257 258 259
        }
        Ok(())
    }
L
ljedrz 已提交
260

261
    pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
262 263 264 265 266 267
        self.bclose_(span, indent_unit)
    }

    pub fn in_cbox(&self) -> bool {
        match self.boxes.last() {
            Some(&last_box) => last_box == pp::Breaks::Consistent,
N
Nick Cameron 已提交
268
            None => false,
269 270
        }
    }
L
ljedrz 已提交
271

272
    pub fn space_if_not_bol(&mut self) -> io::Result<()> {
N
Nick Cameron 已提交
273
        if !self.is_bol() {
274
            self.s.space()?;
N
Nick Cameron 已提交
275
        }
276 277
        Ok(())
    }
L
ljedrz 已提交
278

N
Nick Cameron 已提交
279
    pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
280
        if !self.is_bol() {
281
            self.s.break_offset(n, off)
282 283 284 285 286
        } else {
            if off != 0 && self.s.last_token().is_hardbreak_tok() {
                // We do something pretty sketchy here: tuck the nonzero
                // offset-adjustment we were going to deposit along with the
                // break into the previous hardbreak.
287
                self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
288 289 290 291 292 293 294 295
            }
            Ok(())
        }
    }

    // Synthesizes a comment that was not textually present in the original source
    // file.
    pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
296 297
        self.s.word("/*")?;
        self.s.space()?;
298
        self.s.word(text)?;
299 300
        self.s.space()?;
        self.s.word("*/")
301 302 303 304 305 306
    }

    pub fn commasep_cmnt<T, F, G>(&mut self,
                                  b: Breaks,
                                  elts: &[T],
                                  mut op: F,
N
Nick Cameron 已提交
307 308
                                  mut get_span: G)
                                  -> io::Result<()>
309
        where F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
310
              G: FnMut(&T) -> syntax_pos::Span
311
    {
J
Jorge Aparicio 已提交
312
        self.rbox(0, b)?;
313 314 315
        let len = elts.len();
        let mut i = 0;
        for elt in elts {
316
            self.maybe_print_comment(get_span(elt).hi())?;
J
Jorge Aparicio 已提交
317
            op(self, elt)?;
318 319
            i += 1;
            if i < len {
320
                self.s.word(",")?;
321
                self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
J
Jorge Aparicio 已提交
322
                self.space_if_not_bol()?;
323 324 325 326 327
            }
        }
        self.end()
    }

328
    pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
329
        self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
330 331
    }

N
Nick Cameron 已提交
332
    pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
J
Jorge Aparicio 已提交
333
        self.print_inner_attributes(attrs)?;
334
        for &item_id in &_mod.item_ids {
335
            self.ann.nested(self, Nested::Item(item_id))?;
336 337 338 339
        }
        Ok(())
    }

N
Nick Cameron 已提交
340 341 342 343
    pub fn print_foreign_mod(&mut self,
                             nmod: &hir::ForeignMod,
                             attrs: &[ast::Attribute])
                             -> io::Result<()> {
J
Jorge Aparicio 已提交
344
        self.print_inner_attributes(attrs)?;
345
        for item in &nmod.items {
J
Jorge Aparicio 已提交
346
            self.print_foreign_item(item)?;
347 348 349 350
        }
        Ok(())
    }

351 352 353
    pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
        if !lifetime.is_elided() {
            self.print_lifetime(lifetime)?;
J
Jorge Aparicio 已提交
354
            self.nbsp()?;
355 356 357 358 359
        }
        Ok(())
    }

    pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
360
        self.maybe_print_comment(ty.span.lo())?;
J
Jorge Aparicio 已提交
361
        self.ibox(0)?;
362
        match ty.node {
C
TyKind  
csmoe 已提交
363
            hir::TyKind::Slice(ref ty) => {
364
                self.s.word("[")?;
J
Jorge Aparicio 已提交
365
                self.print_type(&ty)?;
366
                self.s.word("]")?;
367
            }
C
TyKind  
csmoe 已提交
368
            hir::TyKind::Ptr(ref mt) => {
369
                self.s.word("*")?;
370
                match mt.mutbl {
J
Jorge Aparicio 已提交
371 372
                    hir::MutMutable => self.word_nbsp("mut")?,
                    hir::MutImmutable => self.word_nbsp("const")?,
373
                }
J
Jorge Aparicio 已提交
374
                self.print_type(&mt.ty)?;
375
            }
C
TyKind  
csmoe 已提交
376
            hir::TyKind::Rptr(ref lifetime, ref mt) => {
377
                self.s.word("&")?;
J
Jorge Aparicio 已提交
378 379
                self.print_opt_lifetime(lifetime)?;
                self.print_mt(mt)?;
380
            }
C
TyKind  
csmoe 已提交
381
            hir::TyKind::Never => {
382
                self.s.word("!")?;
383
            },
C
TyKind  
csmoe 已提交
384
            hir::TyKind::Tup(ref elts) => {
J
Jorge Aparicio 已提交
385 386
                self.popen()?;
                self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
387
                if elts.len() == 1 {
388
                    self.s.word(",")?;
389
                }
J
Jorge Aparicio 已提交
390
                self.pclose()?;
391
            }
C
TyKind  
csmoe 已提交
392
            hir::TyKind::BareFn(ref f) => {
393
                self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
394
                                 &f.arg_names[..])?;
395
            }
396
            hir::TyKind::Def(..) => {},
C
TyKind  
csmoe 已提交
397
            hir::TyKind::Path(ref qpath) => {
398
                self.print_qpath(qpath, false)?
399
            }
C
TyKind  
csmoe 已提交
400
            hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
401 402 403 404 405
                let mut first = true;
                for bound in bounds {
                    if first {
                        first = false;
                    } else {
406
                        self.nbsp()?;
407 408 409 410 411
                        self.word_space("+")?;
                    }
                    self.print_poly_trait_ref(bound)?;
                }
                if !lifetime.is_elided() {
412
                    self.nbsp()?;
413 414 415
                    self.word_space("+")?;
                    self.print_lifetime(lifetime)?;
                }
416
            }
C
TyKind  
csmoe 已提交
417
            hir::TyKind::Array(ref ty, ref length) => {
418
                self.s.word("[")?;
J
Jorge Aparicio 已提交
419
                self.print_type(&ty)?;
420
                self.s.word("; ")?;
421
                self.print_anon_const(length)?;
422
                self.s.word("]")?;
423
            }
C
TyKind  
csmoe 已提交
424
            hir::TyKind::Typeof(ref e) => {
425
                self.s.word("typeof(")?;
426
                self.print_anon_const(e)?;
427
                self.s.word(")")?;
428
            }
C
TyKind  
csmoe 已提交
429
            hir::TyKind::Infer => {
430
                self.s.word("_")?;
431
            }
C
TyKind  
csmoe 已提交
432
            hir::TyKind::Err => {
433 434 435
                self.popen()?;
                self.s.word("/*ERROR*/")?;
                self.pclose()?;
436
            }
437 438 439
            hir::TyKind::CVarArgs(_) => {
                self.s.word("...")?;
            }
440 441 442 443
        }
        self.end()
    }

N
Nick Cameron 已提交
444
    pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
J
Jorge Aparicio 已提交
445
        self.hardbreak_if_not_bol()?;
446
        self.maybe_print_comment(item.span.lo())?;
J
Jorge Aparicio 已提交
447
        self.print_outer_attributes(&item.attrs)?;
448
        match item.node {
C
csmoe 已提交
449
            hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
J
Jorge Aparicio 已提交
450 451
                self.head("")?;
                self.print_fn(decl,
452 453 454 455 456 457
                              hir::FnHeader {
                                  unsafety: hir::Unsafety::Normal,
                                  constness: hir::Constness::NotConst,
                                  abi: Abi::Rust,
                                  asyncness: hir::IsAsync::NotAsync,
                              },
458
                              Some(item.ident.name),
J
Jorge Aparicio 已提交
459
                              generics,
460 461 462
                              &item.vis,
                              arg_names,
                              None)?;
J
Jorge Aparicio 已提交
463
                self.end()?; // end head-ibox
464
                self.s.word(";")?;
465 466
                self.end() // end the outer fn box
            }
C
csmoe 已提交
467
            hir::ForeignItemKind::Static(ref t, m) => {
468
                self.head(visibility_qualified(&item.vis, "static"))?;
469
                if m {
J
Jorge Aparicio 已提交
470
                    self.word_space("mut")?;
471
                }
472
                self.print_ident(item.ident)?;
J
Jorge Aparicio 已提交
473 474
                self.word_space(":")?;
                self.print_type(&t)?;
475
                self.s.word(";")?;
J
Jorge Aparicio 已提交
476
                self.end()?; // end the head-ibox
P
Paul Lietar 已提交
477 478
                self.end() // end the outer cbox
            }
C
csmoe 已提交
479
            hir::ForeignItemKind::Type => {
480
                self.head(visibility_qualified(&item.vis, "type"))?;
481
                self.print_ident(item.ident)?;
P
Paul Lietar 已提交
482 483
                self.s.word(";")?;
                self.end()?; // end the head-ibox
484 485 486 487 488 489
                self.end() // end the outer cbox
            }
        }
    }

    fn print_associated_const(&mut self,
490
                              ident: ast::Ident,
491
                              ty: &hir::Ty,
492
                              default: Option<hir::BodyId>,
493
                              vis: &hir::Visibility)
N
Nick Cameron 已提交
494
                              -> io::Result<()> {
495
        self.s.word(visibility_qualified(vis, ""))?;
J
Jorge Aparicio 已提交
496
        self.word_space("const")?;
497
        self.print_ident(ident)?;
J
Jorge Aparicio 已提交
498 499
        self.word_space(":")?;
        self.print_type(ty)?;
500
        if let Some(expr) = default {
501
            self.s.space()?;
J
Jorge Aparicio 已提交
502
            self.word_space("=")?;
503
            self.ann.nested(self, Nested::Body(expr))?;
504
        }
505
        self.s.word(";")
506 507 508
    }

    fn print_associated_type(&mut self,
509
                             ident: ast::Ident,
V
varkor 已提交
510
                             bounds: Option<&hir::GenericBounds>,
511 512
                             ty: Option<&hir::Ty>)
                             -> io::Result<()> {
J
Jorge Aparicio 已提交
513
        self.word_space("type")?;
514
        self.print_ident(ident)?;
515
        if let Some(bounds) = bounds {
J
Jorge Aparicio 已提交
516
            self.print_bounds(":", bounds)?;
517 518
        }
        if let Some(ty) = ty {
519
            self.s.space()?;
J
Jorge Aparicio 已提交
520 521
            self.word_space("=")?;
            self.print_type(ty)?;
522
        }
523
        self.s.word(";")
524 525 526 527
    }

    /// Pretty-print an item
    pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
J
Jorge Aparicio 已提交
528
        self.hardbreak_if_not_bol()?;
529
        self.maybe_print_comment(item.span.lo())?;
J
Jorge Aparicio 已提交
530
        self.print_outer_attributes(&item.attrs)?;
V
varkor 已提交
531
        self.ann.pre(self, AnnNode::Item(item))?;
532
        match item.node {
C
csmoe 已提交
533
            hir::ItemKind::ExternCrate(orig_name) => {
534
                self.head(visibility_qualified(&item.vis, "extern crate"))?;
535 536
                if let Some(orig_name) = orig_name {
                    self.print_name(orig_name)?;
537 538 539
                    self.s.space()?;
                    self.s.word("as")?;
                    self.s.space()?;
540
                }
541
                self.print_ident(item.ident)?;
542
                self.s.word(";")?;
J
Jorge Aparicio 已提交
543 544
                self.end()?; // end inner head-block
                self.end()?; // end outer head-block
545
            }
C
csmoe 已提交
546
            hir::ItemKind::Use(ref path, kind) => {
547
                self.head(visibility_qualified(&item.vis, "use"))?;
548 549 550 551
                self.print_path(path, false)?;

                match kind {
                    hir::UseKind::Single => {
552
                        if path.segments.last().unwrap().ident != item.ident {
553
                            self.s.space()?;
554
                            self.word_space("as")?;
555
                            self.print_ident(item.ident)?;
556
                        }
557
                        self.s.word(";")?;
558
                    }
559 560
                    hir::UseKind::Glob => self.s.word("::*;")?,
                    hir::UseKind::ListStem => self.s.word("::{};")?
561
                }
J
Jorge Aparicio 已提交
562 563
                self.end()?; // end inner head-block
                self.end()?; // end outer head-block
564
            }
C
csmoe 已提交
565
            hir::ItemKind::Static(ref ty, m, expr) => {
566
                self.head(visibility_qualified(&item.vis, "static"))?;
567
                if m == hir::MutMutable {
J
Jorge Aparicio 已提交
568
                    self.word_space("mut")?;
569
                }
570
                self.print_ident(item.ident)?;
J
Jorge Aparicio 已提交
571 572
                self.word_space(":")?;
                self.print_type(&ty)?;
573
                self.s.space()?;
J
Jorge Aparicio 已提交
574
                self.end()?; // end the head-ibox
575

J
Jorge Aparicio 已提交
576
                self.word_space("=")?;
577
                self.ann.nested(self, Nested::Body(expr))?;
578
                self.s.word(";")?;
J
Jorge Aparicio 已提交
579
                self.end()?; // end the outer cbox
580
            }
C
csmoe 已提交
581
            hir::ItemKind::Const(ref ty, expr) => {
582
                self.head(visibility_qualified(&item.vis, "const"))?;
583
                self.print_ident(item.ident)?;
J
Jorge Aparicio 已提交
584 585
                self.word_space(":")?;
                self.print_type(&ty)?;
586
                self.s.space()?;
J
Jorge Aparicio 已提交
587 588 589
                self.end()?; // end the head-ibox

                self.word_space("=")?;
590
                self.ann.nested(self, Nested::Body(expr))?;
591
                self.s.word(";")?;
J
Jorge Aparicio 已提交
592
                self.end()?; // end the outer cbox
593
            }
V
varkor 已提交
594
            hir::ItemKind::Fn(ref decl, header, ref param_names, body) => {
J
Jorge Aparicio 已提交
595 596
                self.head("")?;
                self.print_fn(decl,
W
Without Boats 已提交
597
                              header,
598
                              Some(item.ident.name),
V
varkor 已提交
599
                              param_names,
600 601 602
                              &item.vis,
                              &[],
                              Some(body))?;
603
                self.s.word(" ")?;
604 605
                self.end()?; // need to close a box
                self.end()?; // need to close a box
606
                self.ann.nested(self, Nested::Body(body))?;
607
            }
C
csmoe 已提交
608
            hir::ItemKind::Mod(ref _mod) => {
609
                self.head(visibility_qualified(&item.vis, "mod"))?;
610
                self.print_ident(item.ident)?;
J
Jorge Aparicio 已提交
611 612 613 614
                self.nbsp()?;
                self.bopen()?;
                self.print_mod(_mod, &item.attrs)?;
                self.bclose(item.span)?;
615
            }
C
csmoe 已提交
616
            hir::ItemKind::ForeignMod(ref nmod) => {
J
Jorge Aparicio 已提交
617
                self.head("extern")?;
618
                self.word_nbsp(nmod.abi.to_string())?;
J
Jorge Aparicio 已提交
619 620 621
                self.bopen()?;
                self.print_foreign_mod(nmod, &item.attrs)?;
                self.bclose(item.span)?;
622
            }
C
csmoe 已提交
623
            hir::ItemKind::GlobalAsm(ref ga) => {
624 625
                self.head(visibility_qualified(&item.vis, "global asm"))?;
                self.s.word(ga.asm.as_str().get())?;
626 627
                self.end()?
            }
C
csmoe 已提交
628
            hir::ItemKind::Ty(ref ty, ref generics) => {
629
                self.head(visibility_qualified(&item.vis, "type"))?;
630
                self.print_ident(item.ident)?;
631
                self.print_generic_params(&generics.params)?;
J
Jorge Aparicio 已提交
632 633
                self.end()?; // end the inner ibox

634
                self.print_where_clause(&generics.where_clause)?;
635
                self.s.space()?;
J
Jorge Aparicio 已提交
636 637
                self.word_space("=")?;
                self.print_type(&ty)?;
638
                self.s.word(";")?;
J
Jorge Aparicio 已提交
639
                self.end()?; // end the outer ibox
640
            }
C
csmoe 已提交
641
            hir::ItemKind::Existential(ref exist) => {
642
                self.head(visibility_qualified(&item.vis, "existential type"))?;
643
                self.print_ident(item.ident)?;
644 645 646 647 648 649 650 651
                self.print_generic_params(&exist.generics.params)?;
                self.end()?; // end the inner ibox

                self.print_where_clause(&exist.generics.where_clause)?;
                self.s.space()?;
                self.word_space(":")?;
                let mut real_bounds = Vec::with_capacity(exist.bounds.len());
                for b in exist.bounds.iter() {
652
                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
653 654 655 656 657 658 659 660 661 662 663
                        self.s.space()?;
                        self.word_space("for ?")?;
                        self.print_trait_ref(&ptr.trait_ref)?;
                    } else {
                        real_bounds.push(b.clone());
                    }
                }
                self.print_bounds(":", &real_bounds[..])?;
                self.s.word(";")?;
                self.end()?; // end the outer ibox
            }
C
csmoe 已提交
664
            hir::ItemKind::Enum(ref enum_definition, ref params) => {
665 666
                self.print_enum_def(enum_definition, params, item.ident.name, item.span,
                                    &item.vis)?;
667
            }
C
csmoe 已提交
668
            hir::ItemKind::Struct(ref struct_def, ref generics) => {
669
                self.head(visibility_qualified(&item.vis, "struct"))?;
670
                self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
671
            }
C
csmoe 已提交
672
            hir::ItemKind::Union(ref struct_def, ref generics) => {
673
                self.head(visibility_qualified(&item.vis, "union"))?;
674
                self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
V
Vadim Petrochenkov 已提交
675
            }
C
csmoe 已提交
676
            hir::ItemKind::Impl(unsafety,
677
                          polarity,
678
                          defaultness,
679 680 681 682
                          ref generics,
                          ref opt_trait,
                          ref ty,
                          ref impl_items) => {
J
Jorge Aparicio 已提交
683
                self.head("")?;
684
                self.print_visibility(&item.vis)?;
685
                self.print_defaultness(defaultness)?;
J
Jorge Aparicio 已提交
686 687
                self.print_unsafety(unsafety)?;
                self.word_nbsp("impl")?;
688

689 690
                if !generics.params.is_empty() {
                    self.print_generic_params(&generics.params)?;
691
                    self.s.space()?;
692 693
                }

L
ljedrz 已提交
694 695
                if let hir::ImplPolarity::Negative = polarity {
                    self.s.word("!")?;
696 697
                }

L
ljedrz 已提交
698 699 700 701
                if let Some(ref t) = opt_trait {
                    self.print_trait_ref(t)?;
                    self.s.space()?;
                    self.word_space("for")?;
702 703
                }

J
Jorge Aparicio 已提交
704 705
                self.print_type(&ty)?;
                self.print_where_clause(&generics.where_clause)?;
706

707
                self.s.space()?;
J
Jorge Aparicio 已提交
708 709
                self.bopen()?;
                self.print_inner_attributes(&item.attrs)?;
710
                for impl_item in impl_items {
711
                    self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
712
                }
J
Jorge Aparicio 已提交
713
                self.bclose(item.span)?;
714
            }
C
csmoe 已提交
715
            hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
J
Jorge Aparicio 已提交
716
                self.head("")?;
717
                self.print_visibility(&item.vis)?;
718
                self.print_is_auto(is_auto)?;
J
Jorge Aparicio 已提交
719 720
                self.print_unsafety(unsafety)?;
                self.word_nbsp("trait")?;
721
                self.print_ident(item.ident)?;
722
                self.print_generic_params(&generics.params)?;
723 724
                let mut real_bounds = Vec::with_capacity(bounds.len());
                for b in bounds.iter() {
V
varkor 已提交
725
                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
726
                        self.s.space()?;
J
Jorge Aparicio 已提交
727 728
                        self.word_space("for ?")?;
                        self.print_trait_ref(&ptr.trait_ref)?;
729 730 731 732
                    } else {
                        real_bounds.push(b.clone());
                    }
                }
J
Jorge Aparicio 已提交
733 734
                self.print_bounds(":", &real_bounds[..])?;
                self.print_where_clause(&generics.where_clause)?;
735
                self.s.word(" ")?;
J
Jorge Aparicio 已提交
736
                self.bopen()?;
737
                for trait_item in trait_items {
738
                    self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
739
                }
J
Jorge Aparicio 已提交
740
                self.bclose(item.span)?;
741
            }
C
csmoe 已提交
742
            hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
A
Alex Burka 已提交
743 744 745
                self.head("")?;
                self.print_visibility(&item.vis)?;
                self.word_nbsp("trait")?;
746
                self.print_ident(item.ident)?;
747
                self.print_generic_params(&generics.params)?;
A
Alex Burka 已提交
748 749 750
                let mut real_bounds = Vec::with_capacity(bounds.len());
                // FIXME(durka) this seems to be some quite outdated syntax
                for b in bounds.iter() {
V
varkor 已提交
751
                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
A
Alex Burka 已提交
752 753 754 755 756 757 758
                        self.s.space()?;
                        self.word_space("for ?")?;
                        self.print_trait_ref(&ptr.trait_ref)?;
                    } else {
                        real_bounds.push(b.clone());
                    }
                }
759 760
                self.nbsp()?;
                self.print_bounds("=", &real_bounds[..])?;
A
Alex Burka 已提交
761 762 763
                self.print_where_clause(&generics.where_clause)?;
                self.s.word(";")?;
            }
764
        }
V
varkor 已提交
765
        self.ann.post(self, AnnNode::Item(item))
766 767
    }

768
    pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
769
        self.print_path(&t.path, false)
770 771
    }

772 773 774 775 776 777 778
    fn print_formal_generic_params(
        &mut self,
        generic_params: &[hir::GenericParam]
    ) -> io::Result<()> {
        if !generic_params.is_empty() {
            self.s.word("for")?;
            self.print_generic_params(generic_params)?;
779
            self.nbsp()?;
780 781 782 783 784
        }
        Ok(())
    }

    fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
785
        self.print_formal_generic_params(&t.bound_generic_params)?;
786 787 788
        self.print_trait_ref(&t.trait_ref)
    }

N
Nick Cameron 已提交
789 790 791 792
    pub fn print_enum_def(&mut self,
                          enum_definition: &hir::EnumDef,
                          generics: &hir::Generics,
                          name: ast::Name,
793
                          span: syntax_pos::Span,
794
                          visibility: &hir::Visibility)
N
Nick Cameron 已提交
795
                          -> io::Result<()> {
796
        self.head(visibility_qualified(visibility, "enum"))?;
J
Jorge Aparicio 已提交
797
        self.print_name(name)?;
798
        self.print_generic_params(&generics.params)?;
J
Jorge Aparicio 已提交
799
        self.print_where_clause(&generics.where_clause)?;
800
        self.s.space()?;
801 802 803 804
        self.print_variants(&enum_definition.variants, span)
    }

    pub fn print_variants(&mut self,
805
                          variants: &[hir::Variant],
806
                          span: syntax_pos::Span)
N
Nick Cameron 已提交
807
                          -> io::Result<()> {
J
Jorge Aparicio 已提交
808
        self.bopen()?;
809
        for v in variants {
J
Jorge Aparicio 已提交
810
            self.space_if_not_bol()?;
811
            self.maybe_print_comment(v.span.lo())?;
J
Jorge Aparicio 已提交
812 813 814
            self.print_outer_attributes(&v.node.attrs)?;
            self.ibox(indent_unit)?;
            self.print_variant(v)?;
815
            self.s.word(",")?;
J
Jorge Aparicio 已提交
816 817
            self.end()?;
            self.maybe_print_trailing_comment(v.span, None)?;
818 819 820 821
        }
        self.bclose(span)
    }

822
    pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
823
        match vis.node {
824 825 826 827
            hir::VisibilityKind::Public => self.word_nbsp("pub")?,
            hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
            hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
            hir::VisibilityKind::Restricted { ref path, .. } => {
828
                self.s.word("pub(")?;
829 830
                if path.segments.len() == 1 &&
                   path.segments[0].ident.name == keywords::Super.name() {
831 832 833 834 835 836 837 838
                    // Special case: `super` can print like `pub(super)`.
                    self.s.word("super")?;
                } else {
                    // Everything else requires `in` at present.
                    self.word_nbsp("in")?;
                    self.print_path(path, false)?;
                }
                self.word_nbsp(")")?;
839
            }
840
            hir::VisibilityKind::Inherited => ()
841
        }
842 843

        Ok(())
844 845
    }

846
    pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
847 848 849
        match defaultness {
            hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
            hir::Defaultness::Final => (),
850 851 852 853
        }
        Ok(())
    }

854
    pub fn print_struct(&mut self,
855
                        struct_def: &hir::VariantData,
856
                        generics: &hir::Generics,
V
Vadim Petrochenkov 已提交
857
                        name: ast::Name,
858
                        span: syntax_pos::Span,
859
                        print_finalizer: bool)
N
Nick Cameron 已提交
860
                        -> io::Result<()> {
J
Jorge Aparicio 已提交
861
        self.print_name(name)?;
862
        self.print_generic_params(&generics.params)?;
863 864
        if !struct_def.is_struct() {
            if struct_def.is_tuple() {
J
Jorge Aparicio 已提交
865 866
                self.popen()?;
                self.commasep(Inconsistent, struct_def.fields(), |s, field| {
867
                    s.maybe_print_comment(field.span.lo())?;
868 869
                    s.print_outer_attributes(&field.attrs)?;
                    s.print_visibility(&field.vis)?;
870
                    s.print_type(&field.ty)
J
Jorge Aparicio 已提交
871 872
                })?;
                self.pclose()?;
873
            }
J
Jorge Aparicio 已提交
874
            self.print_where_clause(&generics.where_clause)?;
875
            if print_finalizer {
876
                self.s.word(";")?;
877
            }
J
Jorge Aparicio 已提交
878
            self.end()?;
879 880
            self.end() // close the outer-box
        } else {
J
Jorge Aparicio 已提交
881 882 883 884
            self.print_where_clause(&generics.where_clause)?;
            self.nbsp()?;
            self.bopen()?;
            self.hardbreak_if_not_bol()?;
885

886
            for field in struct_def.fields() {
J
Jorge Aparicio 已提交
887
                self.hardbreak_if_not_bol()?;
888
                self.maybe_print_comment(field.span.lo())?;
J
Jorge Aparicio 已提交
889
                self.print_outer_attributes(&field.attrs)?;
890
                self.print_visibility(&field.vis)?;
891
                self.print_ident(field.ident)?;
J
Jorge Aparicio 已提交
892 893
                self.word_nbsp(":")?;
                self.print_type(&field.ty)?;
894
                self.s.word(",")?;
895 896 897 898 899 900 901
            }

            self.bclose(span)
        }
    }

    pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
J
Jorge Aparicio 已提交
902
        self.head("")?;
903
        let generics = hir::Generics::empty();
904
        self.print_struct(&v.node.data, &generics, v.node.ident.name, v.span, false)?;
905
        if let Some(ref d) = v.node.disr_expr {
906
            self.s.space()?;
907
            self.word_space("=")?;
908
            self.print_anon_const(d)?;
909
        }
910
        Ok(())
911 912
    }
    pub fn print_method_sig(&mut self,
913
                            ident: ast::Ident,
914
                            m: &hir::MethodSig,
915
                            generics: &hir::Generics,
916
                            vis: &hir::Visibility,
917
                            arg_names: &[ast::Ident],
918
                            body_id: Option<hir::BodyId>)
919 920
                            -> io::Result<()> {
        self.print_fn(&m.decl,
W
Without Boats 已提交
921
                      m.header,
922
                      Some(ident.name),
923
                      generics,
924 925 926
                      vis,
                      arg_names,
                      body_id)
927 928
    }

N
Nick Cameron 已提交
929
    pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
L
ljedrz 已提交
930
        self.ann.pre(self, AnnNode::SubItem(ti.hir_id))?;
J
Jorge Aparicio 已提交
931
        self.hardbreak_if_not_bol()?;
932
        self.maybe_print_comment(ti.span.lo())?;
J
Jorge Aparicio 已提交
933
        self.print_outer_attributes(&ti.attrs)?;
934
        match ti.node {
935
            hir::TraitItemKind::Const(ref ty, default) => {
936 937
                let vis = Spanned { span: syntax_pos::DUMMY_SP,
                                    node: hir::VisibilityKind::Inherited };
938
                self.print_associated_const(ti.ident, &ty, default, &vis)?;
939
            }
940
            hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
941 942
                let vis = Spanned { span: syntax_pos::DUMMY_SP,
                                    node: hir::VisibilityKind::Inherited };
943
                self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
944
                self.s.word(";")?;
945 946
            }
            hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
947 948
                let vis = Spanned { span: syntax_pos::DUMMY_SP,
                                    node: hir::VisibilityKind::Inherited };
949
                self.head("")?;
950
                self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
951 952 953
                self.nbsp()?;
                self.end()?; // need to close a box
                self.end()?; // need to close a box
954
                self.ann.nested(self, Nested::Body(body))?;
955
            }
956
            hir::TraitItemKind::Type(ref bounds, ref default) => {
957
                self.print_associated_type(ti.ident,
J
Jorge Aparicio 已提交
958 959
                                           Some(bounds),
                                           default.as_ref().map(|ty| &**ty))?;
960 961
            }
        }
L
ljedrz 已提交
962
        self.ann.post(self, AnnNode::SubItem(ti.hir_id))
963 964 965
    }

    pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
L
ljedrz 已提交
966
        self.ann.pre(self, AnnNode::SubItem(ii.hir_id))?;
J
Jorge Aparicio 已提交
967
        self.hardbreak_if_not_bol()?;
968
        self.maybe_print_comment(ii.span.lo())?;
J
Jorge Aparicio 已提交
969
        self.print_outer_attributes(&ii.attrs)?;
970
        self.print_defaultness(ii.defaultness)?;
971

972
        match ii.node {
973
            hir::ImplItemKind::Const(ref ty, expr) => {
974
                self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
975
            }
976
            hir::ImplItemKind::Method(ref sig, body) => {
J
Jorge Aparicio 已提交
977
                self.head("")?;
978
                self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
J
Jorge Aparicio 已提交
979
                self.nbsp()?;
980 981
                self.end()?; // need to close a box
                self.end()?; // need to close a box
982
                self.ann.nested(self, Nested::Body(body))?;
983
            }
984
            hir::ImplItemKind::Type(ref ty) => {
985
                self.print_associated_type(ii.ident, None, Some(ty))?;
986
            }
O
Oliver Schneider 已提交
987 988 989 990
            hir::ImplItemKind::Existential(ref bounds) => {
                self.word_space("existential")?;
                self.print_associated_type(ii.ident, Some(bounds), None)?;
            }
991
        }
L
ljedrz 已提交
992
        self.ann.post(self, AnnNode::SubItem(ii.hir_id))
993 994 995
    }

    pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
996
        self.maybe_print_comment(st.span.lo())?;
997
        match st.node {
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
            hir::StmtKind::Local(ref loc) => {
                self.space_if_not_bol()?;
                self.ibox(indent_unit)?;
                self.word_nbsp("let")?;

                self.ibox(indent_unit)?;
                self.print_local_decl(&loc)?;
                self.end()?;
                if let Some(ref init) = loc.init {
                    self.nbsp()?;
                    self.word_space("=")?;
                    self.print_expr(&init)?;
                }
                self.end()?
            }
1013 1014
            hir::StmtKind::Item(item) => {
                self.ann.nested(self, Nested::Item(item))?
1015
            }
1016
            hir::StmtKind::Expr(ref expr) => {
J
Jorge Aparicio 已提交
1017 1018
                self.space_if_not_bol()?;
                self.print_expr(&expr)?;
1019
            }
1020
            hir::StmtKind::Semi(ref expr) => {
J
Jorge Aparicio 已提交
1021 1022
                self.space_if_not_bol()?;
                self.print_expr(&expr)?;
1023
                self.s.word(";")?;
1024 1025 1026
            }
        }
        if stmt_ends_with_semi(&st.node) {
1027
            self.s.word(";")?;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        }
        self.maybe_print_trailing_comment(st.span, None)
    }

    pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
        self.print_block_with_attrs(blk, &[])
    }

    pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
        self.print_block_unclosed_indent(blk, indent_unit)
    }

N
Nick Cameron 已提交
1040 1041 1042 1043
    pub fn print_block_unclosed_indent(&mut self,
                                       blk: &hir::Block,
                                       indented: usize)
                                       -> io::Result<()> {
1044 1045 1046 1047 1048
        self.print_block_maybe_unclosed(blk, indented, &[], false)
    }

    pub fn print_block_with_attrs(&mut self,
                                  blk: &hir::Block,
N
Nick Cameron 已提交
1049 1050
                                  attrs: &[ast::Attribute])
                                  -> io::Result<()> {
1051 1052 1053 1054 1055 1056
        self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
    }

    pub fn print_block_maybe_unclosed(&mut self,
                                      blk: &hir::Block,
                                      indented: usize,
1057
                                      attrs: &[ast::Attribute],
N
Nick Cameron 已提交
1058 1059
                                      close_box: bool)
                                      -> io::Result<()> {
1060
        match blk.rules {
J
Jorge Aparicio 已提交
1061 1062 1063
            hir::UnsafeBlock(..) => self.word_space("unsafe")?,
            hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
            hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
N
Nick Cameron 已提交
1064
            hir::DefaultBlock => (),
1065
        }
1066
        self.maybe_print_comment(blk.span.lo())?;
V
varkor 已提交
1067
        self.ann.pre(self, AnnNode::Block(blk))?;
J
Jorge Aparicio 已提交
1068
        self.bopen()?;
1069

J
Jorge Aparicio 已提交
1070
        self.print_inner_attributes(attrs)?;
1071 1072

        for st in &blk.stmts {
J
Jorge Aparicio 已提交
1073
            self.print_stmt(st)?;
1074
        }
L
ljedrz 已提交
1075 1076 1077 1078
        if let Some(ref expr) = blk.expr {
            self.space_if_not_bol()?;
            self.print_expr(&expr)?;
            self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1079
        }
J
Jorge Aparicio 已提交
1080
        self.bclose_maybe_open(blk.span, indented, close_box)?;
V
varkor 已提交
1081
        self.ann.post(self, AnnNode::Block(blk))
1082 1083 1084 1085 1086 1087 1088
    }

    fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
        match els {
            Some(_else) => {
                match _else.node {
                    // "another else-if"
C
csmoe 已提交
1089
                    hir::ExprKind::If(ref i, ref then, ref e) => {
J
Jorge Aparicio 已提交
1090 1091
                        self.cbox(indent_unit - 1)?;
                        self.ibox(0)?;
1092
                        self.s.word(" else if ")?;
1093
                        self.print_expr_as_cond(&i)?;
1094
                        self.s.space()?;
1095
                        self.print_expr(&then)?;
1096 1097 1098
                        self.print_else(e.as_ref().map(|e| &**e))
                    }
                    // "final else"
C
csmoe 已提交
1099
                    hir::ExprKind::Block(ref b, _) => {
J
Jorge Aparicio 已提交
1100 1101
                        self.cbox(indent_unit - 1)?;
                        self.ibox(0)?;
1102
                        self.s.word(" else ")?;
1103
                        self.print_block(&b)
1104 1105 1106 1107 1108 1109 1110
                    }
                    // BLEAH, constraints would be great here
                    _ => {
                        panic!("print_if saw if with weird alternative");
                    }
                }
            }
N
Nick Cameron 已提交
1111
            _ => Ok(()),
1112 1113 1114
        }
    }

N
Nick Cameron 已提交
1115 1116
    pub fn print_if(&mut self,
                    test: &hir::Expr,
1117
                    blk: &hir::Expr,
N
Nick Cameron 已提交
1118 1119
                    elseopt: Option<&hir::Expr>)
                    -> io::Result<()> {
J
Jorge Aparicio 已提交
1120
        self.head("if")?;
1121
        self.print_expr_as_cond(test)?;
1122
        self.s.space()?;
1123
        self.print_expr(blk)?;
1124 1125 1126
        self.print_else(elseopt)
    }

N
Nick Cameron 已提交
1127 1128 1129 1130 1131 1132
    pub fn print_if_let(&mut self,
                        pat: &hir::Pat,
                        expr: &hir::Expr,
                        blk: &hir::Block,
                        elseopt: Option<&hir::Expr>)
                        -> io::Result<()> {
J
Jorge Aparicio 已提交
1133 1134
        self.head("if let")?;
        self.print_pat(pat)?;
1135
        self.s.space()?;
J
Jorge Aparicio 已提交
1136
        self.word_space("=")?;
1137
        self.print_expr_as_cond(expr)?;
1138
        self.s.space()?;
J
Jorge Aparicio 已提交
1139
        self.print_block(blk)?;
1140 1141 1142
        self.print_else(elseopt)
    }

1143 1144 1145
    pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
        self.ann.nested(self, Nested::Body(constant.body))
    }
1146

1147
    fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1148 1149
        self.popen()?;
        self.commasep_exprs(Inconsistent, args)?;
1150 1151 1152
        self.pclose()
    }

1153
    pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1154
        let needs_par = expr.precedence().order() < prec;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        if needs_par {
            self.popen()?;
        }
        self.print_expr(expr)?;
        if needs_par {
            self.pclose()?;
        }
        Ok(())
    }

    /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
    /// `if cond { ... }`.
    pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
        let needs_par = match expr.node {
            // These cases need parens due to the parse error observed in #26461: `if return {}`
            // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
C
csmoe 已提交
1171 1172 1173
            hir::ExprKind::Closure(..) |
            hir::ExprKind::Ret(..) |
            hir::ExprKind::Break(..) => true,
1174 1175 1176 1177

            _ => contains_exterior_struct_lit(expr),
        };

1178
        if needs_par {
J
Jorge Aparicio 已提交
1179
            self.popen()?;
1180
        }
J
Jorge Aparicio 已提交
1181
        self.print_expr(expr)?;
1182
        if needs_par {
J
Jorge Aparicio 已提交
1183
            self.pclose()?;
1184 1185 1186 1187
        }
        Ok(())
    }

1188
    fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1189
        self.ibox(indent_unit)?;
1190
        self.s.word("[")?;
1191
        self.commasep_exprs(Inconsistent, exprs)?;
1192
        self.s.word("]")?;
1193 1194 1195
        self.end()
    }

1196
    fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
J
Jorge Aparicio 已提交
1197
        self.ibox(indent_unit)?;
1198
        self.s.word("[")?;
J
Jorge Aparicio 已提交
1199 1200
        self.print_expr(element)?;
        self.word_space(";")?;
1201
        self.print_anon_const(count)?;
1202
        self.s.word("]")?;
1203 1204 1205 1206
        self.end()
    }

    fn print_expr_struct(&mut self,
1207
                         qpath: &hir::QPath,
1208
                         fields: &[hir::Field],
N
Nick Cameron 已提交
1209 1210
                         wth: &Option<P<hir::Expr>>)
                         -> io::Result<()> {
1211
        self.print_qpath(qpath, true)?;
1212
        self.s.word("{")?;
J
Jorge Aparicio 已提交
1213
        self.commasep_cmnt(Consistent,
J
Jorge Aparicio 已提交
1214 1215 1216
                           &fields[..],
                           |s, field| {
                               s.ibox(indent_unit)?;
1217
                               if !field.is_shorthand {
1218
                                    s.print_ident(field.ident)?;
1219 1220
                                    s.word_space(":")?;
                               }
J
Jorge Aparicio 已提交
1221 1222 1223 1224
                               s.print_expr(&field.expr)?;
                               s.end()
                           },
                           |f| f.span)?;
1225 1226
        match *wth {
            Some(ref expr) => {
J
Jorge Aparicio 已提交
1227
                self.ibox(indent_unit)?;
1228
                if !fields.is_empty() {
1229 1230
                    self.s.word(",")?;
                    self.s.space()?;
1231
                }
1232
                self.s.word("..")?;
J
Jorge Aparicio 已提交
1233 1234
                self.print_expr(&expr)?;
                self.end()?;
1235 1236
            }
            _ => if !fields.is_empty() {
1237
                self.s.word(",")?
N
Nick Cameron 已提交
1238
            },
1239
        }
1240
        self.s.word("}")?;
1241 1242 1243
        Ok(())
    }

1244
    fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1245
        self.popen()?;
1246
        self.commasep_exprs(Inconsistent, exprs)?;
1247
        if exprs.len() == 1 {
1248
            self.s.word(",")?;
1249 1250 1251 1252
        }
        self.pclose()
    }

1253
    fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1254 1255
        let prec =
            match func.node {
C
csmoe 已提交
1256
                hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1257 1258 1259 1260
                _ => parser::PREC_POSTFIX,
            };

        self.print_expr_maybe_paren(func, prec)?;
1261 1262 1263 1264
        self.print_call_post(args)
    }

    fn print_expr_method_call(&mut self,
1265
                              segment: &hir::PathSegment,
1266
                              args: &[hir::Expr])
N
Nick Cameron 已提交
1267
                              -> io::Result<()> {
1268
        let base_args = &args[1..];
1269
        self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1270
        self.s.word(".")?;
1271
        self.print_ident(segment.ident)?;
1272

1273
        segment.with_generic_args(|generic_args| {
1274 1275
            if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
                return self.print_generic_args(&generic_args, segment.infer_types, true);
1276
            }
1277
            Ok(())
1278
        })?;
1279 1280 1281 1282 1283 1284
        self.print_call_post(base_args)
    }

    fn print_expr_binary(&mut self,
                         op: hir::BinOp,
                         lhs: &hir::Expr,
N
Nick Cameron 已提交
1285 1286
                         rhs: &hir::Expr)
                         -> io::Result<()> {
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
        let assoc_op = bin_op_to_assoc_op(op.node);
        let prec = assoc_op.precedence() as i8;
        let fixity = assoc_op.fixity();

        let (left_prec, right_prec) = match fixity {
            Fixity::Left => (prec, prec + 1),
            Fixity::Right => (prec + 1, prec),
            Fixity::None => (prec + 1, prec + 1),
        };

1297 1298 1299 1300
        let left_prec = match (&lhs.node, op.node) {
            // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
            // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
            // of `(x as i32) < ...`. We need to convince it _not_ to do that.
C
csmoe 已提交
1301 1302
            (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
            (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1303 1304 1305
            _ => left_prec,
        };

1306
        self.print_expr_maybe_paren(lhs, left_prec)?;
1307
        self.s.space()?;
1308
        self.word_space(op.node.as_str())?;
1309
        self.print_expr_maybe_paren(rhs, right_prec)
1310 1311
    }

N
Nick Cameron 已提交
1312
    fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1313
        self.s.word(op.as_str())?;
1314
        self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1315 1316 1317 1318
    }

    fn print_expr_addr_of(&mut self,
                          mutability: hir::Mutability,
N
Nick Cameron 已提交
1319 1320
                          expr: &hir::Expr)
                          -> io::Result<()> {
1321
        self.s.word("&")?;
J
Jorge Aparicio 已提交
1322
        self.print_mutability(mutability)?;
1323
        self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1324 1325 1326
    }

    pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1327
        self.maybe_print_comment(expr.span.lo())?;
1328
        self.print_outer_attributes(&expr.attrs)?;
J
Jorge Aparicio 已提交
1329
        self.ibox(indent_unit)?;
V
varkor 已提交
1330
        self.ann.pre(self, AnnNode::Expr(expr))?;
1331
        match expr.node {
C
csmoe 已提交
1332
            hir::ExprKind::Box(ref expr) => {
J
Jorge Aparicio 已提交
1333
                self.word_space("box")?;
1334
                self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1335
            }
C
csmoe 已提交
1336
            hir::ExprKind::Array(ref exprs) => {
1337
                self.print_expr_vec(exprs)?;
1338
            }
C
csmoe 已提交
1339
            hir::ExprKind::Repeat(ref element, ref count) => {
1340
                self.print_expr_repeat(&element, count)?;
1341
            }
C
csmoe 已提交
1342
            hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1343
                self.print_expr_struct(qpath, &fields[..], wth)?;
1344
            }
C
csmoe 已提交
1345
            hir::ExprKind::Tup(ref exprs) => {
1346
                self.print_expr_tup(exprs)?;
1347
            }
C
csmoe 已提交
1348
            hir::ExprKind::Call(ref func, ref args) => {
1349
                self.print_expr_call(&func, args)?;
1350
            }
C
csmoe 已提交
1351
            hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1352
                self.print_expr_method_call(segment, args)?;
1353
            }
C
csmoe 已提交
1354
            hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
J
Jorge Aparicio 已提交
1355
                self.print_expr_binary(op, &lhs, &rhs)?;
1356
            }
C
csmoe 已提交
1357
            hir::ExprKind::Unary(op, ref expr) => {
J
Jorge Aparicio 已提交
1358
                self.print_expr_unary(op, &expr)?;
1359
            }
C
csmoe 已提交
1360
            hir::ExprKind::AddrOf(m, ref expr) => {
J
Jorge Aparicio 已提交
1361
                self.print_expr_addr_of(m, &expr)?;
1362
            }
C
csmoe 已提交
1363
            hir::ExprKind::Lit(ref lit) => {
J
Jorge Aparicio 已提交
1364
                self.print_literal(&lit)?;
1365
            }
C
csmoe 已提交
1366
            hir::ExprKind::Cast(ref expr, ref ty) => {
1367 1368
                let prec = AssocOp::As.precedence() as i8;
                self.print_expr_maybe_paren(&expr, prec)?;
1369
                self.s.space()?;
J
Jorge Aparicio 已提交
1370 1371
                self.word_space("as")?;
                self.print_type(&ty)?;
1372
            }
C
csmoe 已提交
1373
            hir::ExprKind::Type(ref expr, ref ty) => {
1374 1375
                let prec = AssocOp::Colon.precedence() as i8;
                self.print_expr_maybe_paren(&expr, prec)?;
J
Jorge Aparicio 已提交
1376 1377
                self.word_space(":")?;
                self.print_type(&ty)?;
1378
            }
C
csmoe 已提交
1379
            hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
J
Jorge Aparicio 已提交
1380
                self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1381
            }
C
csmoe 已提交
1382
            hir::ExprKind::While(ref test, ref blk, opt_label) => {
1383
                if let Some(label) = opt_label {
1384
                    self.print_ident(label.ident)?;
J
Jorge Aparicio 已提交
1385
                    self.word_space(":")?;
1386
                }
J
Jorge Aparicio 已提交
1387
                self.head("while")?;
1388
                self.print_expr_as_cond(&test)?;
1389
                self.s.space()?;
J
Jorge Aparicio 已提交
1390
                self.print_block(&blk)?;
1391
            }
C
csmoe 已提交
1392
            hir::ExprKind::Loop(ref blk, opt_label, _) => {
1393
                if let Some(label) = opt_label {
1394
                    self.print_ident(label.ident)?;
J
Jorge Aparicio 已提交
1395
                    self.word_space(":")?;
1396
                }
J
Jorge Aparicio 已提交
1397
                self.head("loop")?;
1398
                self.s.space()?;
J
Jorge Aparicio 已提交
1399
                self.print_block(&blk)?;
1400
            }
C
csmoe 已提交
1401
            hir::ExprKind::Match(ref expr, ref arms, _) => {
J
Jorge Aparicio 已提交
1402 1403 1404
                self.cbox(indent_unit)?;
                self.ibox(4)?;
                self.word_nbsp("match")?;
1405
                self.print_expr_as_cond(&expr)?;
1406
                self.s.space()?;
J
Jorge Aparicio 已提交
1407
                self.bopen()?;
1408
                for arm in arms {
J
Jorge Aparicio 已提交
1409
                    self.print_arm(arm)?;
1410
                }
J
Jorge Aparicio 已提交
1411
                self.bclose_(expr.span, indent_unit)?;
1412
            }
C
csmoe 已提交
1413
            hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
J
Jorge Aparicio 已提交
1414
                self.print_capture_clause(capture_clause)?;
1415

1416
                self.print_closure_args(&decl, body)?;
1417
                self.s.space()?;
1418

1419
                // this is a bare expression
1420
                self.ann.nested(self, Nested::Body(body))?;
1421
                self.end()?; // need to close a box
1422 1423 1424 1425

                // a box will be closed by print_expr, but we didn't want an overall
                // wrapper so we closed the corresponding opening. so create an
                // empty box to satisfy the close.
J
Jorge Aparicio 已提交
1426
                self.ibox(0)?;
1427
            }
C
csmoe 已提交
1428
            hir::ExprKind::Block(ref blk, opt_label) => {
1429
                if let Some(label) = opt_label {
1430
                    self.print_ident(label.ident)?;
1431 1432
                    self.word_space(":")?;
                }
1433
                // containing cbox, will be closed by print-block at }
J
Jorge Aparicio 已提交
1434
                self.cbox(indent_unit)?;
1435
                // head-box, will be closed by print-block after {
J
Jorge Aparicio 已提交
1436 1437
                self.ibox(0)?;
                self.print_block(&blk)?;
1438
            }
C
csmoe 已提交
1439
            hir::ExprKind::Assign(ref lhs, ref rhs) => {
1440 1441
                let prec = AssocOp::Assign.precedence() as i8;
                self.print_expr_maybe_paren(&lhs, prec + 1)?;
1442
                self.s.space()?;
J
Jorge Aparicio 已提交
1443
                self.word_space("=")?;
1444
                self.print_expr_maybe_paren(&rhs, prec)?;
1445
            }
C
csmoe 已提交
1446
            hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1447 1448
                let prec = AssocOp::Assign.precedence() as i8;
                self.print_expr_maybe_paren(&lhs, prec + 1)?;
1449 1450
                self.s.space()?;
                self.s.word(op.node.as_str())?;
J
Jorge Aparicio 已提交
1451
                self.word_space("=")?;
1452
                self.print_expr_maybe_paren(&rhs, prec)?;
1453
            }
C
csmoe 已提交
1454
            hir::ExprKind::Field(ref expr, ident) => {
1455
                self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1456
                self.s.word(".")?;
1457
                self.print_ident(ident)?;
1458
            }
C
csmoe 已提交
1459
            hir::ExprKind::Index(ref expr, ref index) => {
1460
                self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1461
                self.s.word("[")?;
J
Jorge Aparicio 已提交
1462
                self.print_expr(&index)?;
1463
                self.s.word("]")?;
1464
            }
C
csmoe 已提交
1465
            hir::ExprKind::Path(ref qpath) => {
1466
                self.print_qpath(qpath, true)?
1467
            }
C
csmoe 已提交
1468
            hir::ExprKind::Break(destination, ref opt_expr) => {
1469 1470
                self.s.word("break")?;
                self.s.space()?;
1471
                if let Some(label) = destination.label {
1472
                    self.print_ident(label.ident)?;
1473
                    self.s.space()?;
1474
                }
1475
                if let Some(ref expr) = *opt_expr {
1476
                    self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1477
                    self.s.space()?;
1478
                }
1479
            }
C
csmoe 已提交
1480
            hir::ExprKind::Continue(destination) => {
1481 1482
                self.s.word("continue")?;
                self.s.space()?;
1483
                if let Some(label) = destination.label {
1484
                    self.print_ident(label.ident)?;
1485
                    self.s.space()?
1486 1487
                }
            }
C
csmoe 已提交
1488
            hir::ExprKind::Ret(ref result) => {
1489
                self.s.word("return")?;
L
ljedrz 已提交
1490 1491 1492
                if let Some(ref expr) = *result {
                    self.s.word(" ")?;
                    self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1493 1494
                }
            }
C
csmoe 已提交
1495
            hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1496
                self.s.word("asm!")?;
J
Jorge Aparicio 已提交
1497
                self.popen()?;
1498
                self.print_string(&a.asm.as_str(), a.asm_str_style)?;
J
Jorge Aparicio 已提交
1499
                self.word_space(":")?;
1500

1501
                let mut out_idx = 0;
J
Jorge Aparicio 已提交
1502
                self.commasep(Inconsistent, &a.outputs, |s, out| {
1503 1504
                    let constraint = out.constraint.as_str();
                    let mut ch = constraint.chars();
1505 1506 1507 1508
                    match ch.next() {
                        Some('=') if out.is_rw => {
                            s.print_string(&format!("+{}", ch.as_str()),
                                           ast::StrStyle::Cooked)?
J
Jose Narvaez 已提交
1509
                        }
1510
                        _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
J
Jose Narvaez 已提交
1511
                    }
J
Jorge Aparicio 已提交
1512 1513 1514
                    s.popen()?;
                    s.print_expr(&outputs[out_idx])?;
                    s.pclose()?;
1515
                    out_idx += 1;
J
Jose Narvaez 已提交
1516
                    Ok(())
J
Jorge Aparicio 已提交
1517
                })?;
1518
                self.s.space()?;
J
Jorge Aparicio 已提交
1519
                self.word_space(":")?;
1520

1521
                let mut in_idx = 0;
J
Jorge Aparicio 已提交
1522
                self.commasep(Inconsistent, &a.inputs, |s, co| {
1523
                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
J
Jorge Aparicio 已提交
1524 1525 1526
                    s.popen()?;
                    s.print_expr(&inputs[in_idx])?;
                    s.pclose()?;
1527
                    in_idx += 1;
J
Jose Narvaez 已提交
1528
                    Ok(())
J
Jorge Aparicio 已提交
1529
                })?;
1530
                self.s.space()?;
J
Jorge Aparicio 已提交
1531
                self.word_space(":")?;
1532

J
Jorge Aparicio 已提交
1533
                self.commasep(Inconsistent, &a.clobbers, |s, co| {
1534
                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
J
Jose Narvaez 已提交
1535
                    Ok(())
J
Jorge Aparicio 已提交
1536
                })?;
1537

J
Jose Narvaez 已提交
1538
                let mut options = vec![];
1539 1540 1541 1542 1543 1544
                if a.volatile {
                    options.push("volatile");
                }
                if a.alignstack {
                    options.push("alignstack");
                }
1545
                if a.dialect == ast::AsmDialect::Intel {
1546 1547 1548 1549
                    options.push("intel");
                }

                if !options.is_empty() {
1550
                    self.s.space()?;
J
Jorge Aparicio 已提交
1551 1552 1553
                    self.word_space(":")?;
                    self.commasep(Inconsistent, &options, |s, &co| {
                        s.print_string(co, ast::StrStyle::Cooked)?;
J
Jose Narvaez 已提交
1554
                        Ok(())
J
Jorge Aparicio 已提交
1555
                    })?;
1556 1557
                }

J
Jorge Aparicio 已提交
1558
                self.pclose()?;
1559
            }
C
csmoe 已提交
1560
            hir::ExprKind::Yield(ref expr) => {
J
John Kåre Alsaker 已提交
1561
                self.word_space("yield")?;
1562
                self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
J
John Kåre Alsaker 已提交
1563
            }
1564 1565 1566 1567 1568
            hir::ExprKind::Err => {
                self.popen()?;
                self.s.word("/*ERROR*/")?;
                self.pclose()?;
            }
1569
        }
V
varkor 已提交
1570
        self.ann.post(self, AnnNode::Expr(expr))?;
1571 1572 1573 1574
        self.end()
    }

    pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
J
Jorge Aparicio 已提交
1575
        self.print_pat(&loc.pat)?;
1576
        if let Some(ref ty) = loc.ty {
J
Jorge Aparicio 已提交
1577 1578
            self.word_space(":")?;
            self.print_type(&ty)?;
1579 1580 1581 1582 1583
        }
        Ok(())
    }

    pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1584
        self.s.word(i.to_string())
1585 1586
    }

1587 1588
    pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
        if ident.is_raw_guess() {
1589
            self.s.word(format!("r#{}", ident.name))?;
1590
        } else {
1591
            self.s.word(ident.as_str().get())?;
1592
        }
V
varkor 已提交
1593
        self.ann.post(self, AnnNode::Name(&ident.name))
1594 1595 1596
    }

    pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1597
        self.print_ident(ast::Ident::with_empty_ctxt(name))
1598 1599
    }

N
Nick Cameron 已提交
1600
    pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
J
Jorge Aparicio 已提交
1601
        self.print_local_decl(loc)?;
1602
        self.s.space()?;
J
Jorge Aparicio 已提交
1603
        self.word_space("in")?;
1604 1605 1606
        self.print_expr(coll)
    }

1607 1608 1609 1610
    pub fn print_path(&mut self,
                      path: &hir::Path,
                      colons_before_params: bool)
                      -> io::Result<()> {
1611
        self.maybe_print_comment(path.span.lo())?;
1612

1613 1614
        for (i, segment) in path.segments.iter().enumerate() {
            if i > 0 {
1615
                self.s.word("::")?
1616
            }
1617
            if segment.ident.name != keywords::PathRoot.name() {
1618
               self.print_ident(segment.ident)?;
1619
               segment.with_generic_args(|generic_args| {
1620
                   self.print_generic_args(generic_args, segment.infer_types,
1621
                                           colons_before_params)
1622
               })?;
1623
            }
1624 1625 1626 1627 1628
        }

        Ok(())
    }

1629
    pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
1630
        if segment.ident.name != keywords::PathRoot.name() {
1631 1632 1633 1634 1635 1636 1637 1638
           self.print_ident(segment.ident)?;
           segment.with_generic_args(|generic_args| {
               self.print_generic_args(generic_args, segment.infer_types, false)
           })?;
        }
        Ok(())
    }

1639 1640 1641 1642
    pub fn print_qpath(&mut self,
                       qpath: &hir::QPath,
                       colons_before_params: bool)
                       -> io::Result<()> {
1643 1644 1645 1646 1647
        match *qpath {
            hir::QPath::Resolved(None, ref path) => {
                self.print_path(path, colons_before_params)
            }
            hir::QPath::Resolved(Some(ref qself), ref path) => {
1648
                self.s.word("<")?;
1649
                self.print_type(qself)?;
1650
                self.s.space()?;
1651 1652
                self.word_space("as")?;

1653 1654
                for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
                    if i > 0 {
1655
                        self.s.word("::")?
1656
                    }
1657
                    if segment.ident.name != keywords::PathRoot.name() {
1658
                        self.print_ident(segment.ident)?;
1659 1660 1661 1662
                        segment.with_generic_args(|generic_args| {
                            self.print_generic_args(generic_args,
                                                    segment.infer_types,
                                                    colons_before_params)
1663
                        })?;
1664
                    }
1665 1666
                }

1667 1668
                self.s.word(">")?;
                self.s.word("::")?;
1669
                let item_segment = path.segments.last().unwrap();
1670
                self.print_ident(item_segment.ident)?;
1671 1672 1673 1674
                item_segment.with_generic_args(|generic_args| {
                    self.print_generic_args(generic_args,
                                            item_segment.infer_types,
                                            colons_before_params)
1675
                })
1676 1677
            }
            hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1678
                self.s.word("<")?;
1679
                self.print_type(qself)?;
1680 1681
                self.s.word(">")?;
                self.s.word("::")?;
1682
                self.print_ident(item_segment.ident)?;
1683 1684 1685 1686
                item_segment.with_generic_args(|generic_args| {
                    self.print_generic_args(generic_args,
                                            item_segment.infer_types,
                                            colons_before_params)
1687
                })
1688
            }
1689 1690 1691
        }
    }

1692 1693
    fn print_generic_args(&mut self,
                             generic_args: &hir::GenericArgs,
1694
                             infer_types: bool,
1695
                             colons_before_params: bool)
N
Nick Cameron 已提交
1696
                             -> io::Result<()> {
1697
        if generic_args.parenthesized {
1698
            self.s.word("(")?;
1699
            self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1700
            self.s.word(")")?;
1701

1702 1703
            self.space_if_not_bol()?;
            self.word_space("->")?;
1704
            self.print_type(&generic_args.bindings[0].ty)?;
1705 1706 1707 1708 1709 1710 1711 1712 1713
        } else {
            let start = if colons_before_params { "::<" } else { "<" };
            let empty = Cell::new(true);
            let start_or_comma = |this: &mut Self| {
                if empty.get() {
                    empty.set(false);
                    this.s.word(start)
                } else {
                    this.word_space(",")
1714
                }
1715
            };
1716

V
varkor 已提交
1717 1718 1719 1720 1721 1722
            let mut nonelided_generic_args: bool = false;
            let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
                GenericArg::Lifetime(lt) => lt.is_elided(),
                _ => {
                    nonelided_generic_args = true;
                    true
1723
                }
V
varkor 已提交
1724 1725 1726
            });

            if nonelided_generic_args {
1727
                start_or_comma(self)?;
1728 1729
                self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
                    match generic_arg {
V
varkor 已提交
1730 1731
                        GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
                        GenericArg::Lifetime(_) => Ok(()),
1732
                        GenericArg::Type(ty) => s.print_type(ty),
V
varkor 已提交
1733
                        GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1734
                    }
1735
                })?;
V
varkor 已提交
1736 1737
            }

1738 1739
            // FIXME(eddyb) This would leak into error messages, e.g.:
            // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1740
            if infer_types && false {
1741 1742
                start_or_comma(self)?;
                self.s.word("..")?;
1743 1744
            }

1745
            for binding in generic_args.bindings.iter() {
1746
                start_or_comma(self)?;
1747
                self.print_ident(binding.ident)?;
1748 1749 1750 1751
                self.s.space()?;
                self.word_space("=")?;
                self.print_type(&binding.ty)?;
            }
1752

1753 1754
            if !empty.get() {
                self.s.word(">")?
1755 1756 1757 1758 1759 1760 1761
            }
        }

        Ok(())
    }

    pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1762
        self.maybe_print_comment(pat.span.lo())?;
V
varkor 已提交
1763
        self.ann.pre(self, AnnNode::Pat(pat))?;
J
Jose Narvaez 已提交
1764 1765
        // Pat isn't normalized, but the beauty of it
        // is that it doesn't matter
1766
        match pat.node {
1767
            PatKind::Wild => self.s.word("_")?,
L
ljedrz 已提交
1768
            PatKind::Binding(binding_mode, _, ident, ref sub) => {
1769
                match binding_mode {
1770
                    hir::BindingAnnotation::Ref => {
J
Jorge Aparicio 已提交
1771
                        self.word_nbsp("ref")?;
1772
                        self.print_mutability(hir::MutImmutable)?;
1773
                    }
1774 1775 1776 1777 1778 1779
                    hir::BindingAnnotation::RefMut => {
                        self.word_nbsp("ref")?;
                        self.print_mutability(hir::MutMutable)?;
                    }
                    hir::BindingAnnotation::Unannotated => {}
                    hir::BindingAnnotation::Mutable => {
J
Jorge Aparicio 已提交
1780
                        self.word_nbsp("mut")?;
1781 1782
                    }
                }
1783
                self.print_ident(ident)?;
1784
                if let Some(ref p) = *sub {
1785
                    self.s.word("@")?;
1786
                    self.print_pat(&p)?;
1787 1788
                }
            }
1789 1790
            PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
                self.print_qpath(qpath, true)?;
1791 1792 1793 1794 1795 1796
                self.popen()?;
                if let Some(ddpos) = ddpos {
                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
                    if ddpos != 0 {
                        self.word_space(",")?;
                    }
1797
                    self.s.word("..")?;
1798
                    if ddpos != elts.len() {
1799
                        self.s.word(",")?;
1800
                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1801
                    }
1802
                } else {
1803
                    self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1804
                }
1805
                self.pclose()?;
1806
            }
1807 1808
            PatKind::Path(ref qpath) => {
                self.print_qpath(qpath, true)?;
1809
            }
1810 1811
            PatKind::Struct(ref qpath, ref fields, etc) => {
                self.print_qpath(qpath, true)?;
J
Jorge Aparicio 已提交
1812 1813 1814
                self.nbsp()?;
                self.word_space("{")?;
                self.commasep_cmnt(Consistent,
J
Jorge Aparicio 已提交
1815 1816 1817 1818
                                   &fields[..],
                                   |s, f| {
                                       s.cbox(indent_unit)?;
                                       if !f.node.is_shorthand {
1819
                                           s.print_ident(f.node.ident)?;
J
Jorge Aparicio 已提交
1820 1821 1822 1823 1824 1825
                                           s.word_nbsp(":")?;
                                       }
                                       s.print_pat(&f.node.pat)?;
                                       s.end()
                                   },
                                   |f| f.node.pat.span)?;
1826
                if etc {
N
Nick Cameron 已提交
1827
                    if !fields.is_empty() {
J
Jorge Aparicio 已提交
1828
                        self.word_space(",")?;
N
Nick Cameron 已提交
1829
                    }
1830
                    self.s.word("..")?;
1831
                }
1832 1833
                self.s.space()?;
                self.s.word("}")?;
1834
            }
1835
            PatKind::Tuple(ref elts, ddpos) => {
J
Jorge Aparicio 已提交
1836
                self.popen()?;
1837 1838 1839 1840 1841
                if let Some(ddpos) = ddpos {
                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
                    if ddpos != 0 {
                        self.word_space(",")?;
                    }
1842
                    self.s.word("..")?;
1843
                    if ddpos != elts.len() {
1844
                        self.s.word(",")?;
1845 1846 1847 1848 1849
                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
                    }
                } else {
                    self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
                    if elts.len() == 1 {
1850
                        self.s.word(",")?;
1851
                    }
1852
                }
J
Jorge Aparicio 已提交
1853
                self.pclose()?;
1854
            }
1855
            PatKind::Box(ref inner) => {
1856 1857 1858 1859
                let is_range_inner = match inner.node {
                    PatKind::Range(..) => true,
                    _ => false,
                };
1860
                self.s.word("box ")?;
1861 1862 1863
                if is_range_inner {
                    self.popen()?;
                }
J
Jorge Aparicio 已提交
1864
                self.print_pat(&inner)?;
1865 1866 1867
                if is_range_inner {
                    self.pclose()?;
                }
1868
            }
1869
            PatKind::Ref(ref inner, mutbl) => {
1870 1871 1872 1873
                let is_range_inner = match inner.node {
                    PatKind::Range(..) => true,
                    _ => false,
                };
1874
                self.s.word("&")?;
1875
                if mutbl == hir::MutMutable {
1876
                    self.s.word("mut ")?;
1877
                }
1878 1879 1880
                if is_range_inner {
                    self.popen()?;
                }
J
Jorge Aparicio 已提交
1881
                self.print_pat(&inner)?;
1882 1883 1884
                if is_range_inner {
                    self.pclose()?;
                }
1885
            }
J
Jorge Aparicio 已提交
1886
            PatKind::Lit(ref e) => self.print_expr(&e)?,
1887
            PatKind::Range(ref begin, ref end, ref end_kind) => {
J
Jorge Aparicio 已提交
1888
                self.print_expr(&begin)?;
1889
                self.s.space()?;
1890
                match *end_kind {
1891 1892
                    RangeEnd::Included => self.s.word("...")?,
                    RangeEnd::Excluded => self.s.word("..")?,
1893
                }
J
Jorge Aparicio 已提交
1894
                self.print_expr(&end)?;
1895
            }
1896
            PatKind::Slice(ref before, ref slice, ref after) => {
1897
                self.s.word("[")?;
J
Jorge Aparicio 已提交
1898
                self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1899
                if let Some(ref p) = *slice {
N
Nick Cameron 已提交
1900
                    if !before.is_empty() {
J
Jorge Aparicio 已提交
1901
                        self.word_space(",")?;
N
Nick Cameron 已提交
1902
                    }
1903 1904 1905
                    if let PatKind::Wild = p.node {
                        // Print nothing
                    } else {
J
Jorge Aparicio 已提交
1906
                        self.print_pat(&p)?;
1907
                    }
1908
                    self.s.word("..")?;
N
Nick Cameron 已提交
1909
                    if !after.is_empty() {
J
Jorge Aparicio 已提交
1910
                        self.word_space(",")?;
N
Nick Cameron 已提交
1911
                    }
1912
                }
J
Jorge Aparicio 已提交
1913
                self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1914
                self.s.word("]")?;
1915 1916
            }
        }
V
varkor 已提交
1917
        self.ann.post(self, AnnNode::Pat(pat))
1918 1919 1920 1921 1922 1923
    }

    fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
        // I have no idea why this check is necessary, but here it
        // is :(
        if arm.attrs.is_empty() {
1924
            self.s.space()?;
1925
        }
J
Jorge Aparicio 已提交
1926 1927 1928
        self.cbox(indent_unit)?;
        self.ibox(0)?;
        self.print_outer_attributes(&arm.attrs)?;
1929 1930 1931 1932 1933
        let mut first = true;
        for p in &arm.pats {
            if first {
                first = false;
            } else {
1934
                self.s.space()?;
J
Jorge Aparicio 已提交
1935
                self.word_space("|")?;
1936
            }
J
Jorge Aparicio 已提交
1937
            self.print_pat(&p)?;
1938
        }
1939
        self.s.space()?;
F
F001 已提交
1940 1941 1942 1943 1944 1945 1946 1947
        if let Some(ref g) = arm.guard {
            match g {
                hir::Guard::If(e) => {
                    self.word_space("if")?;
                    self.print_expr(&e)?;
                    self.s.space()?;
                }
            }
1948
        }
J
Jorge Aparicio 已提交
1949
        self.word_space("=>")?;
1950 1951

        match arm.body.node {
C
csmoe 已提交
1952
            hir::ExprKind::Block(ref blk, opt_label) => {
1953
                if let Some(label) = opt_label {
1954
                    self.print_ident(label.ident)?;
1955 1956
                    self.word_space(":")?;
                }
1957
                // the block will close the pattern's ibox
J
Jorge Aparicio 已提交
1958
                self.print_block_unclosed_indent(&blk, indent_unit)?;
1959 1960 1961

                // If it is a user-provided unsafe block, print a comma after it
                if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1962
                    self.s.word(",")?;
1963 1964 1965
                }
            }
            _ => {
J
Jorge Aparicio 已提交
1966 1967
                self.end()?; // close the ibox for the pattern
                self.print_expr(&arm.body)?;
1968
                self.s.word(",")?;
1969 1970 1971 1972 1973 1974 1975
            }
        }
        self.end() // close enclosing cbox
    }

    pub fn print_fn(&mut self,
                    decl: &hir::FnDecl,
W
Without Boats 已提交
1976
                    header: hir::FnHeader,
V
Vadim Petrochenkov 已提交
1977
                    name: Option<ast::Name>,
1978
                    generics: &hir::Generics,
1979
                    vis: &hir::Visibility,
1980
                    arg_names: &[ast::Ident],
1981
                    body_id: Option<hir::BodyId>)
N
Nick Cameron 已提交
1982
                    -> io::Result<()> {
W
Without Boats 已提交
1983
        self.print_fn_header_info(header, vis)?;
1984 1985

        if let Some(name) = name {
J
Jorge Aparicio 已提交
1986 1987
            self.nbsp()?;
            self.print_name(name)?;
1988
        }
1989
        self.print_generic_params(&generics.params)?;
1990

J
Jorge Aparicio 已提交
1991
        self.popen()?;
1992 1993 1994 1995 1996
        let mut i = 0;
        // Make sure we aren't supplied *both* `arg_names` and `body_id`.
        assert!(arg_names.is_empty() || body_id.is_none());
        self.commasep(Inconsistent, &decl.inputs, |s, ty| {
            s.ibox(indent_unit)?;
1997
            if let Some(arg_name) = arg_names.get(i) {
1998
                s.s.word(arg_name.as_str().get())?;
1999 2000
                s.s.word(":")?;
                s.s.space()?;
2001 2002
            } else if let Some(body_id) = body_id {
                s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2003 2004
                s.s.word(":")?;
                s.s.space()?;
2005 2006 2007 2008 2009
            }
            i += 1;
            s.print_type(ty)?;
            s.end()
        })?;
D
Dan Robertson 已提交
2010
        if decl.c_variadic {
2011
            self.s.word(", ...")?;
2012
        }
J
Jorge Aparicio 已提交
2013
        self.pclose()?;
2014

2015 2016
        self.print_fn_output(decl)?;
        self.print_where_clause(&generics.where_clause)
2017 2018
    }

2019
    fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2020
        self.s.word("|")?;
2021 2022 2023 2024
        let mut i = 0;
        self.commasep(Inconsistent, &decl.inputs, |s, ty| {
            s.ibox(indent_unit)?;

2025
            s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2026 2027
            i += 1;

C
TyKind  
csmoe 已提交
2028
            if let hir::TyKind::Infer = ty.node {
2029 2030
                // Print nothing
            } else {
2031 2032
                s.s.word(":")?;
                s.s.space()?;
2033 2034 2035 2036
                s.print_type(ty)?;
            }
            s.end()
        })?;
2037
        self.s.word("|")?;
2038 2039 2040 2041 2042

        if let hir::DefaultReturn(..) = decl.output {
            return Ok(());
        }

J
Jorge Aparicio 已提交
2043 2044
        self.space_if_not_bol()?;
        self.word_space("->")?;
2045 2046
        match decl.output {
            hir::Return(ref ty) => {
J
Jorge Aparicio 已提交
2047
                self.print_type(&ty)?;
2048
                self.maybe_print_comment(ty.span.lo())
2049 2050 2051 2052 2053
            }
            hir::DefaultReturn(..) => unreachable!(),
        }
    }

N
Nick Cameron 已提交
2054
    pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2055 2056 2057 2058 2059 2060
        match capture_clause {
            hir::CaptureByValue => self.word_space("move"),
            hir::CaptureByRef => Ok(()),
        }
    }

2061 2062
    pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
                        -> io::Result<()> {
2063
        if !bounds.is_empty() {
2064
            self.s.word(prefix)?;
2065 2066
            let mut first = true;
            for bound in bounds {
2067 2068 2069
                if !(first && prefix.is_empty()) {
                    self.nbsp()?;
                }
2070 2071 2072
                if first {
                    first = false;
                } else {
J
Jorge Aparicio 已提交
2073
                    self.word_space("+")?;
2074 2075
                }

2076
                match bound {
V
varkor 已提交
2077
                    GenericBound::Trait(tref, modifier) => {
2078 2079 2080 2081
                        if modifier == &TraitBoundModifier::Maybe {
                            self.s.word("?")?;
                        }
                        self.print_poly_trait_ref(tref)?;
2082
                    }
V
varkor 已提交
2083
                    GenericBound::Outlives(lt) => {
2084
                        self.print_lifetime(lt)?;
2085
                    }
2086
                }
2087 2088
            }
        }
2089
        Ok(())
2090 2091
    }

V
varkor 已提交
2092
    pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2093 2094
        if !generic_params.is_empty() {
            self.s.word("<")?;
2095

2096
            self.commasep(Inconsistent, generic_params, |s, param| {
V
varkor 已提交
2097
                s.print_generic_param(param)
2098
            })?;
2099

2100
            self.s.word(">")?;
2101 2102 2103 2104
        }
        Ok(())
    }

V
varkor 已提交
2105
    pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
V
varkor 已提交
2106 2107 2108 2109
        if let GenericParamKind::Const { .. } = param.kind {
            self.word_space("const")?;
        }

V
Vadim Petrochenkov 已提交
2110
        self.print_ident(param.name.ident())?;
V
varkor 已提交
2111

V
varkor 已提交
2112
        match param.kind {
V
varkor 已提交
2113
            GenericParamKind::Lifetime { .. } => {
V
varkor 已提交
2114
                let mut sep = ":";
V
varkor 已提交
2115 2116
                for bound in &param.bounds {
                    match bound {
V
varkor 已提交
2117
                        GenericBound::Outlives(lt) => {
V
varkor 已提交
2118 2119 2120 2121 2122 2123
                            self.s.word(sep)?;
                            self.print_lifetime(lt)?;
                            sep = "+";
                        }
                        _ => bug!(),
                    }
V
varkor 已提交
2124 2125 2126
                }
                Ok(())
            }
V
varkor 已提交
2127 2128
            GenericParamKind::Type { ref default, .. } => {
                self.print_bounds(":", &param.bounds)?;
V
varkor 已提交
2129 2130 2131 2132 2133 2134 2135 2136
                match default {
                    Some(default) => {
                        self.s.space()?;
                        self.word_space("=")?;
                        self.print_type(&default)
                    }
                    _ => Ok(()),
                }
2137
            }
V
varkor 已提交
2138 2139 2140 2141
            GenericParamKind::Const { ref ty } => {
                self.word_space(":")?;
                self.print_type(ty)
            }
2142 2143 2144
        }
    }

V
varkor 已提交
2145
    pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
V
Vadim Petrochenkov 已提交
2146
        self.print_ident(lifetime.name.ident())
V
varkor 已提交
2147 2148
    }

N
Nick Cameron 已提交
2149
    pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2150
        if where_clause.predicates.is_empty() {
J
Jose Narvaez 已提交
2151
            return Ok(());
2152 2153
        }

2154
        self.s.space()?;
J
Jorge Aparicio 已提交
2155
        self.word_space("where")?;
2156 2157 2158

        for (i, predicate) in where_clause.predicates.iter().enumerate() {
            if i != 0 {
J
Jorge Aparicio 已提交
2159
                self.word_space(",")?;
2160 2161 2162
            }

            match predicate {
2163 2164 2165 2166 2167 2168 2169
                &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
                    ref bound_generic_params,
                    ref bounded_ty,
                    ref bounds,
                    ..
                }) => {
                    self.print_formal_generic_params(bound_generic_params)?;
J
Jorge Aparicio 已提交
2170 2171
                    self.print_type(&bounded_ty)?;
                    self.print_bounds(":", bounds)?;
2172 2173 2174 2175
                }
                &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
                                                                                ref bounds,
                                                                                ..}) => {
J
Jorge Aparicio 已提交
2176
                    self.print_lifetime(lifetime)?;
2177
                    self.s.word(":")?;
2178 2179

                    for (i, bound) in bounds.iter().enumerate() {
V
varkor 已提交
2180
                        match bound {
V
varkor 已提交
2181
                            GenericBound::Outlives(lt) => {
V
varkor 已提交
2182 2183 2184 2185
                                self.print_lifetime(lt)?;
                            }
                            _ => bug!(),
                        }
2186 2187

                        if i != 0 {
2188
                            self.s.word(":")?;
2189 2190 2191
                        }
                    }
                }
2192 2193 2194 2195
                &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
                                                                        ref rhs_ty,
                                                                        ..}) => {
                    self.print_type(lhs_ty)?;
2196
                    self.s.space()?;
J
Jorge Aparicio 已提交
2197
                    self.word_space("=")?;
2198
                    self.print_type(rhs_ty)?;
2199 2200 2201 2202 2203 2204 2205
                }
            }
        }

        Ok(())
    }

N
Nick Cameron 已提交
2206
    pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2207 2208 2209 2210 2211 2212 2213
        match mutbl {
            hir::MutMutable => self.word_nbsp("mut"),
            hir::MutImmutable => Ok(()),
        }
    }

    pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
J
Jorge Aparicio 已提交
2214
        self.print_mutability(mt.mutbl)?;
2215
        self.print_type(&mt.ty)
2216 2217 2218 2219 2220 2221 2222
    }

    pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
        if let hir::DefaultReturn(..) = decl.output {
            return Ok(());
        }

J
Jorge Aparicio 已提交
2223 2224 2225
        self.space_if_not_bol()?;
        self.ibox(indent_unit)?;
        self.word_space("->")?;
2226 2227
        match decl.output {
            hir::DefaultReturn(..) => unreachable!(),
J
Jorge Aparicio 已提交
2228
            hir::Return(ref ty) => self.print_type(&ty)?,
2229
        }
J
Jorge Aparicio 已提交
2230
        self.end()?;
2231 2232

        match decl.output {
2233
            hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
N
Nick Cameron 已提交
2234
            _ => Ok(()),
2235 2236 2237 2238
        }
    }

    pub fn print_ty_fn(&mut self,
2239
                       abi: Abi,
2240 2241
                       unsafety: hir::Unsafety,
                       decl: &hir::FnDecl,
2242
                       name: Option<ast::Name>,
2243
                       generic_params: &[hir::GenericParam],
2244
                       arg_names: &[ast::Ident])
2245
                       -> io::Result<()> {
J
Jorge Aparicio 已提交
2246
        self.ibox(indent_unit)?;
2247
        if !generic_params.is_empty() {
2248
            self.s.word("for")?;
2249
            self.print_generic_params(generic_params)?;
2250 2251
        }
        let generics = hir::Generics {
2252
            params: hir::HirVec::new(),
2253
            where_clause: hir::WhereClause {
L
ljedrz 已提交
2254
                hir_id: hir::DUMMY_HIR_ID,
2255
                predicates: hir::HirVec::new(),
2256
            },
2257
            span: syntax_pos::DUMMY_SP,
2258
        };
J
Jorge Aparicio 已提交
2259
        self.print_fn(decl,
W
Without Boats 已提交
2260
                      hir::FnHeader {
2261 2262 2263 2264
                          unsafety,
                          abi,
                          constness: hir::Constness::NotConst,
                          asyncness: hir::IsAsync::NotAsync,
W
Without Boats 已提交
2265
                      },
J
Jorge Aparicio 已提交
2266 2267
                      name,
                      &generics,
2268 2269
                      &Spanned { span: syntax_pos::DUMMY_SP,
                                 node: hir::VisibilityKind::Inherited },
2270
                      arg_names,
2271
                      None)?;
2272 2273 2274
        self.end()
    }

N
Nick Cameron 已提交
2275
    pub fn maybe_print_trailing_comment(&mut self,
2276
                                        span: syntax_pos::Span,
2277
                                        next_pos: Option<BytePos>)
N
Nick Cameron 已提交
2278
                                        -> io::Result<()> {
2279 2280
        let cm = match self.cm {
            Some(cm) => cm,
N
Nick Cameron 已提交
2281
            _ => return Ok(()),
2282
        };
2283 2284 2285 2286
        if let Some(ref cmnt) = self.next_comment() {
            if (*cmnt).style != comments::Trailing {
                return Ok(());
            }
2287
            let span_line = cm.lookup_char_pos(span.hi());
2288 2289 2290 2291 2292
            let comment_line = cm.lookup_char_pos((*cmnt).pos);
            let mut next = (*cmnt).pos + BytePos(1);
            if let Some(p) = next_pos {
                next = p;
            }
2293
            if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2294 2295
               span_line.line == comment_line.line {
                self.print_comment(cmnt)?;
2296 2297 2298 2299 2300 2301 2302 2303 2304
            }
        }
        Ok(())
    }

    pub fn print_remaining_comments(&mut self) -> io::Result<()> {
        // If there aren't any remaining comments, then we need to manually
        // make sure there is a line break at the end.
        if self.next_comment().is_none() {
2305
            self.s.hardbreak()?;
2306
        }
L
leonardo.yvens 已提交
2307 2308
        while let Some(ref cmnt) = self.next_comment() {
            self.print_comment(cmnt)?
2309 2310 2311 2312 2313
        }
        Ok(())
    }

    pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2314
                                                  opt_abi: Option<Abi>)
N
Nick Cameron 已提交
2315
                                                  -> io::Result<()> {
2316
        match opt_abi {
2317
            Some(Abi::Rust) => Ok(()),
2318
            Some(abi) => {
J
Jorge Aparicio 已提交
2319
                self.word_nbsp("extern")?;
2320
                self.word_nbsp(abi.to_string())
2321
            }
N
Nick Cameron 已提交
2322
            None => Ok(()),
2323 2324 2325
        }
    }

2326
    pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2327 2328
        match opt_abi {
            Some(abi) => {
J
Jorge Aparicio 已提交
2329
                self.word_nbsp("extern")?;
2330
                self.word_nbsp(abi.to_string())
2331
            }
N
Nick Cameron 已提交
2332
            None => Ok(()),
2333 2334 2335 2336
        }
    }

    pub fn print_fn_header_info(&mut self,
W
Without Boats 已提交
2337
                                header: hir::FnHeader,
2338
                                vis: &hir::Visibility)
N
Nick Cameron 已提交
2339
                                -> io::Result<()> {
2340
        self.s.word(visibility_qualified(vis, ""))?;
2341

W
Without Boats 已提交
2342
        match header.constness {
2343
            hir::Constness::NotConst => {}
J
Jorge Aparicio 已提交
2344
            hir::Constness::Const => self.word_nbsp("const")?,
2345 2346
        }

W
Without Boats 已提交
2347 2348 2349 2350 2351 2352 2353 2354
        match header.asyncness {
            hir::IsAsync::NotAsync => {}
            hir::IsAsync::Async => self.word_nbsp("async")?,
        }

        self.print_unsafety(header.unsafety)?;

        if header.abi != Abi::Rust {
J
Jorge Aparicio 已提交
2355
            self.word_nbsp("extern")?;
2356
            self.word_nbsp(header.abi.to_string())?;
2357 2358
        }

2359
        self.s.word("fn")
2360 2361 2362 2363 2364 2365 2366 2367
    }

    pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
        match s {
            hir::Unsafety::Normal => Ok(()),
            hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
        }
    }
2368 2369 2370 2371 2372 2373 2374

    pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
        match s {
            hir::IsAuto::Yes => self.word_nbsp("auto"),
            hir::IsAuto::No => Ok(()),
        }
    }
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
}

// Dup'ed from parse::classify, but adapted for the HIR.
/// Does this expression require a semicolon to be treated
/// as a statement? The negation of this: 'can this expression
/// be used as a statement without a semicolon' -- is used
/// as an early-bail-out in the parser so that, for instance,
///     if true {...} else {...}
///      |x| 5
/// isn't parsed as (if true {...} else {...} | x) | 5
fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
    match e.node {
C
csmoe 已提交
2387 2388 2389 2390 2391
        hir::ExprKind::If(..) |
        hir::ExprKind::Match(..) |
        hir::ExprKind::Block(..) |
        hir::ExprKind::While(..) |
        hir::ExprKind::Loop(..) => false,
N
Nick Cameron 已提交
2392
        _ => true,
2393 2394 2395 2396 2397 2398
    }
}

/// this statement requires a semicolon after it.
/// note that in one case (stmt_semi), we've already
/// seen the semicolon, and thus don't need another.
C
csmoe 已提交
2399
fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2400
    match *stmt {
2401 2402 2403 2404
        hir::StmtKind::Local(_) => true,
        hir::StmtKind::Item(_) => false,
        hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
        hir::StmtKind::Semi(..) => false,
2405 2406
    }
}
2407

C
csmoe 已提交
2408
fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
M
Mark Mansi 已提交
2409
    use crate::hir::BinOpKind::*;
2410
    match op {
C
csmoe 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
        Add => AssocOp::Add,
        Sub => AssocOp::Subtract,
        Mul => AssocOp::Multiply,
        Div => AssocOp::Divide,
        Rem => AssocOp::Modulus,

        And => AssocOp::LAnd,
        Or => AssocOp::LOr,

        BitXor => AssocOp::BitXor,
        BitAnd => AssocOp::BitAnd,
        BitOr => AssocOp::BitOr,
        Shl => AssocOp::ShiftLeft,
        Shr => AssocOp::ShiftRight,

        Eq => AssocOp::Equal,
        Lt => AssocOp::Less,
        Le => AssocOp::LessEqual,
        Ne => AssocOp::NotEqual,
        Ge => AssocOp::GreaterEqual,
        Gt => AssocOp::Greater,
2432 2433 2434
    }
}

2435 2436
/// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2437 2438 2439
/// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
    match value.node {
C
csmoe 已提交
2440
        hir::ExprKind::Struct(..) => true,
2441

C
csmoe 已提交
2442 2443 2444
        hir::ExprKind::Assign(ref lhs, ref rhs) |
        hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
        hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2445 2446 2447
            // X { y: 1 } + X { y: 2 }
            contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
        }
C
csmoe 已提交
2448 2449 2450 2451 2452
        hir::ExprKind::Unary(_, ref x) |
        hir::ExprKind::Cast(ref x, _) |
        hir::ExprKind::Type(ref x, _) |
        hir::ExprKind::Field(ref x, _) |
        hir::ExprKind::Index(ref x, _) => {
2453 2454 2455 2456
            // &X { y: 1 }, X { y: 1 }.y
            contains_exterior_struct_lit(&x)
        }

C
csmoe 已提交
2457
        hir::ExprKind::MethodCall(.., ref exprs) => {
2458 2459 2460 2461 2462 2463 2464
            // X { y: 1 }.bar(...)
            contains_exterior_struct_lit(&exprs[0])
        }

        _ => false,
    }
}