]> git.proxmox.com Git - rustc.git/blob - src/librustc/hir/print.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / librustc / hir / print.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::AnnNode::*;
12
13 use syntax::abi::Abi;
14 use syntax::ast;
15 use syntax::codemap::{CodeMap, Spanned};
16 use syntax::parse::ParseSess;
17 use syntax::parse::lexer::comments;
18 use syntax::print::pp::{self, Breaks};
19 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
20 use syntax::print::pprust::PrintState;
21 use syntax::ptr::P;
22 use syntax::symbol::keywords;
23 use syntax::util::parser::{self, AssocOp, Fixity};
24 use syntax_pos::{self, BytePos};
25
26 use hir;
27 use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
28
29 use std::cell::Cell;
30 use std::io::{self, Write, Read};
31 use std::iter::Peekable;
32 use std::vec;
33
34 pub enum AnnNode<'a> {
35 NodeName(&'a ast::Name),
36 NodeBlock(&'a hir::Block),
37 NodeItem(&'a hir::Item),
38 NodeSubItem(ast::NodeId),
39 NodeExpr(&'a hir::Expr),
40 NodePat(&'a hir::Pat),
41 }
42
43 pub enum Nested {
44 Item(hir::ItemId),
45 TraitItem(hir::TraitItemId),
46 ImplItem(hir::ImplItemId),
47 Body(hir::BodyId),
48 BodyArgPat(hir::BodyId, usize)
49 }
50
51 pub trait PpAnn {
52 fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
53 Ok(())
54 }
55 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
56 Ok(())
57 }
58 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
59 Ok(())
60 }
61 }
62
63 pub struct NoAnn;
64 impl PpAnn for NoAnn {}
65 pub const NO_ANN: &'static PpAnn = &NoAnn;
66
67 impl PpAnn for hir::Crate {
68 fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
69 match nested {
70 Nested::Item(id) => state.print_item(self.item(id.id)),
71 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
72 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
73 Nested::Body(id) => state.print_expr(&self.body(id).value),
74 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
75 }
76 }
77 }
78
79 pub struct State<'a> {
80 pub s: pp::Printer<'a>,
81 cm: Option<&'a CodeMap>,
82 comments: Option<Vec<comments::Comment>>,
83 literals: Peekable<vec::IntoIter<comments::Literal>>,
84 cur_cmnt: usize,
85 boxes: Vec<pp::Breaks>,
86 ann: &'a (PpAnn + 'a),
87 }
88
89 impl<'a> PrintState<'a> for State<'a> {
90 fn writer(&mut self) -> &mut pp::Printer<'a> {
91 &mut self.s
92 }
93
94 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
95 &mut self.boxes
96 }
97
98 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
99 &mut self.comments
100 }
101
102 fn cur_cmnt(&mut self) -> &mut usize {
103 &mut self.cur_cmnt
104 }
105
106 fn cur_lit(&mut self) -> Option<&comments::Literal> {
107 self.literals.peek()
108 }
109
110 fn bump_lit(&mut self) -> Option<comments::Literal> {
111 self.literals.next()
112 }
113 }
114
115 #[allow(non_upper_case_globals)]
116 pub const indent_unit: usize = 4;
117
118 #[allow(non_upper_case_globals)]
119 pub const default_columns: usize = 78;
120
121
122 /// Requires you to pass an input filename and reader so that
123 /// it can scan the input text for comments and literals to
124 /// copy forward.
125 pub fn print_crate<'a>(cm: &'a CodeMap,
126 sess: &ParseSess,
127 krate: &hir::Crate,
128 filename: String,
129 input: &mut Read,
130 out: Box<Write + 'a>,
131 ann: &'a PpAnn,
132 is_expanded: bool)
133 -> io::Result<()> {
134 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
135
136 // When printing the AST, we sometimes need to inject `#[no_std]` here.
137 // Since you can't compile the HIR, it's not necessary.
138
139 s.print_mod(&krate.module, &krate.attrs)?;
140 s.print_remaining_comments()?;
141 s.s.eof()
142 }
143
144 impl<'a> State<'a> {
145 pub fn new_from_input(cm: &'a CodeMap,
146 sess: &ParseSess,
147 filename: String,
148 input: &mut Read,
149 out: Box<Write + 'a>,
150 ann: &'a PpAnn,
151 is_expanded: bool)
152 -> State<'a> {
153 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
154
155 State::new(cm,
156 out,
157 ann,
158 Some(cmnts),
159 // If the code is post expansion, don't use the table of
160 // literals, since it doesn't correspond with the literals
161 // in the AST anymore.
162 if is_expanded {
163 None
164 } else {
165 Some(lits)
166 })
167 }
168
169 pub fn new(cm: &'a CodeMap,
170 out: Box<Write + 'a>,
171 ann: &'a PpAnn,
172 comments: Option<Vec<comments::Comment>>,
173 literals: Option<Vec<comments::Literal>>)
174 -> State<'a> {
175 State {
176 s: pp::mk_printer(out, default_columns),
177 cm: Some(cm),
178 comments: comments.clone(),
179 literals: literals.unwrap_or_default().into_iter().peekable(),
180 cur_cmnt: 0,
181 boxes: Vec::new(),
182 ann,
183 }
184 }
185 }
186
187 pub fn to_string<F>(ann: &PpAnn, f: F) -> String
188 where F: FnOnce(&mut State) -> io::Result<()>
189 {
190 let mut wr = Vec::new();
191 {
192 let mut printer = State {
193 s: pp::mk_printer(Box::new(&mut wr), default_columns),
194 cm: None,
195 comments: None,
196 literals: vec![].into_iter().peekable(),
197 cur_cmnt: 0,
198 boxes: Vec::new(),
199 ann,
200 };
201 f(&mut printer).unwrap();
202 printer.s.eof().unwrap();
203 }
204 String::from_utf8(wr).unwrap()
205 }
206
207 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
208 to_string(NO_ANN, |s| {
209 s.print_visibility(vis)?;
210 s.s.word(w)
211 })
212 }
213
214 impl<'a> State<'a> {
215 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
216 self.boxes.push(pp::Breaks::Consistent);
217 self.s.cbox(u)
218 }
219
220 pub fn nbsp(&mut self) -> io::Result<()> {
221 self.s.word(" ")
222 }
223
224 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
225 self.s.word(w)?;
226 self.nbsp()
227 }
228
229 pub fn head(&mut self, w: &str) -> io::Result<()> {
230 // outer-box is consistent
231 self.cbox(indent_unit)?;
232 // head-box is inconsistent
233 self.ibox(w.len() + 1)?;
234 // keyword that starts the head
235 if !w.is_empty() {
236 self.word_nbsp(w)?;
237 }
238 Ok(())
239 }
240
241 pub fn bopen(&mut self) -> io::Result<()> {
242 self.s.word("{")?;
243 self.end() // close the head-box
244 }
245
246 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
247 self.bclose_maybe_open(span, indented, true)
248 }
249 pub fn bclose_maybe_open(&mut self,
250 span: syntax_pos::Span,
251 indented: usize,
252 close_box: bool)
253 -> io::Result<()> {
254 self.maybe_print_comment(span.hi())?;
255 self.break_offset_if_not_bol(1, -(indented as isize))?;
256 self.s.word("}")?;
257 if close_box {
258 self.end()?; // close the outer-box
259 }
260 Ok(())
261 }
262 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
263 self.bclose_(span, indent_unit)
264 }
265
266 pub fn in_cbox(&self) -> bool {
267 match self.boxes.last() {
268 Some(&last_box) => last_box == pp::Breaks::Consistent,
269 None => false,
270 }
271 }
272 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
273 if !self.is_bol() {
274 self.s.space()?;
275 }
276 Ok(())
277 }
278 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
279 if !self.is_bol() {
280 self.s.break_offset(n, off)
281 } else {
282 if off != 0 && self.s.last_token().is_hardbreak_tok() {
283 // We do something pretty sketchy here: tuck the nonzero
284 // offset-adjustment we were going to deposit along with the
285 // break into the previous hardbreak.
286 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
287 }
288 Ok(())
289 }
290 }
291
292 // Synthesizes a comment that was not textually present in the original source
293 // file.
294 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
295 self.s.word("/*")?;
296 self.s.space()?;
297 self.s.word(&text[..])?;
298 self.s.space()?;
299 self.s.word("*/")
300 }
301
302
303 pub fn commasep_cmnt<T, F, G>(&mut self,
304 b: Breaks,
305 elts: &[T],
306 mut op: F,
307 mut get_span: G)
308 -> io::Result<()>
309 where F: FnMut(&mut State, &T) -> io::Result<()>,
310 G: FnMut(&T) -> syntax_pos::Span
311 {
312 self.rbox(0, b)?;
313 let len = elts.len();
314 let mut i = 0;
315 for elt in elts {
316 self.maybe_print_comment(get_span(elt).hi())?;
317 op(self, elt)?;
318 i += 1;
319 if i < len {
320 self.s.word(",")?;
321 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
322 self.space_if_not_bol()?;
323 }
324 }
325 self.end()
326 }
327
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
332 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
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 Ok(())
338 }
339
340 pub fn print_foreign_mod(&mut self,
341 nmod: &hir::ForeignMod,
342 attrs: &[ast::Attribute])
343 -> io::Result<()> {
344 self.print_inner_attributes(attrs)?;
345 for item in &nmod.items {
346 self.print_foreign_item(item)?;
347 }
348 Ok(())
349 }
350
351 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
352 if !lifetime.is_elided() {
353 self.print_lifetime(lifetime)?;
354 self.nbsp()?;
355 }
356 Ok(())
357 }
358
359 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
360 self.maybe_print_comment(ty.span.lo())?;
361 self.ibox(0)?;
362 match ty.node {
363 hir::TySlice(ref ty) => {
364 self.s.word("[")?;
365 self.print_type(&ty)?;
366 self.s.word("]")?;
367 }
368 hir::TyPtr(ref mt) => {
369 self.s.word("*")?;
370 match mt.mutbl {
371 hir::MutMutable => self.word_nbsp("mut")?,
372 hir::MutImmutable => self.word_nbsp("const")?,
373 }
374 self.print_type(&mt.ty)?;
375 }
376 hir::TyRptr(ref lifetime, ref mt) => {
377 self.s.word("&")?;
378 self.print_opt_lifetime(lifetime)?;
379 self.print_mt(mt)?;
380 }
381 hir::TyNever => {
382 self.s.word("!")?;
383 },
384 hir::TyTup(ref elts) => {
385 self.popen()?;
386 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
387 if elts.len() == 1 {
388 self.s.word(",")?;
389 }
390 self.pclose()?;
391 }
392 hir::TyBareFn(ref f) => {
393 let generics = hir::Generics {
394 lifetimes: f.lifetimes.clone(),
395 ty_params: hir::HirVec::new(),
396 where_clause: hir::WhereClause {
397 id: ast::DUMMY_NODE_ID,
398 predicates: hir::HirVec::new(),
399 },
400 span: syntax_pos::DUMMY_SP,
401 };
402 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics,
403 &f.arg_names[..])?;
404 }
405 hir::TyPath(ref qpath) => {
406 self.print_qpath(qpath, false)?
407 }
408 hir::TyTraitObject(ref bounds, ref lifetime) => {
409 let mut first = true;
410 for bound in bounds {
411 self.nbsp()?;
412 if first {
413 first = false;
414 } else {
415 self.word_space("+")?;
416 }
417 self.print_poly_trait_ref(bound)?;
418 }
419 if !lifetime.is_elided() {
420 self.word_space("+")?;
421 self.print_lifetime(lifetime)?;
422 }
423 }
424 hir::TyImplTraitExistential(ref bounds) |
425 hir::TyImplTraitUniversal(_, ref bounds) => {
426 self.print_bounds("impl", &bounds[..])?;
427 }
428 hir::TyArray(ref ty, v) => {
429 self.s.word("[")?;
430 self.print_type(&ty)?;
431 self.s.word("; ")?;
432 self.ann.nested(self, Nested::Body(v))?;
433 self.s.word("]")?;
434 }
435 hir::TyTypeof(e) => {
436 self.s.word("typeof(")?;
437 self.ann.nested(self, Nested::Body(e))?;
438 self.s.word(")")?;
439 }
440 hir::TyInfer => {
441 self.s.word("_")?;
442 }
443 hir::TyErr => {
444 self.s.word("?")?;
445 }
446 }
447 self.end()
448 }
449
450 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
451 self.hardbreak_if_not_bol()?;
452 self.maybe_print_comment(item.span.lo())?;
453 self.print_outer_attributes(&item.attrs)?;
454 match item.node {
455 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
456 self.head("")?;
457 self.print_fn(decl,
458 hir::Unsafety::Normal,
459 hir::Constness::NotConst,
460 Abi::Rust,
461 Some(item.name),
462 generics,
463 &item.vis,
464 arg_names,
465 None)?;
466 self.end()?; // end head-ibox
467 self.s.word(";")?;
468 self.end() // end the outer fn box
469 }
470 hir::ForeignItemStatic(ref t, m) => {
471 self.head(&visibility_qualified(&item.vis, "static"))?;
472 if m {
473 self.word_space("mut")?;
474 }
475 self.print_name(item.name)?;
476 self.word_space(":")?;
477 self.print_type(&t)?;
478 self.s.word(";")?;
479 self.end()?; // end the head-ibox
480 self.end() // end the outer cbox
481 }
482 hir::ForeignItemType => {
483 self.head(&visibility_qualified(&item.vis, "type"))?;
484 self.print_name(item.name)?;
485 self.s.word(";")?;
486 self.end()?; // end the head-ibox
487 self.end() // end the outer cbox
488 }
489 }
490 }
491
492 fn print_associated_const(&mut self,
493 name: ast::Name,
494 ty: &hir::Ty,
495 default: Option<hir::BodyId>,
496 vis: &hir::Visibility)
497 -> io::Result<()> {
498 self.s.word(&visibility_qualified(vis, ""))?;
499 self.word_space("const")?;
500 self.print_name(name)?;
501 self.word_space(":")?;
502 self.print_type(ty)?;
503 if let Some(expr) = default {
504 self.s.space()?;
505 self.word_space("=")?;
506 self.ann.nested(self, Nested::Body(expr))?;
507 }
508 self.s.word(";")
509 }
510
511 fn print_associated_type(&mut self,
512 name: ast::Name,
513 bounds: Option<&hir::TyParamBounds>,
514 ty: Option<&hir::Ty>)
515 -> io::Result<()> {
516 self.word_space("type")?;
517 self.print_name(name)?;
518 if let Some(bounds) = bounds {
519 self.print_bounds(":", bounds)?;
520 }
521 if let Some(ty) = ty {
522 self.s.space()?;
523 self.word_space("=")?;
524 self.print_type(ty)?;
525 }
526 self.s.word(";")
527 }
528
529 /// Pretty-print an item
530 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
531 self.hardbreak_if_not_bol()?;
532 self.maybe_print_comment(item.span.lo())?;
533 self.print_outer_attributes(&item.attrs)?;
534 self.ann.pre(self, NodeItem(item))?;
535 match item.node {
536 hir::ItemExternCrate(ref optional_path) => {
537 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
538 if let Some(p) = *optional_path {
539 let val = p.as_str();
540 if val.contains("-") {
541 self.print_string(&val, ast::StrStyle::Cooked)?;
542 } else {
543 self.print_name(p)?;
544 }
545 self.s.space()?;
546 self.s.word("as")?;
547 self.s.space()?;
548 }
549 self.print_name(item.name)?;
550 self.s.word(";")?;
551 self.end()?; // end inner head-block
552 self.end()?; // end outer head-block
553 }
554 hir::ItemUse(ref path, kind) => {
555 self.head(&visibility_qualified(&item.vis, "use"))?;
556 self.print_path(path, false)?;
557
558 match kind {
559 hir::UseKind::Single => {
560 if path.segments.last().unwrap().name != item.name {
561 self.s.space()?;
562 self.word_space("as")?;
563 self.print_name(item.name)?;
564 }
565 self.s.word(";")?;
566 }
567 hir::UseKind::Glob => self.s.word("::*;")?,
568 hir::UseKind::ListStem => self.s.word("::{};")?
569 }
570 self.end()?; // end inner head-block
571 self.end()?; // end outer head-block
572 }
573 hir::ItemStatic(ref ty, m, expr) => {
574 self.head(&visibility_qualified(&item.vis, "static"))?;
575 if m == hir::MutMutable {
576 self.word_space("mut")?;
577 }
578 self.print_name(item.name)?;
579 self.word_space(":")?;
580 self.print_type(&ty)?;
581 self.s.space()?;
582 self.end()?; // end the head-ibox
583
584 self.word_space("=")?;
585 self.ann.nested(self, Nested::Body(expr))?;
586 self.s.word(";")?;
587 self.end()?; // end the outer cbox
588 }
589 hir::ItemConst(ref ty, expr) => {
590 self.head(&visibility_qualified(&item.vis, "const"))?;
591 self.print_name(item.name)?;
592 self.word_space(":")?;
593 self.print_type(&ty)?;
594 self.s.space()?;
595 self.end()?; // end the head-ibox
596
597 self.word_space("=")?;
598 self.ann.nested(self, Nested::Body(expr))?;
599 self.s.word(";")?;
600 self.end()?; // end the outer cbox
601 }
602 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, body) => {
603 self.head("")?;
604 self.print_fn(decl,
605 unsafety,
606 constness,
607 abi,
608 Some(item.name),
609 typarams,
610 &item.vis,
611 &[],
612 Some(body))?;
613 self.s.word(" ")?;
614 self.end()?; // need to close a box
615 self.end()?; // need to close a box
616 self.ann.nested(self, Nested::Body(body))?;
617 }
618 hir::ItemMod(ref _mod) => {
619 self.head(&visibility_qualified(&item.vis, "mod"))?;
620 self.print_name(item.name)?;
621 self.nbsp()?;
622 self.bopen()?;
623 self.print_mod(_mod, &item.attrs)?;
624 self.bclose(item.span)?;
625 }
626 hir::ItemForeignMod(ref nmod) => {
627 self.head("extern")?;
628 self.word_nbsp(&nmod.abi.to_string())?;
629 self.bopen()?;
630 self.print_foreign_mod(nmod, &item.attrs)?;
631 self.bclose(item.span)?;
632 }
633 hir::ItemGlobalAsm(ref ga) => {
634 self.head(&visibility_qualified(&item.vis, "global asm"))?;
635 self.s.word(&ga.asm.as_str())?;
636 self.end()?
637 }
638 hir::ItemTy(ref ty, ref params) => {
639 self.ibox(indent_unit)?;
640 self.ibox(0)?;
641 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
642 self.print_name(item.name)?;
643 self.print_generics(params)?;
644 self.end()?; // end the inner ibox
645
646 self.print_where_clause(&params.where_clause)?;
647 self.s.space()?;
648 self.word_space("=")?;
649 self.print_type(&ty)?;
650 self.s.word(";")?;
651 self.end()?; // end the outer ibox
652 }
653 hir::ItemEnum(ref enum_definition, ref params) => {
654 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
655 }
656 hir::ItemStruct(ref struct_def, ref generics) => {
657 self.head(&visibility_qualified(&item.vis, "struct"))?;
658 self.print_struct(struct_def, generics, item.name, item.span, true)?;
659 }
660 hir::ItemUnion(ref struct_def, ref generics) => {
661 self.head(&visibility_qualified(&item.vis, "union"))?;
662 self.print_struct(struct_def, generics, item.name, item.span, true)?;
663 }
664 hir::ItemAutoImpl(unsafety, ref trait_ref) => {
665 self.head("")?;
666 self.print_visibility(&item.vis)?;
667 self.print_unsafety(unsafety)?;
668 self.word_nbsp("impl")?;
669 self.print_trait_ref(trait_ref)?;
670 self.s.space()?;
671 self.word_space("for")?;
672 self.word_space("..")?;
673 self.bopen()?;
674 self.bclose(item.span)?;
675 }
676 hir::ItemImpl(unsafety,
677 polarity,
678 defaultness,
679 ref generics,
680 ref opt_trait,
681 ref ty,
682 ref impl_items) => {
683 self.head("")?;
684 self.print_visibility(&item.vis)?;
685 self.print_defaultness(defaultness)?;
686 self.print_unsafety(unsafety)?;
687 self.word_nbsp("impl")?;
688
689 if generics.is_parameterized() {
690 self.print_generics(generics)?;
691 self.s.space()?;
692 }
693
694 match polarity {
695 hir::ImplPolarity::Negative => {
696 self.s.word("!")?;
697 }
698 _ => {}
699 }
700
701 match opt_trait {
702 &Some(ref t) => {
703 self.print_trait_ref(t)?;
704 self.s.space()?;
705 self.word_space("for")?;
706 }
707 &None => {}
708 }
709
710 self.print_type(&ty)?;
711 self.print_where_clause(&generics.where_clause)?;
712
713 self.s.space()?;
714 self.bopen()?;
715 self.print_inner_attributes(&item.attrs)?;
716 for impl_item in impl_items {
717 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
718 }
719 self.bclose(item.span)?;
720 }
721 hir::ItemTrait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
722 self.head("")?;
723 self.print_visibility(&item.vis)?;
724 self.print_is_auto(is_auto)?;
725 self.print_unsafety(unsafety)?;
726 self.word_nbsp("trait")?;
727 self.print_name(item.name)?;
728 self.print_generics(generics)?;
729 let mut real_bounds = Vec::with_capacity(bounds.len());
730 for b in bounds.iter() {
731 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
732 self.s.space()?;
733 self.word_space("for ?")?;
734 self.print_trait_ref(&ptr.trait_ref)?;
735 } else {
736 real_bounds.push(b.clone());
737 }
738 }
739 self.print_bounds(":", &real_bounds[..])?;
740 self.print_where_clause(&generics.where_clause)?;
741 self.s.word(" ")?;
742 self.bopen()?;
743 for trait_item in trait_items {
744 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
745 }
746 self.bclose(item.span)?;
747 }
748 }
749 self.ann.post(self, NodeItem(item))
750 }
751
752 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
753 self.print_path(&t.path, false)
754 }
755
756 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
757 if !lifetimes.is_empty() {
758 self.s.word("for<")?;
759 let mut comma = false;
760 for lifetime_def in lifetimes {
761 if comma {
762 self.word_space(",")?
763 }
764 self.print_lifetime_def(lifetime_def)?;
765 comma = true;
766 }
767 self.s.word(">")?;
768 }
769 Ok(())
770 }
771
772 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
773 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
774 self.print_trait_ref(&t.trait_ref)
775 }
776
777 pub fn print_enum_def(&mut self,
778 enum_definition: &hir::EnumDef,
779 generics: &hir::Generics,
780 name: ast::Name,
781 span: syntax_pos::Span,
782 visibility: &hir::Visibility)
783 -> io::Result<()> {
784 self.head(&visibility_qualified(visibility, "enum"))?;
785 self.print_name(name)?;
786 self.print_generics(generics)?;
787 self.print_where_clause(&generics.where_clause)?;
788 self.s.space()?;
789 self.print_variants(&enum_definition.variants, span)
790 }
791
792 pub fn print_variants(&mut self,
793 variants: &[hir::Variant],
794 span: syntax_pos::Span)
795 -> io::Result<()> {
796 self.bopen()?;
797 for v in variants {
798 self.space_if_not_bol()?;
799 self.maybe_print_comment(v.span.lo())?;
800 self.print_outer_attributes(&v.node.attrs)?;
801 self.ibox(indent_unit)?;
802 self.print_variant(v)?;
803 self.s.word(",")?;
804 self.end()?;
805 self.maybe_print_trailing_comment(v.span, None)?;
806 }
807 self.bclose(span)
808 }
809
810 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
811 match *vis {
812 hir::Public => self.word_nbsp("pub"),
813 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
814 hir::Visibility::Restricted { ref path, .. } => {
815 self.s.word("pub(")?;
816 self.print_path(path, false)?;
817 self.word_nbsp(")")
818 }
819 hir::Inherited => Ok(()),
820 }
821 }
822
823 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
824 match defaultness {
825 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
826 hir::Defaultness::Final => (),
827 }
828 Ok(())
829 }
830
831 pub fn print_struct(&mut self,
832 struct_def: &hir::VariantData,
833 generics: &hir::Generics,
834 name: ast::Name,
835 span: syntax_pos::Span,
836 print_finalizer: bool)
837 -> io::Result<()> {
838 self.print_name(name)?;
839 self.print_generics(generics)?;
840 if !struct_def.is_struct() {
841 if struct_def.is_tuple() {
842 self.popen()?;
843 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
844 s.maybe_print_comment(field.span.lo())?;
845 s.print_outer_attributes(&field.attrs)?;
846 s.print_visibility(&field.vis)?;
847 s.print_type(&field.ty)
848 })?;
849 self.pclose()?;
850 }
851 self.print_where_clause(&generics.where_clause)?;
852 if print_finalizer {
853 self.s.word(";")?;
854 }
855 self.end()?;
856 self.end() // close the outer-box
857 } else {
858 self.print_where_clause(&generics.where_clause)?;
859 self.nbsp()?;
860 self.bopen()?;
861 self.hardbreak_if_not_bol()?;
862
863 for field in struct_def.fields() {
864 self.hardbreak_if_not_bol()?;
865 self.maybe_print_comment(field.span.lo())?;
866 self.print_outer_attributes(&field.attrs)?;
867 self.print_visibility(&field.vis)?;
868 self.print_name(field.name)?;
869 self.word_nbsp(":")?;
870 self.print_type(&field.ty)?;
871 self.s.word(",")?;
872 }
873
874 self.bclose(span)
875 }
876 }
877
878 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
879 self.head("")?;
880 let generics = hir::Generics::empty();
881 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
882 if let Some(d) = v.node.disr_expr {
883 self.s.space()?;
884 self.word_space("=")?;
885 self.ann.nested(self, Nested::Body(d))?;
886 }
887 Ok(())
888 }
889 pub fn print_method_sig(&mut self,
890 name: ast::Name,
891 m: &hir::MethodSig,
892 generics: &hir::Generics,
893 vis: &hir::Visibility,
894 arg_names: &[Spanned<ast::Name>],
895 body_id: Option<hir::BodyId>)
896 -> io::Result<()> {
897 self.print_fn(&m.decl,
898 m.unsafety,
899 m.constness,
900 m.abi,
901 Some(name),
902 generics,
903 vis,
904 arg_names,
905 body_id)
906 }
907
908 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
909 self.ann.pre(self, NodeSubItem(ti.id))?;
910 self.hardbreak_if_not_bol()?;
911 self.maybe_print_comment(ti.span.lo())?;
912 self.print_outer_attributes(&ti.attrs)?;
913 match ti.node {
914 hir::TraitItemKind::Const(ref ty, default) => {
915 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
916 }
917 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
918 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, arg_names,
919 None)?;
920 self.s.word(";")?;
921 }
922 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
923 self.head("")?;
924 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, &[],
925 Some(body))?;
926 self.nbsp()?;
927 self.end()?; // need to close a box
928 self.end()?; // need to close a box
929 self.ann.nested(self, Nested::Body(body))?;
930 }
931 hir::TraitItemKind::Type(ref bounds, ref default) => {
932 self.print_associated_type(ti.name,
933 Some(bounds),
934 default.as_ref().map(|ty| &**ty))?;
935 }
936 }
937 self.ann.post(self, NodeSubItem(ti.id))
938 }
939
940 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
941 self.ann.pre(self, NodeSubItem(ii.id))?;
942 self.hardbreak_if_not_bol()?;
943 self.maybe_print_comment(ii.span.lo())?;
944 self.print_outer_attributes(&ii.attrs)?;
945 self.print_defaultness(ii.defaultness)?;
946
947 match ii.node {
948 hir::ImplItemKind::Const(ref ty, expr) => {
949 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
950 }
951 hir::ImplItemKind::Method(ref sig, body) => {
952 self.head("")?;
953 self.print_method_sig(ii.name, sig, &ii.generics, &ii.vis, &[], Some(body))?;
954 self.nbsp()?;
955 self.end()?; // need to close a box
956 self.end()?; // need to close a box
957 self.ann.nested(self, Nested::Body(body))?;
958 }
959 hir::ImplItemKind::Type(ref ty) => {
960 self.print_associated_type(ii.name, None, Some(ty))?;
961 }
962 }
963 self.ann.post(self, NodeSubItem(ii.id))
964 }
965
966 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
967 self.maybe_print_comment(st.span.lo())?;
968 match st.node {
969 hir::StmtDecl(ref decl, _) => {
970 self.print_decl(&decl)?;
971 }
972 hir::StmtExpr(ref expr, _) => {
973 self.space_if_not_bol()?;
974 self.print_expr(&expr)?;
975 }
976 hir::StmtSemi(ref expr, _) => {
977 self.space_if_not_bol()?;
978 self.print_expr(&expr)?;
979 self.s.word(";")?;
980 }
981 }
982 if stmt_ends_with_semi(&st.node) {
983 self.s.word(";")?;
984 }
985 self.maybe_print_trailing_comment(st.span, None)
986 }
987
988 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
989 self.print_block_with_attrs(blk, &[])
990 }
991
992 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
993 self.print_block_unclosed_indent(blk, indent_unit)
994 }
995
996 pub fn print_block_unclosed_indent(&mut self,
997 blk: &hir::Block,
998 indented: usize)
999 -> io::Result<()> {
1000 self.print_block_maybe_unclosed(blk, indented, &[], false)
1001 }
1002
1003 pub fn print_block_with_attrs(&mut self,
1004 blk: &hir::Block,
1005 attrs: &[ast::Attribute])
1006 -> io::Result<()> {
1007 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1008 }
1009
1010 pub fn print_block_maybe_unclosed(&mut self,
1011 blk: &hir::Block,
1012 indented: usize,
1013 attrs: &[ast::Attribute],
1014 close_box: bool)
1015 -> io::Result<()> {
1016 match blk.rules {
1017 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1018 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1019 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1020 hir::DefaultBlock => (),
1021 }
1022 self.maybe_print_comment(blk.span.lo())?;
1023 self.ann.pre(self, NodeBlock(blk))?;
1024 self.bopen()?;
1025
1026 self.print_inner_attributes(attrs)?;
1027
1028 for st in &blk.stmts {
1029 self.print_stmt(st)?;
1030 }
1031 match blk.expr {
1032 Some(ref expr) => {
1033 self.space_if_not_bol()?;
1034 self.print_expr(&expr)?;
1035 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1036 }
1037 _ => (),
1038 }
1039 self.bclose_maybe_open(blk.span, indented, close_box)?;
1040 self.ann.post(self, NodeBlock(blk))
1041 }
1042
1043 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1044 match els {
1045 Some(_else) => {
1046 match _else.node {
1047 // "another else-if"
1048 hir::ExprIf(ref i, ref then, ref e) => {
1049 self.cbox(indent_unit - 1)?;
1050 self.ibox(0)?;
1051 self.s.word(" else if ")?;
1052 self.print_expr_as_cond(&i)?;
1053 self.s.space()?;
1054 self.print_expr(&then)?;
1055 self.print_else(e.as_ref().map(|e| &**e))
1056 }
1057 // "final else"
1058 hir::ExprBlock(ref b) => {
1059 self.cbox(indent_unit - 1)?;
1060 self.ibox(0)?;
1061 self.s.word(" else ")?;
1062 self.print_block(&b)
1063 }
1064 // BLEAH, constraints would be great here
1065 _ => {
1066 panic!("print_if saw if with weird alternative");
1067 }
1068 }
1069 }
1070 _ => Ok(()),
1071 }
1072 }
1073
1074 pub fn print_if(&mut self,
1075 test: &hir::Expr,
1076 blk: &hir::Expr,
1077 elseopt: Option<&hir::Expr>)
1078 -> io::Result<()> {
1079 self.head("if")?;
1080 self.print_expr_as_cond(test)?;
1081 self.s.space()?;
1082 self.print_expr(blk)?;
1083 self.print_else(elseopt)
1084 }
1085
1086 pub fn print_if_let(&mut self,
1087 pat: &hir::Pat,
1088 expr: &hir::Expr,
1089 blk: &hir::Block,
1090 elseopt: Option<&hir::Expr>)
1091 -> io::Result<()> {
1092 self.head("if let")?;
1093 self.print_pat(pat)?;
1094 self.s.space()?;
1095 self.word_space("=")?;
1096 self.print_expr_as_cond(expr)?;
1097 self.s.space()?;
1098 self.print_block(blk)?;
1099 self.print_else(elseopt)
1100 }
1101
1102
1103 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1104 self.popen()?;
1105 self.commasep_exprs(Inconsistent, args)?;
1106 self.pclose()
1107 }
1108
1109 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1110 let needs_par = expr_precedence(expr) < prec;
1111 if needs_par {
1112 self.popen()?;
1113 }
1114 self.print_expr(expr)?;
1115 if needs_par {
1116 self.pclose()?;
1117 }
1118 Ok(())
1119 }
1120
1121 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1122 /// `if cond { ... }`.
1123 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1124 let needs_par = match expr.node {
1125 // These cases need parens due to the parse error observed in #26461: `if return {}`
1126 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1127 hir::ExprClosure(..) |
1128 hir::ExprRet(..) |
1129 hir::ExprBreak(..) => true,
1130
1131 _ => contains_exterior_struct_lit(expr),
1132 };
1133
1134 if needs_par {
1135 self.popen()?;
1136 }
1137 self.print_expr(expr)?;
1138 if needs_par {
1139 self.pclose()?;
1140 }
1141 Ok(())
1142 }
1143
1144 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1145 self.ibox(indent_unit)?;
1146 self.s.word("[")?;
1147 self.commasep_exprs(Inconsistent, exprs)?;
1148 self.s.word("]")?;
1149 self.end()
1150 }
1151
1152 fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1153 self.ibox(indent_unit)?;
1154 self.s.word("[")?;
1155 self.print_expr(element)?;
1156 self.word_space(";")?;
1157 self.ann.nested(self, Nested::Body(count))?;
1158 self.s.word("]")?;
1159 self.end()
1160 }
1161
1162 fn print_expr_struct(&mut self,
1163 qpath: &hir::QPath,
1164 fields: &[hir::Field],
1165 wth: &Option<P<hir::Expr>>)
1166 -> io::Result<()> {
1167 self.print_qpath(qpath, true)?;
1168 self.s.word("{")?;
1169 self.commasep_cmnt(Consistent,
1170 &fields[..],
1171 |s, field| {
1172 s.ibox(indent_unit)?;
1173 if !field.is_shorthand {
1174 s.print_name(field.name.node)?;
1175 s.word_space(":")?;
1176 }
1177 s.print_expr(&field.expr)?;
1178 s.end()
1179 },
1180 |f| f.span)?;
1181 match *wth {
1182 Some(ref expr) => {
1183 self.ibox(indent_unit)?;
1184 if !fields.is_empty() {
1185 self.s.word(",")?;
1186 self.s.space()?;
1187 }
1188 self.s.word("..")?;
1189 self.print_expr(&expr)?;
1190 self.end()?;
1191 }
1192 _ => if !fields.is_empty() {
1193 self.s.word(",")?
1194 },
1195 }
1196 self.s.word("}")?;
1197 Ok(())
1198 }
1199
1200 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1201 self.popen()?;
1202 self.commasep_exprs(Inconsistent, exprs)?;
1203 if exprs.len() == 1 {
1204 self.s.word(",")?;
1205 }
1206 self.pclose()
1207 }
1208
1209 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1210 let prec =
1211 match func.node {
1212 hir::ExprField(..) |
1213 hir::ExprTupField(..) => parser::PREC_FORCE_PAREN,
1214 _ => parser::PREC_POSTFIX,
1215 };
1216
1217 self.print_expr_maybe_paren(func, prec)?;
1218 self.print_call_post(args)
1219 }
1220
1221 fn print_expr_method_call(&mut self,
1222 segment: &hir::PathSegment,
1223 args: &[hir::Expr])
1224 -> io::Result<()> {
1225 let base_args = &args[1..];
1226 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1227 self.s.word(".")?;
1228 self.print_name(segment.name)?;
1229
1230 segment.with_parameters(|parameters| {
1231 if !parameters.lifetimes.is_empty() ||
1232 !parameters.types.is_empty() ||
1233 !parameters.bindings.is_empty()
1234 {
1235 self.print_path_parameters(&parameters, segment.infer_types, true)
1236 } else {
1237 Ok(())
1238 }
1239 })?;
1240 self.print_call_post(base_args)
1241 }
1242
1243 fn print_expr_binary(&mut self,
1244 op: hir::BinOp,
1245 lhs: &hir::Expr,
1246 rhs: &hir::Expr)
1247 -> io::Result<()> {
1248 let assoc_op = bin_op_to_assoc_op(op.node);
1249 let prec = assoc_op.precedence() as i8;
1250 let fixity = assoc_op.fixity();
1251
1252 let (left_prec, right_prec) = match fixity {
1253 Fixity::Left => (prec, prec + 1),
1254 Fixity::Right => (prec + 1, prec),
1255 Fixity::None => (prec + 1, prec + 1),
1256 };
1257
1258 let left_prec = match (&lhs.node, op.node) {
1259 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1260 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1261 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1262 (&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1263 (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1264 _ => left_prec,
1265 };
1266
1267 self.print_expr_maybe_paren(lhs, left_prec)?;
1268 self.s.space()?;
1269 self.word_space(op.node.as_str())?;
1270 self.print_expr_maybe_paren(rhs, right_prec)
1271 }
1272
1273 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1274 self.s.word(op.as_str())?;
1275 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1276 }
1277
1278 fn print_expr_addr_of(&mut self,
1279 mutability: hir::Mutability,
1280 expr: &hir::Expr)
1281 -> io::Result<()> {
1282 self.s.word("&")?;
1283 self.print_mutability(mutability)?;
1284 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1285 }
1286
1287 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1288 self.maybe_print_comment(expr.span.lo())?;
1289 self.print_outer_attributes(&expr.attrs)?;
1290 self.ibox(indent_unit)?;
1291 self.ann.pre(self, NodeExpr(expr))?;
1292 match expr.node {
1293 hir::ExprBox(ref expr) => {
1294 self.word_space("box")?;
1295 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1296 }
1297 hir::ExprArray(ref exprs) => {
1298 self.print_expr_vec(exprs)?;
1299 }
1300 hir::ExprRepeat(ref element, count) => {
1301 self.print_expr_repeat(&element, count)?;
1302 }
1303 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1304 self.print_expr_struct(qpath, &fields[..], wth)?;
1305 }
1306 hir::ExprTup(ref exprs) => {
1307 self.print_expr_tup(exprs)?;
1308 }
1309 hir::ExprCall(ref func, ref args) => {
1310 self.print_expr_call(&func, args)?;
1311 }
1312 hir::ExprMethodCall(ref segment, _, ref args) => {
1313 self.print_expr_method_call(segment, args)?;
1314 }
1315 hir::ExprBinary(op, ref lhs, ref rhs) => {
1316 self.print_expr_binary(op, &lhs, &rhs)?;
1317 }
1318 hir::ExprUnary(op, ref expr) => {
1319 self.print_expr_unary(op, &expr)?;
1320 }
1321 hir::ExprAddrOf(m, ref expr) => {
1322 self.print_expr_addr_of(m, &expr)?;
1323 }
1324 hir::ExprLit(ref lit) => {
1325 self.print_literal(&lit)?;
1326 }
1327 hir::ExprCast(ref expr, ref ty) => {
1328 let prec = AssocOp::As.precedence() as i8;
1329 self.print_expr_maybe_paren(&expr, prec)?;
1330 self.s.space()?;
1331 self.word_space("as")?;
1332 self.print_type(&ty)?;
1333 }
1334 hir::ExprType(ref expr, ref ty) => {
1335 let prec = AssocOp::Colon.precedence() as i8;
1336 self.print_expr_maybe_paren(&expr, prec)?;
1337 self.word_space(":")?;
1338 self.print_type(&ty)?;
1339 }
1340 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1341 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1342 }
1343 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1344 if let Some(sp_name) = opt_sp_name {
1345 self.print_name(sp_name.node)?;
1346 self.word_space(":")?;
1347 }
1348 self.head("while")?;
1349 self.print_expr_as_cond(&test)?;
1350 self.s.space()?;
1351 self.print_block(&blk)?;
1352 }
1353 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1354 if let Some(sp_name) = opt_sp_name {
1355 self.print_name(sp_name.node)?;
1356 self.word_space(":")?;
1357 }
1358 self.head("loop")?;
1359 self.s.space()?;
1360 self.print_block(&blk)?;
1361 }
1362 hir::ExprMatch(ref expr, ref arms, _) => {
1363 self.cbox(indent_unit)?;
1364 self.ibox(4)?;
1365 self.word_nbsp("match")?;
1366 self.print_expr_as_cond(&expr)?;
1367 self.s.space()?;
1368 self.bopen()?;
1369 for arm in arms {
1370 self.print_arm(arm)?;
1371 }
1372 self.bclose_(expr.span, indent_unit)?;
1373 }
1374 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1375 self.print_capture_clause(capture_clause)?;
1376
1377 self.print_closure_args(&decl, body)?;
1378 self.s.space()?;
1379
1380 // this is a bare expression
1381 self.ann.nested(self, Nested::Body(body))?;
1382 self.end()?; // need to close a box
1383
1384 // a box will be closed by print_expr, but we didn't want an overall
1385 // wrapper so we closed the corresponding opening. so create an
1386 // empty box to satisfy the close.
1387 self.ibox(0)?;
1388 }
1389 hir::ExprBlock(ref blk) => {
1390 // containing cbox, will be closed by print-block at }
1391 self.cbox(indent_unit)?;
1392 // head-box, will be closed by print-block after {
1393 self.ibox(0)?;
1394 self.print_block(&blk)?;
1395 }
1396 hir::ExprAssign(ref lhs, ref rhs) => {
1397 let prec = AssocOp::Assign.precedence() as i8;
1398 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1399 self.s.space()?;
1400 self.word_space("=")?;
1401 self.print_expr_maybe_paren(&rhs, prec)?;
1402 }
1403 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1404 let prec = AssocOp::Assign.precedence() as i8;
1405 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1406 self.s.space()?;
1407 self.s.word(op.node.as_str())?;
1408 self.word_space("=")?;
1409 self.print_expr_maybe_paren(&rhs, prec)?;
1410 }
1411 hir::ExprField(ref expr, name) => {
1412 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1413 self.s.word(".")?;
1414 self.print_name(name.node)?;
1415 }
1416 hir::ExprTupField(ref expr, id) => {
1417 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1418 self.s.word(".")?;
1419 self.print_usize(id.node)?;
1420 }
1421 hir::ExprIndex(ref expr, ref index) => {
1422 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1423 self.s.word("[")?;
1424 self.print_expr(&index)?;
1425 self.s.word("]")?;
1426 }
1427 hir::ExprPath(ref qpath) => {
1428 self.print_qpath(qpath, true)?
1429 }
1430 hir::ExprBreak(label, ref opt_expr) => {
1431 self.s.word("break")?;
1432 self.s.space()?;
1433 if let Some(label_ident) = label.ident {
1434 self.print_name(label_ident.node.name)?;
1435 self.s.space()?;
1436 }
1437 if let Some(ref expr) = *opt_expr {
1438 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1439 self.s.space()?;
1440 }
1441 }
1442 hir::ExprAgain(label) => {
1443 self.s.word("continue")?;
1444 self.s.space()?;
1445 if let Some(label_ident) = label.ident {
1446 self.print_name(label_ident.node.name)?;
1447 self.s.space()?
1448 }
1449 }
1450 hir::ExprRet(ref result) => {
1451 self.s.word("return")?;
1452 match *result {
1453 Some(ref expr) => {
1454 self.s.word(" ")?;
1455 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1456 }
1457 _ => (),
1458 }
1459 }
1460 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1461 self.s.word("asm!")?;
1462 self.popen()?;
1463 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1464 self.word_space(":")?;
1465
1466 let mut out_idx = 0;
1467 self.commasep(Inconsistent, &a.outputs, |s, out| {
1468 let constraint = out.constraint.as_str();
1469 let mut ch = constraint.chars();
1470 match ch.next() {
1471 Some('=') if out.is_rw => {
1472 s.print_string(&format!("+{}", ch.as_str()),
1473 ast::StrStyle::Cooked)?
1474 }
1475 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1476 }
1477 s.popen()?;
1478 s.print_expr(&outputs[out_idx])?;
1479 s.pclose()?;
1480 out_idx += 1;
1481 Ok(())
1482 })?;
1483 self.s.space()?;
1484 self.word_space(":")?;
1485
1486 let mut in_idx = 0;
1487 self.commasep(Inconsistent, &a.inputs, |s, co| {
1488 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1489 s.popen()?;
1490 s.print_expr(&inputs[in_idx])?;
1491 s.pclose()?;
1492 in_idx += 1;
1493 Ok(())
1494 })?;
1495 self.s.space()?;
1496 self.word_space(":")?;
1497
1498 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1499 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1500 Ok(())
1501 })?;
1502
1503 let mut options = vec![];
1504 if a.volatile {
1505 options.push("volatile");
1506 }
1507 if a.alignstack {
1508 options.push("alignstack");
1509 }
1510 if a.dialect == ast::AsmDialect::Intel {
1511 options.push("intel");
1512 }
1513
1514 if !options.is_empty() {
1515 self.s.space()?;
1516 self.word_space(":")?;
1517 self.commasep(Inconsistent, &options, |s, &co| {
1518 s.print_string(co, ast::StrStyle::Cooked)?;
1519 Ok(())
1520 })?;
1521 }
1522
1523 self.pclose()?;
1524 }
1525 hir::ExprYield(ref expr) => {
1526 self.word_space("yield")?;
1527 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1528 }
1529 }
1530 self.ann.post(self, NodeExpr(expr))?;
1531 self.end()
1532 }
1533
1534 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1535 self.print_pat(&loc.pat)?;
1536 if let Some(ref ty) = loc.ty {
1537 self.word_space(":")?;
1538 self.print_type(&ty)?;
1539 }
1540 Ok(())
1541 }
1542
1543 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1544 self.maybe_print_comment(decl.span.lo())?;
1545 match decl.node {
1546 hir::DeclLocal(ref loc) => {
1547 self.space_if_not_bol()?;
1548 self.ibox(indent_unit)?;
1549 self.word_nbsp("let")?;
1550
1551 self.ibox(indent_unit)?;
1552 self.print_local_decl(&loc)?;
1553 self.end()?;
1554 if let Some(ref init) = loc.init {
1555 self.nbsp()?;
1556 self.word_space("=")?;
1557 self.print_expr(&init)?;
1558 }
1559 self.end()
1560 }
1561 hir::DeclItem(item) => {
1562 self.ann.nested(self, Nested::Item(item))
1563 }
1564 }
1565 }
1566
1567 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1568 self.s.word(&i.to_string())
1569 }
1570
1571 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1572 self.s.word(&name.as_str())?;
1573 self.ann.post(self, NodeName(&name))
1574 }
1575
1576 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1577 self.print_local_decl(loc)?;
1578 self.s.space()?;
1579 self.word_space("in")?;
1580 self.print_expr(coll)
1581 }
1582
1583 pub fn print_path(&mut self,
1584 path: &hir::Path,
1585 colons_before_params: bool)
1586 -> io::Result<()> {
1587 self.maybe_print_comment(path.span.lo())?;
1588
1589 for (i, segment) in path.segments.iter().enumerate() {
1590 if i > 0 {
1591 self.s.word("::")?
1592 }
1593 if segment.name != keywords::CrateRoot.name() &&
1594 segment.name != keywords::DollarCrate.name() {
1595 self.print_name(segment.name)?;
1596 segment.with_parameters(|parameters| {
1597 self.print_path_parameters(parameters,
1598 segment.infer_types,
1599 colons_before_params)
1600 })?;
1601 }
1602 }
1603
1604 Ok(())
1605 }
1606
1607 pub fn print_qpath(&mut self,
1608 qpath: &hir::QPath,
1609 colons_before_params: bool)
1610 -> io::Result<()> {
1611 match *qpath {
1612 hir::QPath::Resolved(None, ref path) => {
1613 self.print_path(path, colons_before_params)
1614 }
1615 hir::QPath::Resolved(Some(ref qself), ref path) => {
1616 self.s.word("<")?;
1617 self.print_type(qself)?;
1618 self.s.space()?;
1619 self.word_space("as")?;
1620
1621 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1622 if i > 0 {
1623 self.s.word("::")?
1624 }
1625 if segment.name != keywords::CrateRoot.name() &&
1626 segment.name != keywords::DollarCrate.name() {
1627 self.print_name(segment.name)?;
1628 segment.with_parameters(|parameters| {
1629 self.print_path_parameters(parameters,
1630 segment.infer_types,
1631 colons_before_params)
1632 })?;
1633 }
1634 }
1635
1636 self.s.word(">")?;
1637 self.s.word("::")?;
1638 let item_segment = path.segments.last().unwrap();
1639 self.print_name(item_segment.name)?;
1640 item_segment.with_parameters(|parameters| {
1641 self.print_path_parameters(parameters,
1642 item_segment.infer_types,
1643 colons_before_params)
1644 })
1645 }
1646 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1647 self.s.word("<")?;
1648 self.print_type(qself)?;
1649 self.s.word(">")?;
1650 self.s.word("::")?;
1651 self.print_name(item_segment.name)?;
1652 item_segment.with_parameters(|parameters| {
1653 self.print_path_parameters(parameters,
1654 item_segment.infer_types,
1655 colons_before_params)
1656 })
1657 }
1658 }
1659 }
1660
1661 fn print_path_parameters(&mut self,
1662 parameters: &hir::PathParameters,
1663 infer_types: bool,
1664 colons_before_params: bool)
1665 -> io::Result<()> {
1666 if parameters.parenthesized {
1667 self.s.word("(")?;
1668 self.commasep(Inconsistent, parameters.inputs(), |s, ty| s.print_type(&ty))?;
1669 self.s.word(")")?;
1670
1671 self.space_if_not_bol()?;
1672 self.word_space("->")?;
1673 self.print_type(&parameters.bindings[0].ty)?;
1674 } else {
1675 let start = if colons_before_params { "::<" } else { "<" };
1676 let empty = Cell::new(true);
1677 let start_or_comma = |this: &mut Self| {
1678 if empty.get() {
1679 empty.set(false);
1680 this.s.word(start)
1681 } else {
1682 this.word_space(",")
1683 }
1684 };
1685
1686 if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) {
1687 for lifetime in &parameters.lifetimes {
1688 start_or_comma(self)?;
1689 self.print_lifetime(lifetime)?;
1690 }
1691 }
1692
1693 if !parameters.types.is_empty() {
1694 start_or_comma(self)?;
1695 self.commasep(Inconsistent, &parameters.types, |s, ty| s.print_type(&ty))?;
1696 }
1697
1698 // FIXME(eddyb) This would leak into error messages, e.g.:
1699 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1700 if infer_types && false {
1701 start_or_comma(self)?;
1702 self.s.word("..")?;
1703 }
1704
1705 for binding in parameters.bindings.iter() {
1706 start_or_comma(self)?;
1707 self.print_name(binding.name)?;
1708 self.s.space()?;
1709 self.word_space("=")?;
1710 self.print_type(&binding.ty)?;
1711 }
1712
1713 if !empty.get() {
1714 self.s.word(">")?
1715 }
1716 }
1717
1718 Ok(())
1719 }
1720
1721 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1722 self.maybe_print_comment(pat.span.lo())?;
1723 self.ann.pre(self, NodePat(pat))?;
1724 // Pat isn't normalized, but the beauty of it
1725 // is that it doesn't matter
1726 match pat.node {
1727 PatKind::Wild => self.s.word("_")?,
1728 PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1729 match binding_mode {
1730 hir::BindingAnnotation::Ref => {
1731 self.word_nbsp("ref")?;
1732 self.print_mutability(hir::MutImmutable)?;
1733 }
1734 hir::BindingAnnotation::RefMut => {
1735 self.word_nbsp("ref")?;
1736 self.print_mutability(hir::MutMutable)?;
1737 }
1738 hir::BindingAnnotation::Unannotated => {}
1739 hir::BindingAnnotation::Mutable => {
1740 self.word_nbsp("mut")?;
1741 }
1742 }
1743 self.print_name(path1.node)?;
1744 if let Some(ref p) = *sub {
1745 self.s.word("@")?;
1746 self.print_pat(&p)?;
1747 }
1748 }
1749 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1750 self.print_qpath(qpath, true)?;
1751 self.popen()?;
1752 if let Some(ddpos) = ddpos {
1753 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1754 if ddpos != 0 {
1755 self.word_space(",")?;
1756 }
1757 self.s.word("..")?;
1758 if ddpos != elts.len() {
1759 self.s.word(",")?;
1760 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1761 }
1762 } else {
1763 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1764 }
1765 self.pclose()?;
1766 }
1767 PatKind::Path(ref qpath) => {
1768 self.print_qpath(qpath, true)?;
1769 }
1770 PatKind::Struct(ref qpath, ref fields, etc) => {
1771 self.print_qpath(qpath, true)?;
1772 self.nbsp()?;
1773 self.word_space("{")?;
1774 self.commasep_cmnt(Consistent,
1775 &fields[..],
1776 |s, f| {
1777 s.cbox(indent_unit)?;
1778 if !f.node.is_shorthand {
1779 s.print_name(f.node.name)?;
1780 s.word_nbsp(":")?;
1781 }
1782 s.print_pat(&f.node.pat)?;
1783 s.end()
1784 },
1785 |f| f.node.pat.span)?;
1786 if etc {
1787 if !fields.is_empty() {
1788 self.word_space(",")?;
1789 }
1790 self.s.word("..")?;
1791 }
1792 self.s.space()?;
1793 self.s.word("}")?;
1794 }
1795 PatKind::Tuple(ref elts, ddpos) => {
1796 self.popen()?;
1797 if let Some(ddpos) = ddpos {
1798 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1799 if ddpos != 0 {
1800 self.word_space(",")?;
1801 }
1802 self.s.word("..")?;
1803 if ddpos != elts.len() {
1804 self.s.word(",")?;
1805 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1806 }
1807 } else {
1808 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1809 if elts.len() == 1 {
1810 self.s.word(",")?;
1811 }
1812 }
1813 self.pclose()?;
1814 }
1815 PatKind::Box(ref inner) => {
1816 self.s.word("box ")?;
1817 self.print_pat(&inner)?;
1818 }
1819 PatKind::Ref(ref inner, mutbl) => {
1820 self.s.word("&")?;
1821 if mutbl == hir::MutMutable {
1822 self.s.word("mut ")?;
1823 }
1824 self.print_pat(&inner)?;
1825 }
1826 PatKind::Lit(ref e) => self.print_expr(&e)?,
1827 PatKind::Range(ref begin, ref end, ref end_kind) => {
1828 self.print_expr(&begin)?;
1829 self.s.space()?;
1830 match *end_kind {
1831 RangeEnd::Included => self.s.word("...")?,
1832 RangeEnd::Excluded => self.s.word("..")?,
1833 }
1834 self.print_expr(&end)?;
1835 }
1836 PatKind::Slice(ref before, ref slice, ref after) => {
1837 self.s.word("[")?;
1838 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1839 if let Some(ref p) = *slice {
1840 if !before.is_empty() {
1841 self.word_space(",")?;
1842 }
1843 if p.node != PatKind::Wild {
1844 self.print_pat(&p)?;
1845 }
1846 self.s.word("..")?;
1847 if !after.is_empty() {
1848 self.word_space(",")?;
1849 }
1850 }
1851 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1852 self.s.word("]")?;
1853 }
1854 }
1855 self.ann.post(self, NodePat(pat))
1856 }
1857
1858 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1859 // I have no idea why this check is necessary, but here it
1860 // is :(
1861 if arm.attrs.is_empty() {
1862 self.s.space()?;
1863 }
1864 self.cbox(indent_unit)?;
1865 self.ibox(0)?;
1866 self.print_outer_attributes(&arm.attrs)?;
1867 let mut first = true;
1868 for p in &arm.pats {
1869 if first {
1870 first = false;
1871 } else {
1872 self.s.space()?;
1873 self.word_space("|")?;
1874 }
1875 self.print_pat(&p)?;
1876 }
1877 self.s.space()?;
1878 if let Some(ref e) = arm.guard {
1879 self.word_space("if")?;
1880 self.print_expr(&e)?;
1881 self.s.space()?;
1882 }
1883 self.word_space("=>")?;
1884
1885 match arm.body.node {
1886 hir::ExprBlock(ref blk) => {
1887 // the block will close the pattern's ibox
1888 self.print_block_unclosed_indent(&blk, indent_unit)?;
1889
1890 // If it is a user-provided unsafe block, print a comma after it
1891 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1892 self.s.word(",")?;
1893 }
1894 }
1895 _ => {
1896 self.end()?; // close the ibox for the pattern
1897 self.print_expr(&arm.body)?;
1898 self.s.word(",")?;
1899 }
1900 }
1901 self.end() // close enclosing cbox
1902 }
1903
1904 pub fn print_fn(&mut self,
1905 decl: &hir::FnDecl,
1906 unsafety: hir::Unsafety,
1907 constness: hir::Constness,
1908 abi: Abi,
1909 name: Option<ast::Name>,
1910 generics: &hir::Generics,
1911 vis: &hir::Visibility,
1912 arg_names: &[Spanned<ast::Name>],
1913 body_id: Option<hir::BodyId>)
1914 -> io::Result<()> {
1915 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1916
1917 if let Some(name) = name {
1918 self.nbsp()?;
1919 self.print_name(name)?;
1920 }
1921 self.print_generics(generics)?;
1922
1923 self.popen()?;
1924 let mut i = 0;
1925 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1926 assert!(arg_names.is_empty() || body_id.is_none());
1927 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1928 s.ibox(indent_unit)?;
1929 if let Some(name) = arg_names.get(i) {
1930 s.s.word(&name.node.as_str())?;
1931 s.s.word(":")?;
1932 s.s.space()?;
1933 } else if let Some(body_id) = body_id {
1934 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1935 s.s.word(":")?;
1936 s.s.space()?;
1937 }
1938 i += 1;
1939 s.print_type(ty)?;
1940 s.end()
1941 })?;
1942 if decl.variadic {
1943 self.s.word(", ...")?;
1944 }
1945 self.pclose()?;
1946
1947 self.print_fn_output(decl)?;
1948 self.print_where_clause(&generics.where_clause)
1949 }
1950
1951 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1952 self.s.word("|")?;
1953 let mut i = 0;
1954 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1955 s.ibox(indent_unit)?;
1956
1957 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1958 i += 1;
1959
1960 if ty.node != hir::TyInfer {
1961 s.s.word(":")?;
1962 s.s.space()?;
1963 s.print_type(ty)?;
1964 }
1965 s.end()
1966 })?;
1967 self.s.word("|")?;
1968
1969 if let hir::DefaultReturn(..) = decl.output {
1970 return Ok(());
1971 }
1972
1973 self.space_if_not_bol()?;
1974 self.word_space("->")?;
1975 match decl.output {
1976 hir::Return(ref ty) => {
1977 self.print_type(&ty)?;
1978 self.maybe_print_comment(ty.span.lo())
1979 }
1980 hir::DefaultReturn(..) => unreachable!(),
1981 }
1982 }
1983
1984 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1985 match capture_clause {
1986 hir::CaptureByValue => self.word_space("move"),
1987 hir::CaptureByRef => Ok(()),
1988 }
1989 }
1990
1991 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1992 if !bounds.is_empty() {
1993 self.s.word(prefix)?;
1994 let mut first = true;
1995 for bound in bounds {
1996 self.nbsp()?;
1997 if first {
1998 first = false;
1999 } else {
2000 self.word_space("+")?;
2001 }
2002
2003 match *bound {
2004 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2005 self.print_poly_trait_ref(tref)
2006 }
2007 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2008 self.s.word("?")?;
2009 self.print_poly_trait_ref(tref)
2010 }
2011 RegionTyParamBound(ref lt) => {
2012 self.print_lifetime(lt)
2013 }
2014 }?
2015 }
2016 Ok(())
2017 } else {
2018 Ok(())
2019 }
2020 }
2021
2022 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2023 self.print_name(lifetime.name.name())
2024 }
2025
2026 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2027 self.print_lifetime(&lifetime.lifetime)?;
2028 let mut sep = ":";
2029 for v in &lifetime.bounds {
2030 self.s.word(sep)?;
2031 self.print_lifetime(v)?;
2032 sep = "+";
2033 }
2034 Ok(())
2035 }
2036
2037 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2038 let total = generics.lifetimes.len() + generics.ty_params.len();
2039 if total == 0 {
2040 return Ok(());
2041 }
2042
2043 self.s.word("<")?;
2044
2045 let mut ints = Vec::new();
2046 for i in 0..total {
2047 ints.push(i);
2048 }
2049
2050 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2051 if idx < generics.lifetimes.len() {
2052 let lifetime = &generics.lifetimes[idx];
2053 s.print_lifetime_def(lifetime)
2054 } else {
2055 let idx = idx - generics.lifetimes.len();
2056 let param = &generics.ty_params[idx];
2057 s.print_ty_param(param)
2058 }
2059 })?;
2060
2061 self.s.word(">")?;
2062 Ok(())
2063 }
2064
2065 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2066 self.print_name(param.name)?;
2067 self.print_bounds(":", &param.bounds)?;
2068 match param.default {
2069 Some(ref default) => {
2070 self.s.space()?;
2071 self.word_space("=")?;
2072 self.print_type(&default)
2073 }
2074 _ => Ok(()),
2075 }
2076 }
2077
2078 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2079 if where_clause.predicates.is_empty() {
2080 return Ok(());
2081 }
2082
2083 self.s.space()?;
2084 self.word_space("where")?;
2085
2086 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2087 if i != 0 {
2088 self.word_space(",")?;
2089 }
2090
2091 match predicate {
2092 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2093 ref bounded_ty,
2094 ref bounds,
2095 ..}) => {
2096 self.print_formal_lifetime_list(bound_lifetimes)?;
2097 self.print_type(&bounded_ty)?;
2098 self.print_bounds(":", bounds)?;
2099 }
2100 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2101 ref bounds,
2102 ..}) => {
2103 self.print_lifetime(lifetime)?;
2104 self.s.word(":")?;
2105
2106 for (i, bound) in bounds.iter().enumerate() {
2107 self.print_lifetime(bound)?;
2108
2109 if i != 0 {
2110 self.s.word(":")?;
2111 }
2112 }
2113 }
2114 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2115 ref rhs_ty,
2116 ..}) => {
2117 self.print_type(lhs_ty)?;
2118 self.s.space()?;
2119 self.word_space("=")?;
2120 self.print_type(rhs_ty)?;
2121 }
2122 }
2123 }
2124
2125 Ok(())
2126 }
2127
2128 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2129 match mutbl {
2130 hir::MutMutable => self.word_nbsp("mut"),
2131 hir::MutImmutable => Ok(()),
2132 }
2133 }
2134
2135 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2136 self.print_mutability(mt.mutbl)?;
2137 self.print_type(&mt.ty)
2138 }
2139
2140 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2141 if let hir::DefaultReturn(..) = decl.output {
2142 return Ok(());
2143 }
2144
2145 self.space_if_not_bol()?;
2146 self.ibox(indent_unit)?;
2147 self.word_space("->")?;
2148 match decl.output {
2149 hir::DefaultReturn(..) => unreachable!(),
2150 hir::Return(ref ty) => self.print_type(&ty)?,
2151 }
2152 self.end()?;
2153
2154 match decl.output {
2155 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2156 _ => Ok(()),
2157 }
2158 }
2159
2160 pub fn print_ty_fn(&mut self,
2161 abi: Abi,
2162 unsafety: hir::Unsafety,
2163 decl: &hir::FnDecl,
2164 name: Option<ast::Name>,
2165 generics: &hir::Generics,
2166 arg_names: &[Spanned<ast::Name>])
2167 -> io::Result<()> {
2168 self.ibox(indent_unit)?;
2169 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2170 self.s.word("for")?;
2171 self.print_generics(generics)?;
2172 }
2173 let generics = hir::Generics {
2174 lifetimes: hir::HirVec::new(),
2175 ty_params: hir::HirVec::new(),
2176 where_clause: hir::WhereClause {
2177 id: ast::DUMMY_NODE_ID,
2178 predicates: hir::HirVec::new(),
2179 },
2180 span: syntax_pos::DUMMY_SP,
2181 };
2182 self.print_fn(decl,
2183 unsafety,
2184 hir::Constness::NotConst,
2185 abi,
2186 name,
2187 &generics,
2188 &hir::Inherited,
2189 arg_names,
2190 None)?;
2191 self.end()
2192 }
2193
2194 pub fn maybe_print_trailing_comment(&mut self,
2195 span: syntax_pos::Span,
2196 next_pos: Option<BytePos>)
2197 -> io::Result<()> {
2198 let cm = match self.cm {
2199 Some(cm) => cm,
2200 _ => return Ok(()),
2201 };
2202 if let Some(ref cmnt) = self.next_comment() {
2203 if (*cmnt).style != comments::Trailing {
2204 return Ok(());
2205 }
2206 let span_line = cm.lookup_char_pos(span.hi());
2207 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2208 let mut next = (*cmnt).pos + BytePos(1);
2209 if let Some(p) = next_pos {
2210 next = p;
2211 }
2212 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2213 span_line.line == comment_line.line {
2214 self.print_comment(cmnt)?;
2215 }
2216 }
2217 Ok(())
2218 }
2219
2220 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2221 // If there aren't any remaining comments, then we need to manually
2222 // make sure there is a line break at the end.
2223 if self.next_comment().is_none() {
2224 self.s.hardbreak()?;
2225 }
2226 loop {
2227 match self.next_comment() {
2228 Some(ref cmnt) => {
2229 self.print_comment(cmnt)?;
2230 }
2231 _ => break,
2232 }
2233 }
2234 Ok(())
2235 }
2236
2237 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2238 opt_abi: Option<Abi>)
2239 -> io::Result<()> {
2240 match opt_abi {
2241 Some(Abi::Rust) => Ok(()),
2242 Some(abi) => {
2243 self.word_nbsp("extern")?;
2244 self.word_nbsp(&abi.to_string())
2245 }
2246 None => Ok(()),
2247 }
2248 }
2249
2250 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2251 match opt_abi {
2252 Some(abi) => {
2253 self.word_nbsp("extern")?;
2254 self.word_nbsp(&abi.to_string())
2255 }
2256 None => Ok(()),
2257 }
2258 }
2259
2260 pub fn print_fn_header_info(&mut self,
2261 unsafety: hir::Unsafety,
2262 constness: hir::Constness,
2263 abi: Abi,
2264 vis: &hir::Visibility)
2265 -> io::Result<()> {
2266 self.s.word(&visibility_qualified(vis, ""))?;
2267 self.print_unsafety(unsafety)?;
2268
2269 match constness {
2270 hir::Constness::NotConst => {}
2271 hir::Constness::Const => self.word_nbsp("const")?,
2272 }
2273
2274 if abi != Abi::Rust {
2275 self.word_nbsp("extern")?;
2276 self.word_nbsp(&abi.to_string())?;
2277 }
2278
2279 self.s.word("fn")
2280 }
2281
2282 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2283 match s {
2284 hir::Unsafety::Normal => Ok(()),
2285 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2286 }
2287 }
2288
2289 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2290 match s {
2291 hir::IsAuto::Yes => self.word_nbsp("auto"),
2292 hir::IsAuto::No => Ok(()),
2293 }
2294 }
2295 }
2296
2297 // Dup'ed from parse::classify, but adapted for the HIR.
2298 /// Does this expression require a semicolon to be treated
2299 /// as a statement? The negation of this: 'can this expression
2300 /// be used as a statement without a semicolon' -- is used
2301 /// as an early-bail-out in the parser so that, for instance,
2302 /// if true {...} else {...}
2303 /// |x| 5
2304 /// isn't parsed as (if true {...} else {...} | x) | 5
2305 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2306 match e.node {
2307 hir::ExprIf(..) |
2308 hir::ExprMatch(..) |
2309 hir::ExprBlock(_) |
2310 hir::ExprWhile(..) |
2311 hir::ExprLoop(..) => false,
2312 _ => true,
2313 }
2314 }
2315
2316 /// this statement requires a semicolon after it.
2317 /// note that in one case (stmt_semi), we've already
2318 /// seen the semicolon, and thus don't need another.
2319 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2320 match *stmt {
2321 hir::StmtDecl(ref d, _) => {
2322 match d.node {
2323 hir::DeclLocal(_) => true,
2324 hir::DeclItem(_) => false,
2325 }
2326 }
2327 hir::StmtExpr(ref e, _) => {
2328 expr_requires_semi_to_be_stmt(&e)
2329 }
2330 hir::StmtSemi(..) => {
2331 false
2332 }
2333 }
2334 }
2335
2336
2337 fn expr_precedence(expr: &hir::Expr) -> i8 {
2338 use syntax::util::parser::*;
2339
2340 match expr.node {
2341 hir::ExprClosure(..) => PREC_CLOSURE,
2342
2343 hir::ExprBreak(..) |
2344 hir::ExprAgain(..) |
2345 hir::ExprRet(..) |
2346 hir::ExprYield(..) => PREC_JUMP,
2347
2348 // Binop-like expr kinds, handled by `AssocOp`.
2349 hir::ExprBinary(op, _, _) => bin_op_to_assoc_op(op.node).precedence() as i8,
2350
2351 hir::ExprCast(..) => AssocOp::As.precedence() as i8,
2352 hir::ExprType(..) => AssocOp::Colon.precedence() as i8,
2353
2354 hir::ExprAssign(..) |
2355 hir::ExprAssignOp(..) => AssocOp::Assign.precedence() as i8,
2356
2357 // Unary, prefix
2358 hir::ExprBox(..) |
2359 hir::ExprAddrOf(..) |
2360 hir::ExprUnary(..) => PREC_PREFIX,
2361
2362 // Unary, postfix
2363 hir::ExprCall(..) |
2364 hir::ExprMethodCall(..) |
2365 hir::ExprField(..) |
2366 hir::ExprTupField(..) |
2367 hir::ExprIndex(..) |
2368 hir::ExprInlineAsm(..) => PREC_POSTFIX,
2369
2370 // Never need parens
2371 hir::ExprArray(..) |
2372 hir::ExprRepeat(..) |
2373 hir::ExprTup(..) |
2374 hir::ExprLit(..) |
2375 hir::ExprPath(..) |
2376 hir::ExprIf(..) |
2377 hir::ExprWhile(..) |
2378 hir::ExprLoop(..) |
2379 hir::ExprMatch(..) |
2380 hir::ExprBlock(..) |
2381 hir::ExprStruct(..) => PREC_PAREN,
2382 }
2383 }
2384
2385 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2386 use hir::BinOp_::*;
2387 match op {
2388 BiAdd => AssocOp::Add,
2389 BiSub => AssocOp::Subtract,
2390 BiMul => AssocOp::Multiply,
2391 BiDiv => AssocOp::Divide,
2392 BiRem => AssocOp::Modulus,
2393
2394 BiAnd => AssocOp::LAnd,
2395 BiOr => AssocOp::LOr,
2396
2397 BiBitXor => AssocOp::BitXor,
2398 BiBitAnd => AssocOp::BitAnd,
2399 BiBitOr => AssocOp::BitOr,
2400 BiShl => AssocOp::ShiftLeft,
2401 BiShr => AssocOp::ShiftRight,
2402
2403 BiEq => AssocOp::Equal,
2404 BiLt => AssocOp::Less,
2405 BiLe => AssocOp::LessEqual,
2406 BiNe => AssocOp::NotEqual,
2407 BiGe => AssocOp::GreaterEqual,
2408 BiGt => AssocOp::Greater,
2409 }
2410 }
2411
2412 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2413 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2414 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2415 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2416 match value.node {
2417 hir::ExprStruct(..) => true,
2418
2419 hir::ExprAssign(ref lhs, ref rhs) |
2420 hir::ExprAssignOp(_, ref lhs, ref rhs) |
2421 hir::ExprBinary(_, ref lhs, ref rhs) => {
2422 // X { y: 1 } + X { y: 2 }
2423 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2424 }
2425 hir::ExprUnary(_, ref x) |
2426 hir::ExprCast(ref x, _) |
2427 hir::ExprType(ref x, _) |
2428 hir::ExprField(ref x, _) |
2429 hir::ExprTupField(ref x, _) |
2430 hir::ExprIndex(ref x, _) => {
2431 // &X { y: 1 }, X { y: 1 }.y
2432 contains_exterior_struct_lit(&x)
2433 }
2434
2435 hir::ExprMethodCall(.., ref exprs) => {
2436 // X { y: 1 }.bar(...)
2437 contains_exterior_struct_lit(&exprs[0])
2438 }
2439
2440 _ => false,
2441 }
2442 }