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.
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.
11 pub use self::AnnNode::*;
15 use syntax::owned_slice::OwnedSlice;
16 use syntax::codemap::{self, CodeMap, BytePos};
17 use syntax::diagnostic;
18 use syntax::parse::token::{self, BinOpToken};
19 use syntax::parse::lexer::comments;
21 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
22 use syntax::print::pp::{Breaks, eof};
23 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
24 use syntax::print::pprust::{self as ast_pp, PrintState};
28 use hir::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
30 use std::io::{self, Write, Read};
32 pub enum AnnNode<'a> {
33 NodeIdent(&'a ast::Ident),
34 NodeName(&'a ast::Name),
35 NodeBlock(&'a hir::Block),
36 NodeItem(&'a hir::Item),
37 NodeSubItem(ast::NodeId),
38 NodeExpr(&'a hir::Expr),
39 NodePat(&'a hir::Pat),
43 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
44 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
47 #[derive(Copy, Clone)]
50 impl PpAnn for NoAnn {}
53 pub struct State<'a> {
54 pub s: pp::Printer<'a>,
55 cm: Option<&'a CodeMap>,
56 comments: Option<Vec<comments::Comment>>,
57 literals: Option<Vec<comments::Literal>>,
58 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
59 boxes: Vec<pp::Breaks>,
63 impl<'a> PrintState<'a> for State<'a> {
64 fn writer(&mut self) -> &mut pp::Printer<'a> {
68 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
72 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
76 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
77 &mut self.cur_cmnt_and_lit
80 fn literals(&self) -> &Option<Vec<comments::Literal>> {
85 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
86 static NO_ANN: NoAnn = NoAnn;
87 rust_printer_annotated(writer, &NO_ANN)
90 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
91 ann: &'a PpAnn) -> State<'a> {
93 s: pp::mk_printer(writer, default_columns),
97 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
106 #[allow(non_upper_case_globals)]
107 pub const indent_unit: usize = 4;
109 #[allow(non_upper_case_globals)]
110 pub const default_columns: usize = 78;
113 /// Requires you to pass an input filename and reader so that
114 /// it can scan the input text for comments and literals to
116 pub fn print_crate<'a>(cm: &'a CodeMap,
117 span_diagnostic: &diagnostic::SpanHandler,
123 is_expanded: bool) -> io::Result<()> {
124 let mut s = State::new_from_input(cm,
132 // When printing the AST, we sometimes need to inject `#[no_std]` here.
133 // Since you can't compile the HIR, it's not necessary.
135 try!(s.print_mod(&krate.module, &krate.attrs));
136 try!(s.print_remaining_comments());
141 pub fn new_from_input(cm: &'a CodeMap,
142 span_diagnostic: &diagnostic::SpanHandler,
147 is_expanded: bool) -> State<'a> {
148 let (cmnts, lits) = comments::gather_comments_and_literals(
158 // If the code is post expansion, don't use the table of
159 // literals, since it doesn't correspond with the literals
160 // in the AST anymore.
161 if is_expanded { None } else { Some(lits) })
164 pub fn new(cm: &'a CodeMap,
167 comments: Option<Vec<comments::Comment>>,
168 literals: Option<Vec<comments::Literal>>) -> State<'a> {
170 s: pp::mk_printer(out, default_columns),
172 comments: comments.clone(),
173 literals: literals.clone(),
174 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
184 pub fn to_string<F>(f: F) -> String where
185 F: FnOnce(&mut State) -> io::Result<()>,
187 let mut wr = Vec::new();
189 let mut printer = rust_printer(Box::new(&mut wr));
190 f(&mut printer).unwrap();
191 eof(&mut printer.s).unwrap();
193 String::from_utf8(wr).unwrap()
196 pub fn binop_to_string(op: BinOpToken) -> &'static str {
202 token::Percent => "%",
211 pub fn ty_to_string(ty: &hir::Ty) -> String {
212 to_string(|s| s.print_type(ty))
215 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
216 to_string(|s| s.print_bounds("", bounds))
219 pub fn pat_to_string(pat: &hir::Pat) -> String {
220 to_string(|s| s.print_pat(pat))
223 pub fn arm_to_string(arm: &hir::Arm) -> String {
224 to_string(|s| s.print_arm(arm))
227 pub fn expr_to_string(e: &hir::Expr) -> String {
228 to_string(|s| s.print_expr(e))
231 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
232 to_string(|s| s.print_lifetime(e))
235 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
236 to_string(|s| s.print_stmt(stmt))
239 pub fn item_to_string(i: &hir::Item) -> String {
240 to_string(|s| s.print_item(i))
243 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
244 to_string(|s| s.print_impl_item(i))
247 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
248 to_string(|s| s.print_trait_item(i))
251 pub fn generics_to_string(generics: &hir::Generics) -> String {
252 to_string(|s| s.print_generics(generics))
255 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
256 to_string(|s| s.print_where_clause(i))
259 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
260 to_string(|s| s.print_fn_block_args(p))
263 pub fn path_to_string(p: &hir::Path) -> String {
264 to_string(|s| s.print_path(p, false, 0))
267 pub fn ident_to_string(id: &ast::Ident) -> String {
268 to_string(|s| s.print_ident(*id))
271 pub fn fun_to_string(decl: &hir::FnDecl,
272 unsafety: hir::Unsafety,
273 constness: hir::Constness,
275 opt_explicit_self: Option<&hir::ExplicitSelf_>,
276 generics: &hir::Generics)
280 try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
281 generics, opt_explicit_self, hir::Inherited));
282 try!(s.end()); // Close the head box
283 s.end() // Close the outer box
287 pub fn block_to_string(blk: &hir::Block) -> String {
289 // containing cbox, will be closed by print-block at }
290 try!(s.cbox(indent_unit));
291 // head-ibox, will be closed by print-block after {
297 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
298 to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
301 pub fn variant_to_string(var: &hir::Variant) -> String {
302 to_string(|s| s.print_variant(var))
305 pub fn arg_to_string(arg: &hir::Arg) -> String {
306 to_string(|s| s.print_arg(arg))
309 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
311 hir::Public => format!("pub {}", s),
312 hir::Inherited => s.to_string()
316 fn needs_parentheses(expr: &hir::Expr) -> bool {
318 hir::ExprAssign(..) | hir::ExprBinary(..) |
319 hir::ExprClosure(..) |
320 hir::ExprAssignOp(..) | hir::ExprCast(..) => true,
326 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
327 self.boxes.push(pp::Breaks::Consistent);
328 pp::cbox(&mut self.s, u)
331 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
333 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
334 try!(word(&mut self.s, w));
338 pub fn head(&mut self, w: &str) -> io::Result<()> {
339 // outer-box is consistent
340 try!(self.cbox(indent_unit));
341 // head-box is inconsistent
342 try!(self.ibox(w.len() + 1));
343 // keyword that starts the head
345 try!(self.word_nbsp(w));
350 pub fn bopen(&mut self) -> io::Result<()> {
351 try!(word(&mut self.s, "{"));
352 self.end() // close the head-box
355 pub fn bclose_(&mut self, span: codemap::Span,
356 indented: usize) -> io::Result<()> {
357 self.bclose_maybe_open(span, indented, true)
359 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
360 indented: usize, close_box: bool) -> io::Result<()> {
361 try!(self.maybe_print_comment(span.hi));
362 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
363 try!(word(&mut self.s, "}"));
365 try!(self.end()); // close the outer-box
369 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
370 self.bclose_(span, indent_unit)
373 pub fn in_cbox(&self) -> bool {
374 match self.boxes.last() {
375 Some(&last_box) => last_box == pp::Breaks::Consistent,
379 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
380 if !self.is_bol() { try!(space(&mut self.s)); }
383 pub fn break_offset_if_not_bol(&mut self, n: usize,
384 off: isize) -> io::Result<()> {
386 break_offset(&mut self.s, n, off)
388 if off != 0 && self.s.last_token().is_hardbreak_tok() {
389 // We do something pretty sketchy here: tuck the nonzero
390 // offset-adjustment we were going to deposit along with the
391 // break into the previous hardbreak.
392 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
398 // Synthesizes a comment that was not textually present in the original source
400 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
401 try!(word(&mut self.s, "/*"));
402 try!(space(&mut self.s));
403 try!(word(&mut self.s, &text[..]));
404 try!(space(&mut self.s));
405 word(&mut self.s, "*/")
409 pub fn commasep_cmnt<T, F, G>(&mut self,
413 mut get_span: G) -> io::Result<()> where
414 F: FnMut(&mut State, &T) -> io::Result<()>,
415 G: FnMut(&T) -> codemap::Span,
417 try!(self.rbox(0, b));
418 let len = elts.len();
421 try!(self.maybe_print_comment(get_span(elt).hi));
425 try!(word(&mut self.s, ","));
426 try!(self.maybe_print_trailing_comment(get_span(elt),
427 Some(get_span(&elts[i]).hi)));
428 try!(self.space_if_not_bol());
434 pub fn commasep_exprs(&mut self, b: Breaks,
435 exprs: &[P<hir::Expr>]) -> io::Result<()> {
436 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
439 pub fn print_mod(&mut self, _mod: &hir::Mod,
440 attrs: &[ast::Attribute]) -> io::Result<()> {
441 try!(self.print_inner_attributes(attrs));
442 for item in &_mod.items {
443 try!(self.print_item(&**item));
448 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod,
449 attrs: &[ast::Attribute]) -> io::Result<()> {
450 try!(self.print_inner_attributes(attrs));
451 for item in &nmod.items {
452 try!(self.print_foreign_item(&**item));
457 pub fn print_opt_lifetime(&mut self,
458 lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
459 if let Some(l) = *lifetime {
460 try!(self.print_lifetime(&l));
466 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
467 try!(self.maybe_print_comment(ty.span.lo));
470 hir::TyVec(ref ty) => {
471 try!(word(&mut self.s, "["));
472 try!(self.print_type(&**ty));
473 try!(word(&mut self.s, "]"));
475 hir::TyPtr(ref mt) => {
476 try!(word(&mut self.s, "*"));
478 hir::MutMutable => try!(self.word_nbsp("mut")),
479 hir::MutImmutable => try!(self.word_nbsp("const")),
481 try!(self.print_type(&*mt.ty));
483 hir::TyRptr(ref lifetime, ref mt) => {
484 try!(word(&mut self.s, "&"));
485 try!(self.print_opt_lifetime(lifetime));
486 try!(self.print_mt(mt));
488 hir::TyTup(ref elts) => {
490 try!(self.commasep(Inconsistent, &elts[..],
491 |s, ty| s.print_type(&**ty)));
493 try!(word(&mut self.s, ","));
497 hir::TyParen(ref typ) => {
499 try!(self.print_type(&**typ));
502 hir::TyBareFn(ref f) => {
503 let generics = hir::Generics {
504 lifetimes: f.lifetimes.clone(),
505 ty_params: OwnedSlice::empty(),
506 where_clause: hir::WhereClause {
507 id: ast::DUMMY_NODE_ID,
508 predicates: Vec::new(),
511 try!(self.print_ty_fn(f.abi,
518 hir::TyPath(None, ref path) => {
519 try!(self.print_path(path, false, 0));
521 hir::TyPath(Some(ref qself), ref path) => {
522 try!(self.print_qpath(path, qself, false))
524 hir::TyObjectSum(ref ty, ref bounds) => {
525 try!(self.print_type(&**ty));
526 try!(self.print_bounds("+", &bounds[..]));
528 hir::TyPolyTraitRef(ref bounds) => {
529 try!(self.print_bounds("", &bounds[..]));
531 hir::TyFixedLengthVec(ref ty, ref v) => {
532 try!(word(&mut self.s, "["));
533 try!(self.print_type(&**ty));
534 try!(word(&mut self.s, "; "));
535 try!(self.print_expr(&**v));
536 try!(word(&mut self.s, "]"));
538 hir::TyTypeof(ref e) => {
539 try!(word(&mut self.s, "typeof("));
540 try!(self.print_expr(&**e));
541 try!(word(&mut self.s, ")"));
544 try!(word(&mut self.s, "_"));
550 pub fn print_foreign_item(&mut self,
551 item: &hir::ForeignItem) -> io::Result<()> {
552 try!(self.hardbreak_if_not_bol());
553 try!(self.maybe_print_comment(item.span.lo));
554 try!(self.print_outer_attributes(&item.attrs));
556 hir::ForeignItemFn(ref decl, ref generics) => {
558 try!(self.print_fn(decl, hir::Unsafety::Normal,
559 hir::Constness::NotConst,
560 abi::Rust, Some(item.ident),
561 generics, None, item.vis));
562 try!(self.end()); // end head-ibox
563 try!(word(&mut self.s, ";"));
564 self.end() // end the outer fn box
566 hir::ForeignItemStatic(ref t, m) => {
567 try!(self.head(&visibility_qualified(item.vis,
570 try!(self.word_space("mut"));
572 try!(self.print_ident(item.ident));
573 try!(self.word_space(":"));
574 try!(self.print_type(&**t));
575 try!(word(&mut self.s, ";"));
576 try!(self.end()); // end the head-ibox
577 self.end() // end the outer cbox
582 fn print_associated_const(&mut self,
585 default: Option<&hir::Expr>,
586 vis: hir::Visibility)
589 try!(word(&mut self.s, &visibility_qualified(vis, "")));
590 try!(self.word_space("const"));
591 try!(self.print_ident(ident));
592 try!(self.word_space(":"));
593 try!(self.print_type(ty));
594 if let Some(expr) = default {
595 try!(space(&mut self.s));
596 try!(self.word_space("="));
597 try!(self.print_expr(expr));
599 word(&mut self.s, ";")
602 fn print_associated_type(&mut self,
604 bounds: Option<&hir::TyParamBounds>,
605 ty: Option<&hir::Ty>)
607 try!(self.word_space("type"));
608 try!(self.print_ident(ident));
609 if let Some(bounds) = bounds {
610 try!(self.print_bounds(":", bounds));
612 if let Some(ty) = ty {
613 try!(space(&mut self.s));
614 try!(self.word_space("="));
615 try!(self.print_type(ty));
617 word(&mut self.s, ";")
620 /// Pretty-print an item
621 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
622 try!(self.hardbreak_if_not_bol());
623 try!(self.maybe_print_comment(item.span.lo));
624 try!(self.print_outer_attributes(&item.attrs));
625 try!(self.ann.pre(self, NodeItem(item)));
627 hir::ItemExternCrate(ref optional_path) => {
628 try!(self.head(&visibility_qualified(item.vis,
630 if let Some(p) = *optional_path {
631 let val = p.as_str();
632 if val.contains("-") {
633 try!(self.print_string(&val, ast::CookedStr));
635 try!(self.print_name(p));
637 try!(space(&mut self.s));
638 try!(word(&mut self.s, "as"));
639 try!(space(&mut self.s));
641 try!(self.print_ident(item.ident));
642 try!(word(&mut self.s, ";"));
643 try!(self.end()); // end inner head-block
644 try!(self.end()); // end outer head-block
646 hir::ItemUse(ref vp) => {
647 try!(self.head(&visibility_qualified(item.vis,
649 try!(self.print_view_path(&**vp));
650 try!(word(&mut self.s, ";"));
651 try!(self.end()); // end inner head-block
652 try!(self.end()); // end outer head-block
654 hir::ItemStatic(ref ty, m, ref expr) => {
655 try!(self.head(&visibility_qualified(item.vis,
657 if m == hir::MutMutable {
658 try!(self.word_space("mut"));
660 try!(self.print_ident(item.ident));
661 try!(self.word_space(":"));
662 try!(self.print_type(&**ty));
663 try!(space(&mut self.s));
664 try!(self.end()); // end the head-ibox
666 try!(self.word_space("="));
667 try!(self.print_expr(&**expr));
668 try!(word(&mut self.s, ";"));
669 try!(self.end()); // end the outer cbox
671 hir::ItemConst(ref ty, ref expr) => {
672 try!(self.head(&visibility_qualified(item.vis,
674 try!(self.print_ident(item.ident));
675 try!(self.word_space(":"));
676 try!(self.print_type(&**ty));
677 try!(space(&mut self.s));
678 try!(self.end()); // end the head-ibox
680 try!(self.word_space("="));
681 try!(self.print_expr(&**expr));
682 try!(word(&mut self.s, ";"));
683 try!(self.end()); // end the outer cbox
685 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
697 try!(word(&mut self.s, " "));
698 try!(self.print_block_with_attrs(&**body, &item.attrs));
700 hir::ItemMod(ref _mod) => {
701 try!(self.head(&visibility_qualified(item.vis,
703 try!(self.print_ident(item.ident));
706 try!(self.print_mod(_mod, &item.attrs));
707 try!(self.bclose(item.span));
709 hir::ItemForeignMod(ref nmod) => {
710 try!(self.head("extern"));
711 try!(self.word_nbsp(&nmod.abi.to_string()));
713 try!(self.print_foreign_mod(nmod, &item.attrs));
714 try!(self.bclose(item.span));
716 hir::ItemTy(ref ty, ref params) => {
717 try!(self.ibox(indent_unit));
719 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
720 try!(self.print_ident(item.ident));
721 try!(self.print_generics(params));
722 try!(self.end()); // end the inner ibox
724 try!(self.print_where_clause(¶ms.where_clause));
725 try!(space(&mut self.s));
726 try!(self.word_space("="));
727 try!(self.print_type(&**ty));
728 try!(word(&mut self.s, ";"));
729 try!(self.end()); // end the outer ibox
731 hir::ItemEnum(ref enum_definition, ref params) => {
732 try!(self.print_enum_def(
740 hir::ItemStruct(ref struct_def, ref generics) => {
741 try!(self.head(&visibility_qualified(item.vis,"struct")));
742 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
745 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
747 try!(self.print_visibility(item.vis));
748 try!(self.print_unsafety(unsafety));
749 try!(self.word_nbsp("impl"));
750 try!(self.print_trait_ref(trait_ref));
751 try!(space(&mut self.s));
752 try!(self.word_space("for"));
753 try!(self.word_space(".."));
755 try!(self.bclose(item.span));
757 hir::ItemImpl(unsafety,
764 try!(self.print_visibility(item.vis));
765 try!(self.print_unsafety(unsafety));
766 try!(self.word_nbsp("impl"));
768 if generics.is_parameterized() {
769 try!(self.print_generics(generics));
770 try!(space(&mut self.s));
774 hir::ImplPolarity::Negative => {
775 try!(word(&mut self.s, "!"));
782 try!(self.print_trait_ref(t));
783 try!(space(&mut self.s));
784 try!(self.word_space("for"));
789 try!(self.print_type(&**ty));
790 try!(self.print_where_clause(&generics.where_clause));
792 try!(space(&mut self.s));
794 try!(self.print_inner_attributes(&item.attrs));
795 for impl_item in impl_items {
796 try!(self.print_impl_item(impl_item));
798 try!(self.bclose(item.span));
800 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
802 try!(self.print_visibility(item.vis));
803 try!(self.print_unsafety(unsafety));
804 try!(self.word_nbsp("trait"));
805 try!(self.print_ident(item.ident));
806 try!(self.print_generics(generics));
807 let mut real_bounds = Vec::with_capacity(bounds.len());
808 for b in bounds.iter() {
809 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
810 try!(space(&mut self.s));
811 try!(self.word_space("for ?"));
812 try!(self.print_trait_ref(&ptr.trait_ref));
814 real_bounds.push(b.clone());
817 try!(self.print_bounds(":", &real_bounds[..]));
818 try!(self.print_where_clause(&generics.where_clause));
819 try!(word(&mut self.s, " "));
821 for trait_item in trait_items {
822 try!(self.print_trait_item(trait_item));
824 try!(self.bclose(item.span));
827 self.ann.post(self, NodeItem(item))
830 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
831 self.print_path(&t.path, false, 0)
834 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
835 if !lifetimes.is_empty() {
836 try!(word(&mut self.s, "for<"));
837 let mut comma = false;
838 for lifetime_def in lifetimes {
840 try!(self.word_space(","))
842 try!(self.print_lifetime_def(lifetime_def));
845 try!(word(&mut self.s, ">"));
850 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
851 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
852 self.print_trait_ref(&t.trait_ref)
855 pub fn print_enum_def(&mut self, enum_definition: &hir::EnumDef,
856 generics: &hir::Generics, ident: ast::Ident,
858 visibility: hir::Visibility) -> io::Result<()> {
859 try!(self.head(&visibility_qualified(visibility, "enum")));
860 try!(self.print_ident(ident));
861 try!(self.print_generics(generics));
862 try!(self.print_where_clause(&generics.where_clause));
863 try!(space(&mut self.s));
864 self.print_variants(&enum_definition.variants, span)
867 pub fn print_variants(&mut self,
868 variants: &[P<hir::Variant>],
869 span: codemap::Span) -> io::Result<()> {
872 try!(self.space_if_not_bol());
873 try!(self.maybe_print_comment(v.span.lo));
874 try!(self.print_outer_attributes(&v.node.attrs));
875 try!(self.ibox(indent_unit));
876 try!(self.print_variant(&**v));
877 try!(word(&mut self.s, ","));
879 try!(self.maybe_print_trailing_comment(v.span, None));
884 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
886 hir::Public => self.word_nbsp("pub"),
887 hir::Inherited => Ok(())
891 pub fn print_struct(&mut self,
892 struct_def: &hir::StructDef,
893 generics: &hir::Generics,
895 span: codemap::Span) -> io::Result<()> {
896 try!(self.print_ident(ident));
897 try!(self.print_generics(generics));
898 if ::util::struct_def_is_tuple_like(struct_def) {
899 if !struct_def.fields.is_empty() {
902 Inconsistent, &struct_def.fields,
904 match field.node.kind {
905 hir::NamedField(..) => panic!("unexpected named field"),
906 hir::UnnamedField(vis) => {
907 try!(s.print_visibility(vis));
908 try!(s.maybe_print_comment(field.span.lo));
909 s.print_type(&*field.node.ty)
916 try!(self.print_where_clause(&generics.where_clause));
917 try!(word(&mut self.s, ";"));
919 self.end() // close the outer-box
921 try!(self.print_where_clause(&generics.where_clause));
924 try!(self.hardbreak_if_not_bol());
926 for field in &struct_def.fields {
927 match field.node.kind {
928 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
929 hir::NamedField(ident, visibility) => {
930 try!(self.hardbreak_if_not_bol());
931 try!(self.maybe_print_comment(field.span.lo));
932 try!(self.print_outer_attributes(&field.node.attrs));
933 try!(self.print_visibility(visibility));
934 try!(self.print_ident(ident));
935 try!(self.word_nbsp(":"));
936 try!(self.print_type(&*field.node.ty));
937 try!(word(&mut self.s, ","));
946 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
947 try!(self.print_visibility(v.node.vis));
949 hir::TupleVariantKind(ref args) => {
950 try!(self.print_ident(v.node.name));
951 if !args.is_empty() {
953 try!(self.commasep(Consistent,
955 |s, arg| s.print_type(&*arg.ty)));
959 hir::StructVariantKind(ref struct_def) => {
961 let generics = ::util::empty_generics();
962 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
965 match v.node.disr_expr {
967 try!(space(&mut self.s));
968 try!(self.word_space("="));
969 self.print_expr(&**d)
975 pub fn print_method_sig(&mut self,
978 vis: hir::Visibility)
980 self.print_fn(&m.decl,
986 Some(&m.explicit_self.node),
990 pub fn print_trait_item(&mut self, ti: &hir::TraitItem)
992 try!(self.ann.pre(self, NodeSubItem(ti.id)));
993 try!(self.hardbreak_if_not_bol());
994 try!(self.maybe_print_comment(ti.span.lo));
995 try!(self.print_outer_attributes(&ti.attrs));
997 hir::ConstTraitItem(ref ty, ref default) => {
998 try!(self.print_associated_const(ti.ident, &ty,
999 default.as_ref().map(|expr| &**expr),
1002 hir::MethodTraitItem(ref sig, ref body) => {
1004 try!(self.head(""));
1006 try!(self.print_method_sig(ti.ident, sig, hir::Inherited));
1007 if let Some(ref body) = *body {
1009 try!(self.print_block_with_attrs(body, &ti.attrs));
1011 try!(word(&mut self.s, ";"));
1014 hir::TypeTraitItem(ref bounds, ref default) => {
1015 try!(self.print_associated_type(ti.ident, Some(bounds),
1016 default.as_ref().map(|ty| &**ty)));
1019 self.ann.post(self, NodeSubItem(ti.id))
1022 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1023 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1024 try!(self.hardbreak_if_not_bol());
1025 try!(self.maybe_print_comment(ii.span.lo));
1026 try!(self.print_outer_attributes(&ii.attrs));
1028 hir::ConstImplItem(ref ty, ref expr) => {
1029 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1031 hir::MethodImplItem(ref sig, ref body) => {
1032 try!(self.head(""));
1033 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1035 try!(self.print_block_with_attrs(body, &ii.attrs));
1037 hir::TypeImplItem(ref ty) => {
1038 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1041 self.ann.post(self, NodeSubItem(ii.id))
1044 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1045 try!(self.maybe_print_comment(st.span.lo));
1047 hir::StmtDecl(ref decl, _) => {
1048 try!(self.print_decl(&**decl));
1050 hir::StmtExpr(ref expr, _) => {
1051 try!(self.space_if_not_bol());
1052 try!(self.print_expr(&**expr));
1054 hir::StmtSemi(ref expr, _) => {
1055 try!(self.space_if_not_bol());
1056 try!(self.print_expr(&**expr));
1057 try!(word(&mut self.s, ";"));
1060 if stmt_ends_with_semi(&st.node) {
1061 try!(word(&mut self.s, ";"));
1063 self.maybe_print_trailing_comment(st.span, None)
1066 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1067 self.print_block_with_attrs(blk, &[])
1070 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1071 self.print_block_unclosed_indent(blk, indent_unit)
1074 pub fn print_block_unclosed_indent(&mut self, blk: &hir::Block,
1075 indented: usize) -> io::Result<()> {
1076 self.print_block_maybe_unclosed(blk, indented, &[], false)
1079 pub fn print_block_with_attrs(&mut self,
1081 attrs: &[ast::Attribute]) -> io::Result<()> {
1082 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1085 pub fn print_block_maybe_unclosed(&mut self,
1088 attrs: &[ast::Attribute],
1089 close_box: bool) -> io::Result<()> {
1091 hir::UnsafeBlock(..) | hir::PushUnsafeBlock(..) => try!(self.word_space("unsafe")),
1092 hir::DefaultBlock | hir::PopUnsafeBlock(..) => ()
1094 try!(self.maybe_print_comment(blk.span.lo));
1095 try!(self.ann.pre(self, NodeBlock(blk)));
1098 try!(self.print_inner_attributes(attrs));
1100 for st in &blk.stmts {
1101 try!(self.print_stmt(&**st));
1105 try!(self.space_if_not_bol());
1106 try!(self.print_expr(&**expr));
1107 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1111 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1112 self.ann.post(self, NodeBlock(blk))
1115 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1119 // "another else-if"
1120 hir::ExprIf(ref i, ref then, ref e) => {
1121 try!(self.cbox(indent_unit - 1));
1123 try!(word(&mut self.s, " else if "));
1124 try!(self.print_expr(&**i));
1125 try!(space(&mut self.s));
1126 try!(self.print_block(&**then));
1127 self.print_else(e.as_ref().map(|e| &**e))
1130 hir::ExprBlock(ref b) => {
1131 try!(self.cbox(indent_unit - 1));
1133 try!(word(&mut self.s, " else "));
1134 self.print_block(&**b)
1136 // BLEAH, constraints would be great here
1138 panic!("print_if saw if with weird alternative");
1146 pub fn print_if(&mut self, test: &hir::Expr, blk: &hir::Block,
1147 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1148 try!(self.head("if"));
1149 try!(self.print_expr(test));
1150 try!(space(&mut self.s));
1151 try!(self.print_block(blk));
1152 self.print_else(elseopt)
1155 pub fn print_if_let(&mut self, pat: &hir::Pat, expr: &hir::Expr, blk: &hir::Block,
1156 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1157 try!(self.head("if let"));
1158 try!(self.print_pat(pat));
1159 try!(space(&mut self.s));
1160 try!(self.word_space("="));
1161 try!(self.print_expr(expr));
1162 try!(space(&mut self.s));
1163 try!(self.print_block(blk));
1164 self.print_else(elseopt)
1168 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1170 try!(self.commasep_exprs(Inconsistent, args));
1174 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1175 let needs_par = needs_parentheses(expr);
1179 try!(self.print_expr(expr));
1181 try!(self.pclose());
1186 fn print_expr_box(&mut self,
1187 place: &Option<P<hir::Expr>>,
1188 expr: &hir::Expr) -> io::Result<()> {
1189 try!(word(&mut self.s, "box"));
1190 try!(word(&mut self.s, "("));
1191 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1192 try!(self.word_space(")"));
1193 self.print_expr(expr)
1196 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1197 try!(self.ibox(indent_unit));
1198 try!(word(&mut self.s, "["));
1199 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1200 try!(word(&mut self.s, "]"));
1204 fn print_expr_repeat(&mut self,
1205 element: &hir::Expr,
1206 count: &hir::Expr) -> io::Result<()> {
1207 try!(self.ibox(indent_unit));
1208 try!(word(&mut self.s, "["));
1209 try!(self.print_expr(element));
1210 try!(self.word_space(";"));
1211 try!(self.print_expr(count));
1212 try!(word(&mut self.s, "]"));
1216 fn print_expr_struct(&mut self,
1218 fields: &[hir::Field],
1219 wth: &Option<P<hir::Expr>>) -> io::Result<()> {
1220 try!(self.print_path(path, true, 0));
1221 if !(fields.is_empty() && wth.is_none()) {
1222 try!(word(&mut self.s, "{"));
1223 try!(self.commasep_cmnt(
1227 try!(s.ibox(indent_unit));
1228 try!(s.print_ident(field.ident.node));
1229 try!(s.word_space(":"));
1230 try!(s.print_expr(&*field.expr));
1236 try!(self.ibox(indent_unit));
1237 if !fields.is_empty() {
1238 try!(word(&mut self.s, ","));
1239 try!(space(&mut self.s));
1241 try!(word(&mut self.s, ".."));
1242 try!(self.print_expr(&**expr));
1245 _ => try!(word(&mut self.s, ",")),
1247 try!(word(&mut self.s, "}"));
1252 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1254 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1255 if exprs.len() == 1 {
1256 try!(word(&mut self.s, ","));
1261 fn print_expr_call(&mut self,
1263 args: &[P<hir::Expr>]) -> io::Result<()> {
1264 try!(self.print_expr_maybe_paren(func));
1265 self.print_call_post(args)
1268 fn print_expr_method_call(&mut self,
1269 ident: hir::SpannedIdent,
1271 args: &[P<hir::Expr>]) -> io::Result<()> {
1272 let base_args = &args[1..];
1273 try!(self.print_expr(&*args[0]));
1274 try!(word(&mut self.s, "."));
1275 try!(self.print_ident(ident.node));
1276 if !tys.is_empty() {
1277 try!(word(&mut self.s, "::<"));
1278 try!(self.commasep(Inconsistent, tys,
1279 |s, ty| s.print_type(&**ty)));
1280 try!(word(&mut self.s, ">"));
1282 self.print_call_post(base_args)
1285 fn print_expr_binary(&mut self,
1288 rhs: &hir::Expr) -> io::Result<()> {
1289 try!(self.print_expr(lhs));
1290 try!(space(&mut self.s));
1291 try!(self.word_space(::util::binop_to_string(op.node)));
1292 self.print_expr(rhs)
1295 fn print_expr_unary(&mut self,
1297 expr: &hir::Expr) -> io::Result<()> {
1298 try!(word(&mut self.s, ::util::unop_to_string(op)));
1299 self.print_expr_maybe_paren(expr)
1302 fn print_expr_addr_of(&mut self,
1303 mutability: hir::Mutability,
1304 expr: &hir::Expr) -> io::Result<()> {
1305 try!(word(&mut self.s, "&"));
1306 try!(self.print_mutability(mutability));
1307 self.print_expr_maybe_paren(expr)
1310 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1311 try!(self.maybe_print_comment(expr.span.lo));
1312 try!(self.ibox(indent_unit));
1313 try!(self.ann.pre(self, NodeExpr(expr)));
1315 hir::ExprBox(ref place, ref expr) => {
1316 try!(self.print_expr_box(place, &**expr));
1318 hir::ExprVec(ref exprs) => {
1319 try!(self.print_expr_vec(&exprs[..]));
1321 hir::ExprRepeat(ref element, ref count) => {
1322 try!(self.print_expr_repeat(&**element, &**count));
1324 hir::ExprStruct(ref path, ref fields, ref wth) => {
1325 try!(self.print_expr_struct(path, &fields[..], wth));
1327 hir::ExprTup(ref exprs) => {
1328 try!(self.print_expr_tup(&exprs[..]));
1330 hir::ExprCall(ref func, ref args) => {
1331 try!(self.print_expr_call(&**func, &args[..]));
1333 hir::ExprMethodCall(ident, ref tys, ref args) => {
1334 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1336 hir::ExprBinary(op, ref lhs, ref rhs) => {
1337 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1339 hir::ExprUnary(op, ref expr) => {
1340 try!(self.print_expr_unary(op, &**expr));
1342 hir::ExprAddrOf(m, ref expr) => {
1343 try!(self.print_expr_addr_of(m, &**expr));
1345 hir::ExprLit(ref lit) => {
1346 try!(self.print_literal(&**lit));
1348 hir::ExprCast(ref expr, ref ty) => {
1349 try!(self.print_expr(&**expr));
1350 try!(space(&mut self.s));
1351 try!(self.word_space("as"));
1352 try!(self.print_type(&**ty));
1354 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1355 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1357 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1358 if let Some(ident) = opt_ident {
1359 try!(self.print_ident(ident));
1360 try!(self.word_space(":"));
1362 try!(self.head("while"));
1363 try!(self.print_expr(&**test));
1364 try!(space(&mut self.s));
1365 try!(self.print_block(&**blk));
1367 hir::ExprLoop(ref blk, opt_ident) => {
1368 if let Some(ident) = opt_ident {
1369 try!(self.print_ident(ident));
1370 try!(self.word_space(":"));
1372 try!(self.head("loop"));
1373 try!(space(&mut self.s));
1374 try!(self.print_block(&**blk));
1376 hir::ExprMatch(ref expr, ref arms, _) => {
1377 try!(self.cbox(indent_unit));
1379 try!(self.word_nbsp("match"));
1380 try!(self.print_expr(&**expr));
1381 try!(space(&mut self.s));
1384 try!(self.print_arm(arm));
1386 try!(self.bclose_(expr.span, indent_unit));
1388 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1389 try!(self.print_capture_clause(capture_clause));
1391 try!(self.print_fn_block_args(&**decl));
1392 try!(space(&mut self.s));
1394 let default_return = match decl.output {
1395 hir::DefaultReturn(..) => true,
1399 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1400 try!(self.print_block_unclosed(&**body));
1402 // we extract the block, so as not to create another set of boxes
1403 match body.expr.as_ref().unwrap().node {
1404 hir::ExprBlock(ref blk) => {
1405 try!(self.print_block_unclosed(&**blk));
1408 // this is a bare expression
1409 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1410 try!(self.end()); // need to close a box
1414 // a box will be closed by print_expr, but we didn't want an overall
1415 // wrapper so we closed the corresponding opening. so create an
1416 // empty box to satisfy the close.
1419 hir::ExprBlock(ref blk) => {
1420 // containing cbox, will be closed by print-block at }
1421 try!(self.cbox(indent_unit));
1422 // head-box, will be closed by print-block after {
1424 try!(self.print_block(&**blk));
1426 hir::ExprAssign(ref lhs, ref rhs) => {
1427 try!(self.print_expr(&**lhs));
1428 try!(space(&mut self.s));
1429 try!(self.word_space("="));
1430 try!(self.print_expr(&**rhs));
1432 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1433 try!(self.print_expr(&**lhs));
1434 try!(space(&mut self.s));
1435 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1436 try!(self.word_space("="));
1437 try!(self.print_expr(&**rhs));
1439 hir::ExprField(ref expr, id) => {
1440 try!(self.print_expr(&**expr));
1441 try!(word(&mut self.s, "."));
1442 try!(self.print_ident(id.node));
1444 hir::ExprTupField(ref expr, id) => {
1445 try!(self.print_expr(&**expr));
1446 try!(word(&mut self.s, "."));
1447 try!(self.print_usize(id.node));
1449 hir::ExprIndex(ref expr, ref index) => {
1450 try!(self.print_expr(&**expr));
1451 try!(word(&mut self.s, "["));
1452 try!(self.print_expr(&**index));
1453 try!(word(&mut self.s, "]"));
1455 hir::ExprRange(ref start, ref end) => {
1456 if let &Some(ref e) = start {
1457 try!(self.print_expr(&**e));
1459 try!(word(&mut self.s, ".."));
1460 if let &Some(ref e) = end {
1461 try!(self.print_expr(&**e));
1464 hir::ExprPath(None, ref path) => {
1465 try!(self.print_path(path, true, 0))
1467 hir::ExprPath(Some(ref qself), ref path) => {
1468 try!(self.print_qpath(path, qself, true))
1470 hir::ExprBreak(opt_ident) => {
1471 try!(word(&mut self.s, "break"));
1472 try!(space(&mut self.s));
1473 if let Some(ident) = opt_ident {
1474 try!(self.print_ident(ident.node));
1475 try!(space(&mut self.s));
1478 hir::ExprAgain(opt_ident) => {
1479 try!(word(&mut self.s, "continue"));
1480 try!(space(&mut self.s));
1481 if let Some(ident) = opt_ident {
1482 try!(self.print_ident(ident.node));
1483 try!(space(&mut self.s))
1486 hir::ExprRet(ref result) => {
1487 try!(word(&mut self.s, "return"));
1490 try!(word(&mut self.s, " "));
1491 try!(self.print_expr(&**expr));
1496 hir::ExprInlineAsm(ref a) => {
1497 try!(word(&mut self.s, "asm!"));
1499 try!(self.print_string(&a.asm, a.asm_str_style));
1500 try!(self.word_space(":"));
1502 try!(self.commasep(Inconsistent, &a.outputs,
1503 |s, &(ref co, ref o, is_rw)| {
1504 match co.slice_shift_char() {
1505 Some(('=', operand)) if is_rw => {
1506 try!(s.print_string(&format!("+{}", operand),
1509 _ => try!(s.print_string(&co, ast::CookedStr))
1512 try!(s.print_expr(&**o));
1516 try!(space(&mut self.s));
1517 try!(self.word_space(":"));
1519 try!(self.commasep(Inconsistent, &a.inputs,
1520 |s, &(ref co, ref o)| {
1521 try!(s.print_string(&co, ast::CookedStr));
1523 try!(s.print_expr(&**o));
1527 try!(space(&mut self.s));
1528 try!(self.word_space(":"));
1530 try!(self.commasep(Inconsistent, &a.clobbers,
1532 try!(s.print_string(&co, ast::CookedStr));
1536 let mut options = vec!();
1538 options.push("volatile");
1541 options.push("alignstack");
1543 if a.dialect == hir::AsmDialect::AsmIntel {
1544 options.push("intel");
1547 if !options.is_empty() {
1548 try!(space(&mut self.s));
1549 try!(self.word_space(":"));
1550 try!(self.commasep(Inconsistent, &*options,
1552 try!(s.print_string(co, ast::CookedStr));
1557 try!(self.pclose());
1559 hir::ExprParen(ref e) => {
1561 try!(self.print_expr(&**e));
1562 try!(self.pclose());
1565 try!(self.ann.post(self, NodeExpr(expr)));
1569 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1570 try!(self.print_pat(&*loc.pat));
1571 if let Some(ref ty) = loc.ty {
1572 try!(self.word_space(":"));
1573 try!(self.print_type(&**ty));
1578 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1579 try!(self.maybe_print_comment(decl.span.lo));
1581 hir::DeclLocal(ref loc) => {
1582 try!(self.space_if_not_bol());
1583 try!(self.ibox(indent_unit));
1584 try!(self.word_nbsp("let"));
1586 try!(self.ibox(indent_unit));
1587 try!(self.print_local_decl(&**loc));
1589 if let Some(ref init) = loc.init {
1591 try!(self.word_space("="));
1592 try!(self.print_expr(&**init));
1596 hir::DeclItem(ref item) => self.print_item(&**item)
1600 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1601 try!(word(&mut self.s, &ident.name.as_str()));
1602 self.ann.post(self, NodeIdent(&ident))
1605 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1606 word(&mut self.s, &i.to_string())
1609 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1610 try!(word(&mut self.s, &name.as_str()));
1611 self.ann.post(self, NodeName(&name))
1614 pub fn print_for_decl(&mut self, loc: &hir::Local,
1615 coll: &hir::Expr) -> io::Result<()> {
1616 try!(self.print_local_decl(loc));
1617 try!(space(&mut self.s));
1618 try!(self.word_space("in"));
1619 self.print_expr(coll)
1622 fn print_path(&mut self,
1624 colons_before_params: bool,
1628 try!(self.maybe_print_comment(path.span.lo));
1630 let mut first = !path.global;
1631 for segment in &path.segments[..path.segments.len()-depth] {
1635 try!(word(&mut self.s, "::"))
1638 try!(self.print_ident(segment.identifier));
1640 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1646 fn print_qpath(&mut self,
1649 colons_before_params: bool)
1652 try!(word(&mut self.s, "<"));
1653 try!(self.print_type(&qself.ty));
1654 if qself.position > 0 {
1655 try!(space(&mut self.s));
1656 try!(self.word_space("as"));
1657 let depth = path.segments.len() - qself.position;
1658 try!(self.print_path(&path, false, depth));
1660 try!(word(&mut self.s, ">"));
1661 try!(word(&mut self.s, "::"));
1662 let item_segment = path.segments.last().unwrap();
1663 try!(self.print_ident(item_segment.identifier));
1664 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1667 fn print_path_parameters(&mut self,
1668 parameters: &hir::PathParameters,
1669 colons_before_params: bool)
1672 if parameters.is_empty() {
1676 if colons_before_params {
1677 try!(word(&mut self.s, "::"))
1681 hir::AngleBracketedParameters(ref data) => {
1682 try!(word(&mut self.s, "<"));
1684 let mut comma = false;
1685 for lifetime in &data.lifetimes {
1687 try!(self.word_space(","))
1689 try!(self.print_lifetime(lifetime));
1693 if !data.types.is_empty() {
1695 try!(self.word_space(","))
1700 |s, ty| s.print_type(&**ty)));
1704 for binding in data.bindings.iter() {
1706 try!(self.word_space(","))
1708 try!(self.print_ident(binding.ident));
1709 try!(space(&mut self.s));
1710 try!(self.word_space("="));
1711 try!(self.print_type(&*binding.ty));
1715 try!(word(&mut self.s, ">"))
1718 hir::ParenthesizedParameters(ref data) => {
1719 try!(word(&mut self.s, "("));
1723 |s, ty| s.print_type(&**ty)));
1724 try!(word(&mut self.s, ")"));
1729 try!(self.space_if_not_bol());
1730 try!(self.word_space("->"));
1731 try!(self.print_type(&**ty));
1740 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1741 try!(self.maybe_print_comment(pat.span.lo));
1742 try!(self.ann.pre(self, NodePat(pat)));
1743 /* Pat isn't normalized, but the beauty of it
1744 is that it doesn't matter */
1746 hir::PatWild(hir::PatWildSingle) => try!(word(&mut self.s, "_")),
1747 hir::PatWild(hir::PatWildMulti) => try!(word(&mut self.s, "..")),
1748 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1749 match binding_mode {
1750 hir::BindByRef(mutbl) => {
1751 try!(self.word_nbsp("ref"));
1752 try!(self.print_mutability(mutbl));
1754 hir::BindByValue(hir::MutImmutable) => {}
1755 hir::BindByValue(hir::MutMutable) => {
1756 try!(self.word_nbsp("mut"));
1759 try!(self.print_ident(path1.node));
1762 try!(word(&mut self.s, "@"));
1763 try!(self.print_pat(&**p));
1768 hir::PatEnum(ref path, ref args_) => {
1769 try!(self.print_path(path, true, 0));
1771 None => try!(word(&mut self.s, "(..)")),
1773 if !args.is_empty() {
1775 try!(self.commasep(Inconsistent, &args[..],
1776 |s, p| s.print_pat(&**p)));
1777 try!(self.pclose());
1782 hir::PatQPath(ref qself, ref path) => {
1783 try!(self.print_qpath(path, qself, false));
1785 hir::PatStruct(ref path, ref fields, etc) => {
1786 try!(self.print_path(path, true, 0));
1788 try!(self.word_space("{"));
1789 try!(self.commasep_cmnt(
1790 Consistent, &fields[..],
1792 try!(s.cbox(indent_unit));
1793 if !f.node.is_shorthand {
1794 try!(s.print_ident(f.node.ident));
1795 try!(s.word_nbsp(":"));
1797 try!(s.print_pat(&*f.node.pat));
1800 |f| f.node.pat.span));
1802 if !fields.is_empty() { try!(self.word_space(",")); }
1803 try!(word(&mut self.s, ".."));
1805 try!(space(&mut self.s));
1806 try!(word(&mut self.s, "}"));
1808 hir::PatTup(ref elts) => {
1810 try!(self.commasep(Inconsistent,
1812 |s, p| s.print_pat(&**p)));
1813 if elts.len() == 1 {
1814 try!(word(&mut self.s, ","));
1816 try!(self.pclose());
1818 hir::PatBox(ref inner) => {
1819 try!(word(&mut self.s, "box "));
1820 try!(self.print_pat(&**inner));
1822 hir::PatRegion(ref inner, mutbl) => {
1823 try!(word(&mut self.s, "&"));
1824 if mutbl == hir::MutMutable {
1825 try!(word(&mut self.s, "mut "));
1827 try!(self.print_pat(&**inner));
1829 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1830 hir::PatRange(ref begin, ref end) => {
1831 try!(self.print_expr(&**begin));
1832 try!(space(&mut self.s));
1833 try!(word(&mut self.s, "..."));
1834 try!(self.print_expr(&**end));
1836 hir::PatVec(ref before, ref slice, ref after) => {
1837 try!(word(&mut self.s, "["));
1838 try!(self.commasep(Inconsistent,
1840 |s, p| s.print_pat(&**p)));
1841 if let Some(ref p) = *slice {
1842 if !before.is_empty() { try!(self.word_space(",")); }
1843 try!(self.print_pat(&**p));
1845 hir::Pat { node: hir::PatWild(hir::PatWildMulti), .. } => {
1846 // this case is handled by print_pat
1848 _ => try!(word(&mut self.s, "..")),
1850 if !after.is_empty() { try!(self.word_space(",")); }
1852 try!(self.commasep(Inconsistent,
1854 |s, p| s.print_pat(&**p)));
1855 try!(word(&mut self.s, "]"));
1858 self.ann.post(self, NodePat(pat))
1861 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1862 // I have no idea why this check is necessary, but here it
1864 if arm.attrs.is_empty() {
1865 try!(space(&mut self.s));
1867 try!(self.cbox(indent_unit));
1869 try!(self.print_outer_attributes(&arm.attrs));
1870 let mut first = true;
1871 for p in &arm.pats {
1875 try!(space(&mut self.s));
1876 try!(self.word_space("|"));
1878 try!(self.print_pat(&**p));
1880 try!(space(&mut self.s));
1881 if let Some(ref e) = arm.guard {
1882 try!(self.word_space("if"));
1883 try!(self.print_expr(&**e));
1884 try!(space(&mut self.s));
1886 try!(self.word_space("=>"));
1888 match arm.body.node {
1889 hir::ExprBlock(ref blk) => {
1890 // the block will close the pattern's ibox
1891 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1893 // If it is a user-provided unsafe block, print a comma after it
1894 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1895 try!(word(&mut self.s, ","));
1899 try!(self.end()); // close the ibox for the pattern
1900 try!(self.print_expr(&*arm.body));
1901 try!(word(&mut self.s, ","));
1904 self.end() // close enclosing cbox
1907 // Returns whether it printed anything
1908 fn print_explicit_self(&mut self,
1909 explicit_self: &hir::ExplicitSelf_,
1910 mutbl: hir::Mutability) -> io::Result<bool> {
1911 try!(self.print_mutability(mutbl));
1912 match *explicit_self {
1913 hir::SelfStatic => { return Ok(false); }
1914 hir::SelfValue(_) => {
1915 try!(word(&mut self.s, "self"));
1917 hir::SelfRegion(ref lt, m, _) => {
1918 try!(word(&mut self.s, "&"));
1919 try!(self.print_opt_lifetime(lt));
1920 try!(self.print_mutability(m));
1921 try!(word(&mut self.s, "self"));
1923 hir::SelfExplicit(ref typ, _) => {
1924 try!(word(&mut self.s, "self"));
1925 try!(self.word_space(":"));
1926 try!(self.print_type(&**typ));
1932 pub fn print_fn(&mut self,
1934 unsafety: hir::Unsafety,
1935 constness: hir::Constness,
1937 name: Option<ast::Ident>,
1938 generics: &hir::Generics,
1939 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1940 vis: hir::Visibility) -> io::Result<()> {
1941 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1943 if let Some(name) = name {
1945 try!(self.print_ident(name));
1947 try!(self.print_generics(generics));
1948 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1949 self.print_where_clause(&generics.where_clause)
1952 pub fn print_fn_args(&mut self, decl: &hir::FnDecl,
1953 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1955 // It is unfortunate to duplicate the commasep logic, but we want the
1956 // self type and the args all in the same box.
1957 try!(self.rbox(0, Inconsistent));
1958 let mut first = true;
1959 if let Some(explicit_self) = opt_explicit_self {
1960 let m = match explicit_self {
1961 &hir::SelfStatic => hir::MutImmutable,
1962 _ => match decl.inputs[0].pat.node {
1963 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1964 _ => hir::MutImmutable
1967 first = !try!(self.print_explicit_self(explicit_self, m));
1970 // HACK(eddyb) ignore the separately printed self argument.
1971 let args = if first {
1978 if first { first = false; } else { try!(self.word_space(",")); }
1979 try!(self.print_arg(arg));
1985 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl,
1986 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1989 try!(self.print_fn_args(decl, opt_explicit_self));
1991 try!(word(&mut self.s, ", ..."));
1993 try!(self.pclose());
1995 self.print_fn_output(decl)
1998 pub fn print_fn_block_args(
2002 try!(word(&mut self.s, "|"));
2003 try!(self.print_fn_args(decl, None));
2004 try!(word(&mut self.s, "|"));
2006 if let hir::DefaultReturn(..) = decl.output {
2010 try!(self.space_if_not_bol());
2011 try!(self.word_space("->"));
2013 hir::Return(ref ty) => {
2014 try!(self.print_type(&**ty));
2015 self.maybe_print_comment(ty.span.lo)
2017 hir::DefaultReturn(..) => unreachable!(),
2018 hir::NoReturn(span) => {
2019 try!(self.word_nbsp("!"));
2020 self.maybe_print_comment(span.lo)
2025 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause)
2027 match capture_clause {
2028 hir::CaptureByValue => self.word_space("move"),
2029 hir::CaptureByRef => Ok(()),
2033 pub fn print_bounds(&mut self,
2035 bounds: &[hir::TyParamBound])
2037 if !bounds.is_empty() {
2038 try!(word(&mut self.s, prefix));
2039 let mut first = true;
2040 for bound in bounds {
2045 try!(self.word_space("+"));
2049 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2050 self.print_poly_trait_ref(tref)
2052 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2053 try!(word(&mut self.s, "?"));
2054 self.print_poly_trait_ref(tref)
2056 RegionTyParamBound(ref lt) => {
2057 self.print_lifetime(lt)
2067 pub fn print_lifetime(&mut self,
2068 lifetime: &hir::Lifetime)
2071 self.print_name(lifetime.name)
2074 pub fn print_lifetime_def(&mut self,
2075 lifetime: &hir::LifetimeDef)
2078 try!(self.print_lifetime(&lifetime.lifetime));
2080 for v in &lifetime.bounds {
2081 try!(word(&mut self.s, sep));
2082 try!(self.print_lifetime(v));
2088 pub fn print_generics(&mut self,
2089 generics: &hir::Generics)
2092 let total = generics.lifetimes.len() + generics.ty_params.len();
2097 try!(word(&mut self.s, "<"));
2099 let mut ints = Vec::new();
2104 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2105 if idx < generics.lifetimes.len() {
2106 let lifetime = &generics.lifetimes[idx];
2107 s.print_lifetime_def(lifetime)
2109 let idx = idx - generics.lifetimes.len();
2110 let param = &generics.ty_params[idx];
2111 s.print_ty_param(param)
2115 try!(word(&mut self.s, ">"));
2119 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2120 try!(self.print_ident(param.ident));
2121 try!(self.print_bounds(":", ¶m.bounds));
2122 match param.default {
2123 Some(ref default) => {
2124 try!(space(&mut self.s));
2125 try!(self.word_space("="));
2126 self.print_type(&**default)
2132 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause)
2134 if where_clause.predicates.is_empty() {
2138 try!(space(&mut self.s));
2139 try!(self.word_space("where"));
2141 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2143 try!(self.word_space(","));
2147 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2151 try!(self.print_formal_lifetime_list(bound_lifetimes));
2152 try!(self.print_type(&**bounded_ty));
2153 try!(self.print_bounds(":", bounds));
2155 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2158 try!(self.print_lifetime(lifetime));
2159 try!(word(&mut self.s, ":"));
2161 for (i, bound) in bounds.iter().enumerate() {
2162 try!(self.print_lifetime(bound));
2165 try!(word(&mut self.s, ":"));
2169 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2170 try!(self.print_path(path, false, 0));
2171 try!(space(&mut self.s));
2172 try!(self.word_space("="));
2173 try!(self.print_type(&**ty));
2181 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2183 hir::ViewPathSimple(ident, ref path) => {
2184 try!(self.print_path(path, false, 0));
2186 // FIXME(#6993) can't compare identifiers directly here
2187 if path.segments.last().unwrap().identifier.name !=
2189 try!(space(&mut self.s));
2190 try!(self.word_space("as"));
2191 try!(self.print_ident(ident));
2197 hir::ViewPathGlob(ref path) => {
2198 try!(self.print_path(path, false, 0));
2199 word(&mut self.s, "::*")
2202 hir::ViewPathList(ref path, ref idents) => {
2203 if path.segments.is_empty() {
2204 try!(word(&mut self.s, "{"));
2206 try!(self.print_path(path, false, 0));
2207 try!(word(&mut self.s, "::{"));
2209 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2211 hir::PathListIdent { name, .. } => {
2214 hir::PathListMod { .. } => {
2215 word(&mut s.s, "self")
2219 word(&mut self.s, "}")
2224 pub fn print_mutability(&mut self,
2225 mutbl: hir::Mutability) -> io::Result<()> {
2227 hir::MutMutable => self.word_nbsp("mut"),
2228 hir::MutImmutable => Ok(()),
2232 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2233 try!(self.print_mutability(mt.mutbl));
2234 self.print_type(&*mt.ty)
2237 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2238 try!(self.ibox(indent_unit));
2239 match input.ty.node {
2240 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2242 match input.pat.node {
2243 hir::PatIdent(_, ref path1, _) if
2245 parse::token::special_idents::invalid.name => {
2249 try!(self.print_pat(&*input.pat));
2250 try!(word(&mut self.s, ":"));
2251 try!(space(&mut self.s));
2254 try!(self.print_type(&*input.ty));
2260 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2261 if let hir::DefaultReturn(..) = decl.output {
2265 try!(self.space_if_not_bol());
2266 try!(self.ibox(indent_unit));
2267 try!(self.word_space("->"));
2270 try!(self.word_nbsp("!")),
2271 hir::DefaultReturn(..) => unreachable!(),
2272 hir::Return(ref ty) =>
2273 try!(self.print_type(&**ty))
2278 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2283 pub fn print_ty_fn(&mut self,
2285 unsafety: hir::Unsafety,
2287 name: Option<ast::Ident>,
2288 generics: &hir::Generics,
2289 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2291 try!(self.ibox(indent_unit));
2292 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2293 try!(word(&mut self.s, "for"));
2294 try!(self.print_generics(generics));
2296 let generics = hir::Generics {
2297 lifetimes: Vec::new(),
2298 ty_params: OwnedSlice::empty(),
2299 where_clause: hir::WhereClause {
2300 id: ast::DUMMY_NODE_ID,
2301 predicates: Vec::new(),
2304 try!(self.print_fn(decl,
2306 hir::Constness::NotConst,
2315 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2316 next_pos: Option<BytePos>)
2318 let cm = match self.cm {
2322 match self.next_comment() {
2324 if (*cmnt).style != comments::Trailing { return Ok(()) }
2325 let span_line = cm.lookup_char_pos(span.hi);
2326 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2327 let mut next = (*cmnt).pos + BytePos(1);
2328 match next_pos { None => (), Some(p) => next = p }
2329 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2330 span_line.line == comment_line.line {
2331 try!(self.print_comment(cmnt));
2332 self.cur_cmnt_and_lit.cur_cmnt += 1;
2340 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2341 // If there aren't any remaining comments, then we need to manually
2342 // make sure there is a line break at the end.
2343 if self.next_comment().is_none() {
2344 try!(hardbreak(&mut self.s));
2347 match self.next_comment() {
2349 try!(self.print_comment(cmnt));
2350 self.cur_cmnt_and_lit.cur_cmnt += 1;
2358 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2359 opt_abi: Option<abi::Abi>)
2362 Some(abi::Rust) => Ok(()),
2364 try!(self.word_nbsp("extern"));
2365 self.word_nbsp(&abi.to_string())
2371 pub fn print_extern_opt_abi(&mut self,
2372 opt_abi: Option<abi::Abi>) -> io::Result<()> {
2375 try!(self.word_nbsp("extern"));
2376 self.word_nbsp(&abi.to_string())
2382 pub fn print_fn_header_info(&mut self,
2383 unsafety: hir::Unsafety,
2384 constness: hir::Constness,
2386 vis: hir::Visibility) -> io::Result<()> {
2387 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2388 try!(self.print_unsafety(unsafety));
2391 hir::Constness::NotConst => {}
2392 hir::Constness::Const => try!(self.word_nbsp("const"))
2395 if abi != abi::Rust {
2396 try!(self.word_nbsp("extern"));
2397 try!(self.word_nbsp(&abi.to_string()));
2400 word(&mut self.s, "fn")
2403 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2405 hir::Unsafety::Normal => Ok(()),
2406 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2411 // Dup'ed from parse::classify, but adapted for the HIR.
2412 /// Does this expression require a semicolon to be treated
2413 /// as a statement? The negation of this: 'can this expression
2414 /// be used as a statement without a semicolon' -- is used
2415 /// as an early-bail-out in the parser so that, for instance,
2416 /// if true {...} else {...}
2418 /// isn't parsed as (if true {...} else {...} | x) | 5
2419 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2422 | hir::ExprMatch(..)
2424 | hir::ExprWhile(..)
2425 | hir::ExprLoop(..) => false,
2430 /// this statement requires a semicolon after it.
2431 /// note that in one case (stmt_semi), we've already
2432 /// seen the semicolon, and thus don't need another.
2433 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2435 hir::StmtDecl(ref d, _) => {
2437 hir::DeclLocal(_) => true,
2438 hir::DeclItem(_) => false
2441 hir::StmtExpr(ref e, _) => { expr_requires_semi_to_be_stmt(&**e) }
2442 hir::StmtSemi(..) => { false }