print.rs 89.3 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
    fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item> {
52 53
        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
    fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item> {
62 63
        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 == hir::MutMutable {
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
                self.head(visibility_qualified(&item.vis, "global asm"))?;
625
                self.s.word(ga.asm.as_str().to_string())?;
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 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
        match struct_def {
            hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
                if let hir::VariantData::Tuple(..) = struct_def {
                    self.popen()?;
                    self.commasep(Inconsistent, struct_def.fields(), |s, field| {
                        s.maybe_print_comment(field.span.lo())?;
                        s.print_outer_attributes(&field.attrs)?;
                        s.print_visibility(&field.vis)?;
                        s.print_type(&field.ty)
                    })?;
                    self.pclose()?;
                }
                self.print_where_clause(&generics.where_clause)?;
                if print_finalizer {
                    self.s.word(";")?;
                }
                self.end()?;
                self.end() // close the outer-box
881
            }
882 883 884 885
            hir::VariantData::Struct(..) => {
                self.print_where_clause(&generics.where_clause)?;
                self.nbsp()?;
                self.bopen()?;
J
Jorge Aparicio 已提交
886
                self.hardbreak_if_not_bol()?;
887

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

                self.bclose(span)
            }
901 902 903 904
        }
    }

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

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

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

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

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    pub fn print_local(
        &mut self,
        init: Option<&hir::Expr>,
        decl: impl Fn(&mut Self) -> io::Result<()>
    ) -> io::Result<()> {
        self.space_if_not_bol()?;
        self.ibox(indent_unit)?;
        self.word_nbsp("let")?;

        self.ibox(indent_unit)?;
        decl(self)?;
        self.end()?;

        if let Some(ref init) = init {
            self.nbsp()?;
            self.word_space("=")?;
            self.print_expr(&init)?;
        }
        self.end()
    }

1019
    pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1020
        self.maybe_print_comment(st.span.lo())?;
1021
        match st.node {
1022
            hir::StmtKind::Local(ref loc) => {
1023
                self.print_local(loc.init.deref(), |this| this.print_local_decl(&loc))?;
1024
            }
1025 1026
            hir::StmtKind::Item(item) => {
                self.ann.nested(self, Nested::Item(item))?
1027
            }
1028
            hir::StmtKind::Expr(ref expr) => {
J
Jorge Aparicio 已提交
1029 1030
                self.space_if_not_bol()?;
                self.print_expr(&expr)?;
1031
            }
1032
            hir::StmtKind::Semi(ref expr) => {
J
Jorge Aparicio 已提交
1033 1034
                self.space_if_not_bol()?;
                self.print_expr(&expr)?;
1035
                self.s.word(";")?;
1036 1037 1038
            }
        }
        if stmt_ends_with_semi(&st.node) {
1039
            self.s.word(";")?;
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        }
        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 已提交
1052 1053 1054 1055
    pub fn print_block_unclosed_indent(&mut self,
                                       blk: &hir::Block,
                                       indented: usize)
                                       -> io::Result<()> {
1056 1057 1058 1059 1060
        self.print_block_maybe_unclosed(blk, indented, &[], false)
    }

    pub fn print_block_with_attrs(&mut self,
                                  blk: &hir::Block,
N
Nick Cameron 已提交
1061 1062
                                  attrs: &[ast::Attribute])
                                  -> io::Result<()> {
1063 1064 1065 1066 1067 1068
        self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
    }

    pub fn print_block_maybe_unclosed(&mut self,
                                      blk: &hir::Block,
                                      indented: usize,
1069
                                      attrs: &[ast::Attribute],
N
Nick Cameron 已提交
1070 1071
                                      close_box: bool)
                                      -> io::Result<()> {
1072
        match blk.rules {
J
Jorge Aparicio 已提交
1073 1074 1075
            hir::UnsafeBlock(..) => self.word_space("unsafe")?,
            hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
            hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
N
Nick Cameron 已提交
1076
            hir::DefaultBlock => (),
1077
        }
1078
        self.maybe_print_comment(blk.span.lo())?;
V
varkor 已提交
1079
        self.ann.pre(self, AnnNode::Block(blk))?;
J
Jorge Aparicio 已提交
1080
        self.bopen()?;
1081

J
Jorge Aparicio 已提交
1082
        self.print_inner_attributes(attrs)?;
1083 1084

        for st in &blk.stmts {
J
Jorge Aparicio 已提交
1085
            self.print_stmt(st)?;
1086
        }
L
ljedrz 已提交
1087 1088 1089 1090
        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()))?;
1091
        }
J
Jorge Aparicio 已提交
1092
        self.bclose_maybe_open(blk.span, indented, close_box)?;
V
varkor 已提交
1093
        self.ann.post(self, AnnNode::Block(blk))
1094 1095 1096 1097 1098 1099 1100
    }

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

N
Nick Cameron 已提交
1127 1128
    pub fn print_if(&mut self,
                    test: &hir::Expr,
1129
                    blk: &hir::Expr,
N
Nick Cameron 已提交
1130 1131
                    elseopt: Option<&hir::Expr>)
                    -> io::Result<()> {
J
Jorge Aparicio 已提交
1132
        self.head("if")?;
1133
        self.print_expr_as_cond(test)?;
1134
        self.s.space()?;
1135
        self.print_expr(blk)?;
1136 1137 1138
        self.print_else(elseopt)
    }

N
Nick Cameron 已提交
1139 1140 1141 1142 1143 1144
    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 已提交
1145 1146
        self.head("if let")?;
        self.print_pat(pat)?;
1147
        self.s.space()?;
J
Jorge Aparicio 已提交
1148
        self.word_space("=")?;
1149
        self.print_expr_as_cond(expr)?;
1150
        self.s.space()?;
J
Jorge Aparicio 已提交
1151
        self.print_block(blk)?;
1152 1153 1154
        self.print_else(elseopt)
    }

1155 1156 1157
    pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
        self.ann.nested(self, Nested::Body(constant.body))
    }
1158

1159
    fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1160 1161
        self.popen()?;
        self.commasep_exprs(Inconsistent, args)?;
1162 1163 1164
        self.pclose()
    }

1165
    pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1166
        let needs_par = expr.precedence().order() < prec;
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        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 已提交
1183 1184 1185
            hir::ExprKind::Closure(..) |
            hir::ExprKind::Ret(..) |
            hir::ExprKind::Break(..) => true,
1186 1187 1188 1189

            _ => contains_exterior_struct_lit(expr),
        };

1190
        if needs_par {
J
Jorge Aparicio 已提交
1191
            self.popen()?;
1192
        }
J
Jorge Aparicio 已提交
1193
        self.print_expr(expr)?;
1194
        if needs_par {
J
Jorge Aparicio 已提交
1195
            self.pclose()?;
1196 1197 1198 1199
        }
        Ok(())
    }

1200
    fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1201
        self.ibox(indent_unit)?;
1202
        self.s.word("[")?;
1203
        self.commasep_exprs(Inconsistent, exprs)?;
1204
        self.s.word("]")?;
1205 1206 1207
        self.end()
    }

1208
    fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
J
Jorge Aparicio 已提交
1209
        self.ibox(indent_unit)?;
1210
        self.s.word("[")?;
J
Jorge Aparicio 已提交
1211 1212
        self.print_expr(element)?;
        self.word_space(";")?;
1213
        self.print_anon_const(count)?;
1214
        self.s.word("]")?;
1215 1216 1217 1218
        self.end()
    }

    fn print_expr_struct(&mut self,
1219
                         qpath: &hir::QPath,
1220
                         fields: &[hir::Field],
N
Nick Cameron 已提交
1221 1222
                         wth: &Option<P<hir::Expr>>)
                         -> io::Result<()> {
1223
        self.print_qpath(qpath, true)?;
1224
        self.s.word("{")?;
J
Jorge Aparicio 已提交
1225
        self.commasep_cmnt(Consistent,
J
Jorge Aparicio 已提交
1226 1227 1228
                           &fields[..],
                           |s, field| {
                               s.ibox(indent_unit)?;
1229
                               if !field.is_shorthand {
1230
                                    s.print_ident(field.ident)?;
1231 1232
                                    s.word_space(":")?;
                               }
J
Jorge Aparicio 已提交
1233 1234 1235 1236
                               s.print_expr(&field.expr)?;
                               s.end()
                           },
                           |f| f.span)?;
1237 1238
        match *wth {
            Some(ref expr) => {
J
Jorge Aparicio 已提交
1239
                self.ibox(indent_unit)?;
1240
                if !fields.is_empty() {
1241 1242
                    self.s.word(",")?;
                    self.s.space()?;
1243
                }
1244
                self.s.word("..")?;
J
Jorge Aparicio 已提交
1245 1246
                self.print_expr(&expr)?;
                self.end()?;
1247 1248
            }
            _ => if !fields.is_empty() {
1249
                self.s.word(",")?
N
Nick Cameron 已提交
1250
            },
1251
        }
1252
        self.s.word("}")?;
1253 1254 1255
        Ok(())
    }

1256
    fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
J
Jorge Aparicio 已提交
1257
        self.popen()?;
1258
        self.commasep_exprs(Inconsistent, exprs)?;
1259
        if exprs.len() == 1 {
1260
            self.s.word(",")?;
1261 1262 1263 1264
        }
        self.pclose()
    }

1265
    fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1266 1267
        let prec =
            match func.node {
C
csmoe 已提交
1268
                hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1269 1270 1271 1272
                _ => parser::PREC_POSTFIX,
            };

        self.print_expr_maybe_paren(func, prec)?;
1273 1274 1275 1276
        self.print_call_post(args)
    }

    fn print_expr_method_call(&mut self,
1277
                              segment: &hir::PathSegment,
1278
                              args: &[hir::Expr])
N
Nick Cameron 已提交
1279
                              -> io::Result<()> {
1280
        let base_args = &args[1..];
1281
        self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1282
        self.s.word(".")?;
1283
        self.print_ident(segment.ident)?;
1284

1285
        segment.with_generic_args(|generic_args| {
1286 1287
            if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
                return self.print_generic_args(&generic_args, segment.infer_types, true);
1288
            }
1289
            Ok(())
1290
        })?;
1291 1292 1293 1294 1295 1296
        self.print_call_post(base_args)
    }

    fn print_expr_binary(&mut self,
                         op: hir::BinOp,
                         lhs: &hir::Expr,
N
Nick Cameron 已提交
1297 1298
                         rhs: &hir::Expr)
                         -> io::Result<()> {
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        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),
        };

1309 1310 1311 1312
        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 已提交
1313 1314
            (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
            (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1315 1316 1317
            _ => left_prec,
        };

1318
        self.print_expr_maybe_paren(lhs, left_prec)?;
1319
        self.s.space()?;
1320
        self.word_space(op.node.as_str())?;
1321
        self.print_expr_maybe_paren(rhs, right_prec)
1322 1323
    }

N
Nick Cameron 已提交
1324
    fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1325
        self.s.word(op.as_str())?;
1326
        self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1327 1328 1329 1330
    }

    fn print_expr_addr_of(&mut self,
                          mutability: hir::Mutability,
N
Nick Cameron 已提交
1331 1332
                          expr: &hir::Expr)
                          -> io::Result<()> {
1333
        self.s.word("&")?;
J
Jorge Aparicio 已提交
1334
        self.print_mutability(mutability)?;
1335
        self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1336 1337 1338
    }

    pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1339
        self.maybe_print_comment(expr.span.lo())?;
1340
        self.print_outer_attributes(&expr.attrs)?;
J
Jorge Aparicio 已提交
1341
        self.ibox(indent_unit)?;
V
varkor 已提交
1342
        self.ann.pre(self, AnnNode::Expr(expr))?;
1343
        match expr.node {
C
csmoe 已提交
1344
            hir::ExprKind::Box(ref expr) => {
J
Jorge Aparicio 已提交
1345
                self.word_space("box")?;
1346
                self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1347
            }
C
csmoe 已提交
1348
            hir::ExprKind::Array(ref exprs) => {
1349
                self.print_expr_vec(exprs)?;
1350
            }
C
csmoe 已提交
1351
            hir::ExprKind::Repeat(ref element, ref count) => {
1352
                self.print_expr_repeat(&element, count)?;
1353
            }
C
csmoe 已提交
1354
            hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1355
                self.print_expr_struct(qpath, &fields[..], wth)?;
1356
            }
C
csmoe 已提交
1357
            hir::ExprKind::Tup(ref exprs) => {
1358
                self.print_expr_tup(exprs)?;
1359
            }
C
csmoe 已提交
1360
            hir::ExprKind::Call(ref func, ref args) => {
1361
                self.print_expr_call(&func, args)?;
1362
            }
C
csmoe 已提交
1363
            hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1364
                self.print_expr_method_call(segment, args)?;
1365
            }
C
csmoe 已提交
1366
            hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
J
Jorge Aparicio 已提交
1367
                self.print_expr_binary(op, &lhs, &rhs)?;
1368
            }
C
csmoe 已提交
1369
            hir::ExprKind::Unary(op, ref expr) => {
J
Jorge Aparicio 已提交
1370
                self.print_expr_unary(op, &expr)?;
1371
            }
C
csmoe 已提交
1372
            hir::ExprKind::AddrOf(m, ref expr) => {
J
Jorge Aparicio 已提交
1373
                self.print_expr_addr_of(m, &expr)?;
1374
            }
C
csmoe 已提交
1375
            hir::ExprKind::Lit(ref lit) => {
J
Jorge Aparicio 已提交
1376
                self.print_literal(&lit)?;
1377
            }
C
csmoe 已提交
1378
            hir::ExprKind::Cast(ref expr, ref ty) => {
1379 1380
                let prec = AssocOp::As.precedence() as i8;
                self.print_expr_maybe_paren(&expr, prec)?;
1381
                self.s.space()?;
J
Jorge Aparicio 已提交
1382 1383
                self.word_space("as")?;
                self.print_type(&ty)?;
1384
            }
C
csmoe 已提交
1385
            hir::ExprKind::Type(ref expr, ref ty) => {
1386 1387
                let prec = AssocOp::Colon.precedence() as i8;
                self.print_expr_maybe_paren(&expr, prec)?;
J
Jorge Aparicio 已提交
1388 1389
                self.word_space(":")?;
                self.print_type(&ty)?;
1390
            }
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
            hir::ExprKind::Use(ref init) => {
                // Print `{`:
                self.cbox(indent_unit)?;
                self.ibox(0)?;
                self.bopen()?;

                // Print `let _t = $init;`:
                let temp = ast::Ident::from_str("_t");
                self.print_local(Some(init), |this| this.print_ident(temp))?;
                self.s.word(";")?;

                // Print `_t`:
                self.space_if_not_bol()?;
                self.print_ident(temp)?;

                // Print `}`:
                self.bclose_maybe_open(expr.span, indent_unit, true)?;
            }
C
csmoe 已提交
1409
            hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
J
Jorge Aparicio 已提交
1410
                self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1411
            }
C
csmoe 已提交
1412
            hir::ExprKind::While(ref test, ref blk, opt_label) => {
1413
                if let Some(label) = opt_label {
1414
                    self.print_ident(label.ident)?;
J
Jorge Aparicio 已提交
1415
                    self.word_space(":")?;
1416
                }
J
Jorge Aparicio 已提交
1417
                self.head("while")?;
1418
                self.print_expr_as_cond(&test)?;
1419
                self.s.space()?;
J
Jorge Aparicio 已提交
1420
                self.print_block(&blk)?;
1421
            }
C
csmoe 已提交
1422
            hir::ExprKind::Loop(ref blk, opt_label, _) => {
1423
                if let Some(label) = opt_label {
1424
                    self.print_ident(label.ident)?;
J
Jorge Aparicio 已提交
1425
                    self.word_space(":")?;
1426
                }
J
Jorge Aparicio 已提交
1427
                self.head("loop")?;
1428
                self.s.space()?;
J
Jorge Aparicio 已提交
1429
                self.print_block(&blk)?;
1430
            }
C
csmoe 已提交
1431
            hir::ExprKind::Match(ref expr, ref arms, _) => {
J
Jorge Aparicio 已提交
1432 1433 1434
                self.cbox(indent_unit)?;
                self.ibox(4)?;
                self.word_nbsp("match")?;
1435
                self.print_expr_as_cond(&expr)?;
1436
                self.s.space()?;
J
Jorge Aparicio 已提交
1437
                self.bopen()?;
1438
                for arm in arms {
J
Jorge Aparicio 已提交
1439
                    self.print_arm(arm)?;
1440
                }
J
Jorge Aparicio 已提交
1441
                self.bclose_(expr.span, indent_unit)?;
1442
            }
C
csmoe 已提交
1443
            hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
J
Jorge Aparicio 已提交
1444
                self.print_capture_clause(capture_clause)?;
1445

1446
                self.print_closure_args(&decl, body)?;
1447
                self.s.space()?;
1448

1449
                // this is a bare expression
1450
                self.ann.nested(self, Nested::Body(body))?;
1451
                self.end()?; // need to close a box
1452 1453 1454 1455

                // 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 已提交
1456
                self.ibox(0)?;
1457
            }
C
csmoe 已提交
1458
            hir::ExprKind::Block(ref blk, opt_label) => {
1459
                if let Some(label) = opt_label {
1460
                    self.print_ident(label.ident)?;
1461 1462
                    self.word_space(":")?;
                }
1463
                // containing cbox, will be closed by print-block at }
J
Jorge Aparicio 已提交
1464
                self.cbox(indent_unit)?;
1465
                // head-box, will be closed by print-block after {
J
Jorge Aparicio 已提交
1466 1467
                self.ibox(0)?;
                self.print_block(&blk)?;
1468
            }
C
csmoe 已提交
1469
            hir::ExprKind::Assign(ref lhs, ref rhs) => {
1470 1471
                let prec = AssocOp::Assign.precedence() as i8;
                self.print_expr_maybe_paren(&lhs, prec + 1)?;
1472
                self.s.space()?;
J
Jorge Aparicio 已提交
1473
                self.word_space("=")?;
1474
                self.print_expr_maybe_paren(&rhs, prec)?;
1475
            }
C
csmoe 已提交
1476
            hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1477 1478
                let prec = AssocOp::Assign.precedence() as i8;
                self.print_expr_maybe_paren(&lhs, prec + 1)?;
1479 1480
                self.s.space()?;
                self.s.word(op.node.as_str())?;
J
Jorge Aparicio 已提交
1481
                self.word_space("=")?;
1482
                self.print_expr_maybe_paren(&rhs, prec)?;
1483
            }
C
csmoe 已提交
1484
            hir::ExprKind::Field(ref expr, ident) => {
1485
                self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1486
                self.s.word(".")?;
1487
                self.print_ident(ident)?;
1488
            }
C
csmoe 已提交
1489
            hir::ExprKind::Index(ref expr, ref index) => {
1490
                self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1491
                self.s.word("[")?;
J
Jorge Aparicio 已提交
1492
                self.print_expr(&index)?;
1493
                self.s.word("]")?;
1494
            }
C
csmoe 已提交
1495
            hir::ExprKind::Path(ref qpath) => {
1496
                self.print_qpath(qpath, true)?
1497
            }
C
csmoe 已提交
1498
            hir::ExprKind::Break(destination, ref opt_expr) => {
1499 1500
                self.s.word("break")?;
                self.s.space()?;
1501
                if let Some(label) = destination.label {
1502
                    self.print_ident(label.ident)?;
1503
                    self.s.space()?;
1504
                }
1505
                if let Some(ref expr) = *opt_expr {
1506
                    self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1507
                    self.s.space()?;
1508
                }
1509
            }
C
csmoe 已提交
1510
            hir::ExprKind::Continue(destination) => {
1511 1512
                self.s.word("continue")?;
                self.s.space()?;
1513
                if let Some(label) = destination.label {
1514
                    self.print_ident(label.ident)?;
1515
                    self.s.space()?
1516 1517
                }
            }
C
csmoe 已提交
1518
            hir::ExprKind::Ret(ref result) => {
1519
                self.s.word("return")?;
L
ljedrz 已提交
1520 1521 1522
                if let Some(ref expr) = *result {
                    self.s.word(" ")?;
                    self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1523 1524
                }
            }
C
csmoe 已提交
1525
            hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1526
                self.s.word("asm!")?;
J
Jorge Aparicio 已提交
1527
                self.popen()?;
1528
                self.print_string(&a.asm.as_str(), a.asm_str_style)?;
J
Jorge Aparicio 已提交
1529
                self.word_space(":")?;
1530

1531
                let mut out_idx = 0;
J
Jorge Aparicio 已提交
1532
                self.commasep(Inconsistent, &a.outputs, |s, out| {
1533 1534
                    let constraint = out.constraint.as_str();
                    let mut ch = constraint.chars();
1535 1536 1537 1538
                    match ch.next() {
                        Some('=') if out.is_rw => {
                            s.print_string(&format!("+{}", ch.as_str()),
                                           ast::StrStyle::Cooked)?
J
Jose Narvaez 已提交
1539
                        }
1540
                        _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
J
Jose Narvaez 已提交
1541
                    }
J
Jorge Aparicio 已提交
1542 1543 1544
                    s.popen()?;
                    s.print_expr(&outputs[out_idx])?;
                    s.pclose()?;
1545
                    out_idx += 1;
J
Jose Narvaez 已提交
1546
                    Ok(())
J
Jorge Aparicio 已提交
1547
                })?;
1548
                self.s.space()?;
J
Jorge Aparicio 已提交
1549
                self.word_space(":")?;
1550

1551
                let mut in_idx = 0;
J
Jorge Aparicio 已提交
1552
                self.commasep(Inconsistent, &a.inputs, |s, co| {
1553
                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
J
Jorge Aparicio 已提交
1554 1555 1556
                    s.popen()?;
                    s.print_expr(&inputs[in_idx])?;
                    s.pclose()?;
1557
                    in_idx += 1;
J
Jose Narvaez 已提交
1558
                    Ok(())
J
Jorge Aparicio 已提交
1559
                })?;
1560
                self.s.space()?;
J
Jorge Aparicio 已提交
1561
                self.word_space(":")?;
1562

J
Jorge Aparicio 已提交
1563
                self.commasep(Inconsistent, &a.clobbers, |s, co| {
1564
                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
J
Jose Narvaez 已提交
1565
                    Ok(())
J
Jorge Aparicio 已提交
1566
                })?;
1567

J
Jose Narvaez 已提交
1568
                let mut options = vec![];
1569 1570 1571 1572 1573 1574
                if a.volatile {
                    options.push("volatile");
                }
                if a.alignstack {
                    options.push("alignstack");
                }
1575
                if a.dialect == ast::AsmDialect::Intel {
1576 1577 1578 1579
                    options.push("intel");
                }

                if !options.is_empty() {
1580
                    self.s.space()?;
J
Jorge Aparicio 已提交
1581 1582 1583
                    self.word_space(":")?;
                    self.commasep(Inconsistent, &options, |s, &co| {
                        s.print_string(co, ast::StrStyle::Cooked)?;
J
Jose Narvaez 已提交
1584
                        Ok(())
J
Jorge Aparicio 已提交
1585
                    })?;
1586 1587
                }

J
Jorge Aparicio 已提交
1588
                self.pclose()?;
1589
            }
C
csmoe 已提交
1590
            hir::ExprKind::Yield(ref expr) => {
J
John Kåre Alsaker 已提交
1591
                self.word_space("yield")?;
1592
                self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
J
John Kåre Alsaker 已提交
1593
            }
1594 1595 1596 1597 1598
            hir::ExprKind::Err => {
                self.popen()?;
                self.s.word("/*ERROR*/")?;
                self.pclose()?;
            }
1599
        }
V
varkor 已提交
1600
        self.ann.post(self, AnnNode::Expr(expr))?;
1601 1602 1603 1604
        self.end()
    }

    pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
J
Jorge Aparicio 已提交
1605
        self.print_pat(&loc.pat)?;
1606
        if let Some(ref ty) = loc.ty {
J
Jorge Aparicio 已提交
1607 1608
            self.word_space(":")?;
            self.print_type(&ty)?;
1609 1610 1611 1612 1613
        }
        Ok(())
    }

    pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1614
        self.s.word(i.to_string())
1615 1616
    }

1617 1618
    pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
        if ident.is_raw_guess() {
1619
            self.s.word(format!("r#{}", ident.name))?;
1620
        } else {
1621
            self.s.word(ident.as_str().to_string())?;
1622
        }
V
varkor 已提交
1623
        self.ann.post(self, AnnNode::Name(&ident.name))
1624 1625 1626
    }

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

N
Nick Cameron 已提交
1630
    pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
J
Jorge Aparicio 已提交
1631
        self.print_local_decl(loc)?;
1632
        self.s.space()?;
J
Jorge Aparicio 已提交
1633
        self.word_space("in")?;
1634 1635 1636
        self.print_expr(coll)
    }

1637 1638 1639 1640
    pub fn print_path(&mut self,
                      path: &hir::Path,
                      colons_before_params: bool)
                      -> io::Result<()> {
1641
        self.maybe_print_comment(path.span.lo())?;
1642

1643 1644
        for (i, segment) in path.segments.iter().enumerate() {
            if i > 0 {
1645
                self.s.word("::")?
1646
            }
1647
            if segment.ident.name != keywords::PathRoot.name() {
1648
               self.print_ident(segment.ident)?;
1649
               segment.with_generic_args(|generic_args| {
1650
                   self.print_generic_args(generic_args, segment.infer_types,
1651
                                           colons_before_params)
1652
               })?;
1653
            }
1654 1655 1656 1657 1658
        }

        Ok(())
    }

1659
    pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
1660
        if segment.ident.name != keywords::PathRoot.name() {
1661 1662 1663 1664 1665 1666 1667 1668
           self.print_ident(segment.ident)?;
           segment.with_generic_args(|generic_args| {
               self.print_generic_args(generic_args, segment.infer_types, false)
           })?;
        }
        Ok(())
    }

1669 1670 1671 1672
    pub fn print_qpath(&mut self,
                       qpath: &hir::QPath,
                       colons_before_params: bool)
                       -> io::Result<()> {
1673 1674 1675 1676 1677
        match *qpath {
            hir::QPath::Resolved(None, ref path) => {
                self.print_path(path, colons_before_params)
            }
            hir::QPath::Resolved(Some(ref qself), ref path) => {
1678
                self.s.word("<")?;
1679
                self.print_type(qself)?;
1680
                self.s.space()?;
1681 1682
                self.word_space("as")?;

1683 1684
                for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
                    if i > 0 {
1685
                        self.s.word("::")?
1686
                    }
1687
                    if segment.ident.name != keywords::PathRoot.name() {
1688
                        self.print_ident(segment.ident)?;
1689 1690 1691 1692
                        segment.with_generic_args(|generic_args| {
                            self.print_generic_args(generic_args,
                                                    segment.infer_types,
                                                    colons_before_params)
1693
                        })?;
1694
                    }
1695 1696
                }

1697 1698
                self.s.word(">")?;
                self.s.word("::")?;
1699
                let item_segment = path.segments.last().unwrap();
1700
                self.print_ident(item_segment.ident)?;
1701 1702 1703 1704
                item_segment.with_generic_args(|generic_args| {
                    self.print_generic_args(generic_args,
                                            item_segment.infer_types,
                                            colons_before_params)
1705
                })
1706 1707
            }
            hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1708
                self.s.word("<")?;
1709
                self.print_type(qself)?;
1710 1711
                self.s.word(">")?;
                self.s.word("::")?;
1712
                self.print_ident(item_segment.ident)?;
1713 1714 1715 1716
                item_segment.with_generic_args(|generic_args| {
                    self.print_generic_args(generic_args,
                                            item_segment.infer_types,
                                            colons_before_params)
1717
                })
1718
            }
1719 1720 1721
        }
    }

1722 1723
    fn print_generic_args(&mut self,
                             generic_args: &hir::GenericArgs,
1724
                             infer_types: bool,
1725
                             colons_before_params: bool)
N
Nick Cameron 已提交
1726
                             -> io::Result<()> {
1727
        if generic_args.parenthesized {
1728
            self.s.word("(")?;
1729
            self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1730
            self.s.word(")")?;
1731

1732 1733
            self.space_if_not_bol()?;
            self.word_space("->")?;
1734
            self.print_type(&generic_args.bindings[0].ty)?;
1735 1736 1737 1738 1739 1740 1741 1742 1743
        } 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(",")
1744
                }
1745
            };
1746

V
varkor 已提交
1747 1748 1749 1750 1751 1752
            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
1753
                }
V
varkor 已提交
1754 1755 1756
            });

            if nonelided_generic_args {
1757
                start_or_comma(self)?;
1758 1759
                self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
                    match generic_arg {
V
varkor 已提交
1760 1761
                        GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
                        GenericArg::Lifetime(_) => Ok(()),
1762
                        GenericArg::Type(ty) => s.print_type(ty),
V
varkor 已提交
1763
                        GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1764
                    }
1765
                })?;
V
varkor 已提交
1766 1767
            }

1768 1769
            // FIXME(eddyb) This would leak into error messages, e.g.:
            // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1770
            if infer_types && false {
1771 1772
                start_or_comma(self)?;
                self.s.word("..")?;
1773 1774
            }

1775
            for binding in generic_args.bindings.iter() {
1776
                start_or_comma(self)?;
1777
                self.print_ident(binding.ident)?;
1778 1779 1780 1781
                self.s.space()?;
                self.word_space("=")?;
                self.print_type(&binding.ty)?;
            }
1782

1783 1784
            if !empty.get() {
                self.s.word(">")?
1785 1786 1787 1788 1789 1790 1791
            }
        }

        Ok(())
    }

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

    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() {
1954
            self.s.space()?;
1955
        }
J
Jorge Aparicio 已提交
1956 1957 1958
        self.cbox(indent_unit)?;
        self.ibox(0)?;
        self.print_outer_attributes(&arm.attrs)?;
1959 1960 1961 1962 1963
        let mut first = true;
        for p in &arm.pats {
            if first {
                first = false;
            } else {
1964
                self.s.space()?;
J
Jorge Aparicio 已提交
1965
                self.word_space("|")?;
1966
            }
J
Jorge Aparicio 已提交
1967
            self.print_pat(&p)?;
1968
        }
1969
        self.s.space()?;
F
F001 已提交
1970 1971 1972 1973 1974 1975 1976 1977
        if let Some(ref g) = arm.guard {
            match g {
                hir::Guard::If(e) => {
                    self.word_space("if")?;
                    self.print_expr(&e)?;
                    self.s.space()?;
                }
            }
1978
        }
J
Jorge Aparicio 已提交
1979
        self.word_space("=>")?;
1980 1981

        match arm.body.node {
C
csmoe 已提交
1982
            hir::ExprKind::Block(ref blk, opt_label) => {
1983
                if let Some(label) = opt_label {
1984
                    self.print_ident(label.ident)?;
1985 1986
                    self.word_space(":")?;
                }
1987
                // the block will close the pattern's ibox
J
Jorge Aparicio 已提交
1988
                self.print_block_unclosed_indent(&blk, indent_unit)?;
1989 1990 1991

                // If it is a user-provided unsafe block, print a comma after it
                if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1992
                    self.s.word(",")?;
1993 1994 1995
                }
            }
            _ => {
J
Jorge Aparicio 已提交
1996 1997
                self.end()?; // close the ibox for the pattern
                self.print_expr(&arm.body)?;
1998
                self.s.word(",")?;
1999 2000 2001 2002 2003 2004 2005
            }
        }
        self.end() // close enclosing cbox
    }

    pub fn print_fn(&mut self,
                    decl: &hir::FnDecl,
W
Without Boats 已提交
2006
                    header: hir::FnHeader,
V
Vadim Petrochenkov 已提交
2007
                    name: Option<ast::Name>,
2008
                    generics: &hir::Generics,
2009
                    vis: &hir::Visibility,
2010
                    arg_names: &[ast::Ident],
2011
                    body_id: Option<hir::BodyId>)
N
Nick Cameron 已提交
2012
                    -> io::Result<()> {
W
Without Boats 已提交
2013
        self.print_fn_header_info(header, vis)?;
2014 2015

        if let Some(name) = name {
J
Jorge Aparicio 已提交
2016 2017
            self.nbsp()?;
            self.print_name(name)?;
2018
        }
2019
        self.print_generic_params(&generics.params)?;
2020

J
Jorge Aparicio 已提交
2021
        self.popen()?;
2022 2023 2024 2025 2026
        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)?;
2027
            if let Some(arg_name) = arg_names.get(i) {
2028
                s.s.word(arg_name.as_str().to_string())?;
2029 2030
                s.s.word(":")?;
                s.s.space()?;
2031 2032
            } else if let Some(body_id) = body_id {
                s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2033 2034
                s.s.word(":")?;
                s.s.space()?;
2035 2036 2037 2038 2039
            }
            i += 1;
            s.print_type(ty)?;
            s.end()
        })?;
D
Dan Robertson 已提交
2040
        if decl.c_variadic {
2041
            self.s.word(", ...")?;
2042
        }
J
Jorge Aparicio 已提交
2043
        self.pclose()?;
2044

2045 2046
        self.print_fn_output(decl)?;
        self.print_where_clause(&generics.where_clause)
2047 2048
    }

2049
    fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2050
        self.s.word("|")?;
2051 2052 2053 2054
        let mut i = 0;
        self.commasep(Inconsistent, &decl.inputs, |s, ty| {
            s.ibox(indent_unit)?;

2055
            s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2056 2057
            i += 1;

C
TyKind  
csmoe 已提交
2058
            if let hir::TyKind::Infer = ty.node {
2059 2060
                // Print nothing
            } else {
2061 2062
                s.s.word(":")?;
                s.s.space()?;
2063 2064 2065 2066
                s.print_type(ty)?;
            }
            s.end()
        })?;
2067
        self.s.word("|")?;
2068 2069 2070 2071 2072

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

J
Jorge Aparicio 已提交
2073 2074
        self.space_if_not_bol()?;
        self.word_space("->")?;
2075 2076
        match decl.output {
            hir::Return(ref ty) => {
J
Jorge Aparicio 已提交
2077
                self.print_type(&ty)?;
2078
                self.maybe_print_comment(ty.span.lo())
2079 2080 2081 2082 2083
            }
            hir::DefaultReturn(..) => unreachable!(),
        }
    }

N
Nick Cameron 已提交
2084
    pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2085 2086 2087 2088 2089 2090
        match capture_clause {
            hir::CaptureByValue => self.word_space("move"),
            hir::CaptureByRef => Ok(()),
        }
    }

2091 2092
    pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
                        -> io::Result<()> {
2093
        if !bounds.is_empty() {
2094
            self.s.word(prefix)?;
2095 2096
            let mut first = true;
            for bound in bounds {
2097 2098 2099
                if !(first && prefix.is_empty()) {
                    self.nbsp()?;
                }
2100 2101 2102
                if first {
                    first = false;
                } else {
J
Jorge Aparicio 已提交
2103
                    self.word_space("+")?;
2104 2105
                }

2106
                match bound {
V
varkor 已提交
2107
                    GenericBound::Trait(tref, modifier) => {
2108 2109 2110 2111
                        if modifier == &TraitBoundModifier::Maybe {
                            self.s.word("?")?;
                        }
                        self.print_poly_trait_ref(tref)?;
2112
                    }
V
varkor 已提交
2113
                    GenericBound::Outlives(lt) => {
2114
                        self.print_lifetime(lt)?;
2115
                    }
2116
                }
2117 2118
            }
        }
2119
        Ok(())
2120 2121
    }

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

2126
            self.commasep(Inconsistent, generic_params, |s, param| {
V
varkor 已提交
2127
                s.print_generic_param(param)
2128
            })?;
2129

2130
            self.s.word(">")?;
2131 2132 2133 2134
        }
        Ok(())
    }

V
varkor 已提交
2135
    pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
V
varkor 已提交
2136 2137 2138 2139
        if let GenericParamKind::Const { .. } = param.kind {
            self.word_space("const")?;
        }

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

V
varkor 已提交
2142
        match param.kind {
V
varkor 已提交
2143
            GenericParamKind::Lifetime { .. } => {
V
varkor 已提交
2144
                let mut sep = ":";
V
varkor 已提交
2145 2146
                for bound in &param.bounds {
                    match bound {
V
varkor 已提交
2147
                        GenericBound::Outlives(lt) => {
V
varkor 已提交
2148 2149 2150 2151 2152 2153
                            self.s.word(sep)?;
                            self.print_lifetime(lt)?;
                            sep = "+";
                        }
                        _ => bug!(),
                    }
V
varkor 已提交
2154 2155 2156
                }
                Ok(())
            }
V
varkor 已提交
2157 2158
            GenericParamKind::Type { ref default, .. } => {
                self.print_bounds(":", &param.bounds)?;
V
varkor 已提交
2159 2160 2161 2162 2163 2164 2165 2166
                match default {
                    Some(default) => {
                        self.s.space()?;
                        self.word_space("=")?;
                        self.print_type(&default)
                    }
                    _ => Ok(()),
                }
2167
            }
V
varkor 已提交
2168 2169 2170 2171
            GenericParamKind::Const { ref ty } => {
                self.word_space(":")?;
                self.print_type(ty)
            }
2172 2173 2174
        }
    }

V
varkor 已提交
2175
    pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
V
Vadim Petrochenkov 已提交
2176
        self.print_ident(lifetime.name.ident())
V
varkor 已提交
2177 2178
    }

N
Nick Cameron 已提交
2179
    pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2180
        if where_clause.predicates.is_empty() {
J
Jose Narvaez 已提交
2181
            return Ok(());
2182 2183
        }

2184
        self.s.space()?;
J
Jorge Aparicio 已提交
2185
        self.word_space("where")?;
2186 2187 2188

        for (i, predicate) in where_clause.predicates.iter().enumerate() {
            if i != 0 {
J
Jorge Aparicio 已提交
2189
                self.word_space(",")?;
2190 2191 2192
            }

            match predicate {
2193 2194 2195 2196 2197 2198 2199
                &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 已提交
2200 2201
                    self.print_type(&bounded_ty)?;
                    self.print_bounds(":", bounds)?;
2202 2203 2204 2205
                }
                &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
                                                                                ref bounds,
                                                                                ..}) => {
J
Jorge Aparicio 已提交
2206
                    self.print_lifetime(lifetime)?;
2207
                    self.s.word(":")?;
2208 2209

                    for (i, bound) in bounds.iter().enumerate() {
V
varkor 已提交
2210
                        match bound {
V
varkor 已提交
2211
                            GenericBound::Outlives(lt) => {
V
varkor 已提交
2212 2213 2214 2215
                                self.print_lifetime(lt)?;
                            }
                            _ => bug!(),
                        }
2216 2217

                        if i != 0 {
2218
                            self.s.word(":")?;
2219 2220 2221
                        }
                    }
                }
2222 2223 2224 2225
                &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
                                                                        ref rhs_ty,
                                                                        ..}) => {
                    self.print_type(lhs_ty)?;
2226
                    self.s.space()?;
J
Jorge Aparicio 已提交
2227
                    self.word_space("=")?;
2228
                    self.print_type(rhs_ty)?;
2229 2230 2231 2232 2233 2234 2235
                }
            }
        }

        Ok(())
    }

N
Nick Cameron 已提交
2236
    pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2237 2238 2239 2240 2241 2242 2243
        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 已提交
2244
        self.print_mutability(mt.mutbl)?;
2245
        self.print_type(&mt.ty)
2246 2247 2248 2249 2250 2251 2252
    }

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

J
Jorge Aparicio 已提交
2253 2254 2255
        self.space_if_not_bol()?;
        self.ibox(indent_unit)?;
        self.word_space("->")?;
2256 2257
        match decl.output {
            hir::DefaultReturn(..) => unreachable!(),
J
Jorge Aparicio 已提交
2258
            hir::Return(ref ty) => self.print_type(&ty)?,
2259
        }
J
Jorge Aparicio 已提交
2260
        self.end()?;
2261 2262

        match decl.output {
2263
            hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
N
Nick Cameron 已提交
2264
            _ => Ok(()),
2265 2266 2267 2268
        }
    }

    pub fn print_ty_fn(&mut self,
2269
                       abi: Abi,
2270 2271
                       unsafety: hir::Unsafety,
                       decl: &hir::FnDecl,
2272
                       name: Option<ast::Name>,
2273
                       generic_params: &[hir::GenericParam],
2274
                       arg_names: &[ast::Ident])
2275
                       -> io::Result<()> {
J
Jorge Aparicio 已提交
2276
        self.ibox(indent_unit)?;
2277
        if !generic_params.is_empty() {
2278
            self.s.word("for")?;
2279
            self.print_generic_params(generic_params)?;
2280 2281
        }
        let generics = hir::Generics {
2282
            params: hir::HirVec::new(),
2283
            where_clause: hir::WhereClause {
L
ljedrz 已提交
2284
                hir_id: hir::DUMMY_HIR_ID,
2285
                predicates: hir::HirVec::new(),
2286
            },
2287
            span: syntax_pos::DUMMY_SP,
2288
        };
J
Jorge Aparicio 已提交
2289
        self.print_fn(decl,
W
Without Boats 已提交
2290
                      hir::FnHeader {
2291 2292 2293 2294
                          unsafety,
                          abi,
                          constness: hir::Constness::NotConst,
                          asyncness: hir::IsAsync::NotAsync,
W
Without Boats 已提交
2295
                      },
J
Jorge Aparicio 已提交
2296 2297
                      name,
                      &generics,
2298 2299
                      &Spanned { span: syntax_pos::DUMMY_SP,
                                 node: hir::VisibilityKind::Inherited },
2300
                      arg_names,
2301
                      None)?;
2302 2303 2304
        self.end()
    }

N
Nick Cameron 已提交
2305
    pub fn maybe_print_trailing_comment(&mut self,
2306
                                        span: syntax_pos::Span,
2307
                                        next_pos: Option<BytePos>)
N
Nick Cameron 已提交
2308
                                        -> io::Result<()> {
2309 2310
        let cm = match self.cm {
            Some(cm) => cm,
N
Nick Cameron 已提交
2311
            _ => return Ok(()),
2312
        };
2313 2314 2315 2316
        if let Some(ref cmnt) = self.next_comment() {
            if (*cmnt).style != comments::Trailing {
                return Ok(());
            }
2317
            let span_line = cm.lookup_char_pos(span.hi());
2318 2319 2320 2321 2322
            let comment_line = cm.lookup_char_pos((*cmnt).pos);
            let mut next = (*cmnt).pos + BytePos(1);
            if let Some(p) = next_pos {
                next = p;
            }
2323
            if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2324 2325
               span_line.line == comment_line.line {
                self.print_comment(cmnt)?;
2326 2327 2328 2329 2330 2331 2332 2333 2334
            }
        }
        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() {
2335
            self.s.hardbreak()?;
2336
        }
L
leonardo.yvens 已提交
2337 2338
        while let Some(ref cmnt) = self.next_comment() {
            self.print_comment(cmnt)?
2339 2340 2341 2342 2343
        }
        Ok(())
    }

    pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2344
                                                  opt_abi: Option<Abi>)
N
Nick Cameron 已提交
2345
                                                  -> io::Result<()> {
2346
        match opt_abi {
2347
            Some(Abi::Rust) => Ok(()),
2348
            Some(abi) => {
J
Jorge Aparicio 已提交
2349
                self.word_nbsp("extern")?;
2350
                self.word_nbsp(abi.to_string())
2351
            }
N
Nick Cameron 已提交
2352
            None => Ok(()),
2353 2354 2355
        }
    }

2356
    pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2357 2358
        match opt_abi {
            Some(abi) => {
J
Jorge Aparicio 已提交
2359
                self.word_nbsp("extern")?;
2360
                self.word_nbsp(abi.to_string())
2361
            }
N
Nick Cameron 已提交
2362
            None => Ok(()),
2363 2364 2365 2366
        }
    }

    pub fn print_fn_header_info(&mut self,
W
Without Boats 已提交
2367
                                header: hir::FnHeader,
2368
                                vis: &hir::Visibility)
N
Nick Cameron 已提交
2369
                                -> io::Result<()> {
2370
        self.s.word(visibility_qualified(vis, ""))?;
2371

W
Without Boats 已提交
2372
        match header.constness {
2373
            hir::Constness::NotConst => {}
J
Jorge Aparicio 已提交
2374
            hir::Constness::Const => self.word_nbsp("const")?,
2375 2376
        }

W
Without Boats 已提交
2377 2378 2379 2380 2381 2382 2383 2384
        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 已提交
2385
            self.word_nbsp("extern")?;
2386
            self.word_nbsp(header.abi.to_string())?;
2387 2388
        }

2389
        self.s.word("fn")
2390 2391 2392 2393 2394 2395 2396 2397
    }

    pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
        match s {
            hir::Unsafety::Normal => Ok(()),
            hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
        }
    }
2398 2399 2400 2401 2402 2403 2404

    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(()),
        }
    }
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
}

// 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 已提交
2417 2418 2419 2420 2421
        hir::ExprKind::If(..) |
        hir::ExprKind::Match(..) |
        hir::ExprKind::Block(..) |
        hir::ExprKind::While(..) |
        hir::ExprKind::Loop(..) => false,
N
Nick Cameron 已提交
2422
        _ => true,
2423 2424 2425 2426 2427 2428
    }
}

/// 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 已提交
2429
fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2430
    match *stmt {
2431 2432 2433 2434
        hir::StmtKind::Local(_) => true,
        hir::StmtKind::Item(_) => false,
        hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
        hir::StmtKind::Semi(..) => false,
2435 2436
    }
}
2437

C
csmoe 已提交
2438
fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
M
Mark Mansi 已提交
2439
    use crate::hir::BinOpKind::*;
2440
    match op {
C
csmoe 已提交
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
        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,
2462 2463 2464
    }
}

2465 2466
/// 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
2467 2468 2469
/// `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 已提交
2470
        hir::ExprKind::Struct(..) => true,
2471

C
csmoe 已提交
2472 2473 2474
        hir::ExprKind::Assign(ref lhs, ref rhs) |
        hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
        hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2475 2476 2477
            // X { y: 1 } + X { y: 2 }
            contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
        }
C
csmoe 已提交
2478 2479 2480 2481 2482
        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, _) => {
2483 2484 2485 2486
            // &X { y: 1 }, X { y: 1 }.y
            contains_exterior_struct_lit(&x)
        }

C
csmoe 已提交
2487
        hir::ExprKind::MethodCall(.., ref exprs) => {
2488 2489 2490 2491 2492 2493 2494
            // X { y: 1 }.bar(...)
            contains_exterior_struct_lit(&exprs[0])
        }

        _ => false,
    }
}