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, Spanned};
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.name),
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_name(item.name));
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_name(name));
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_name(name));
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_name(item.name));
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_name(item.name));
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_name(item.name));
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_name(item.name));
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_name(item.name));
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.name, 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_name(item.name));
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, name: ast::Name,
858 visibility: hir::Visibility) -> io::Result<()> {
859 try!(self.head(&visibility_qualified(visibility, "enum")));
860 try!(self.print_name(name));
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_name(name));
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<()> {
948 hir::TupleVariantKind(ref args) => {
949 try!(self.print_ident(v.node.name));
950 if !args.is_empty() {
952 try!(self.commasep(Consistent,
954 |s, arg| s.print_type(&*arg.ty)));
958 hir::StructVariantKind(ref struct_def) => {
960 let generics = ::util::empty_generics();
961 try!(self.print_struct(&**struct_def, &generics, v.node.name.name, v.span));
964 match v.node.disr_expr {
966 try!(space(&mut self.s));
967 try!(self.word_space("="));
968 self.print_expr(&**d)
974 pub fn print_method_sig(&mut self,
977 vis: hir::Visibility)
979 self.print_fn(&m.decl,
985 Some(&m.explicit_self.node),
989 pub fn print_trait_item(&mut self, ti: &hir::TraitItem)
991 try!(self.ann.pre(self, NodeSubItem(ti.id)));
992 try!(self.hardbreak_if_not_bol());
993 try!(self.maybe_print_comment(ti.span.lo));
994 try!(self.print_outer_attributes(&ti.attrs));
996 hir::ConstTraitItem(ref ty, ref default) => {
997 try!(self.print_associated_const(ti.name, &ty,
998 default.as_ref().map(|expr| &**expr),
1001 hir::MethodTraitItem(ref sig, ref body) => {
1003 try!(self.head(""));
1005 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
1006 if let Some(ref body) = *body {
1008 try!(self.print_block_with_attrs(body, &ti.attrs));
1010 try!(word(&mut self.s, ";"));
1013 hir::TypeTraitItem(ref bounds, ref default) => {
1014 try!(self.print_associated_type(ti.name, Some(bounds),
1015 default.as_ref().map(|ty| &**ty)));
1018 self.ann.post(self, NodeSubItem(ti.id))
1021 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1022 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1023 try!(self.hardbreak_if_not_bol());
1024 try!(self.maybe_print_comment(ii.span.lo));
1025 try!(self.print_outer_attributes(&ii.attrs));
1027 hir::ConstImplItem(ref ty, ref expr) => {
1028 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1030 hir::MethodImplItem(ref sig, ref body) => {
1031 try!(self.head(""));
1032 try!(self.print_method_sig(ii.name, sig, ii.vis));
1034 try!(self.print_block_with_attrs(body, &ii.attrs));
1036 hir::TypeImplItem(ref ty) => {
1037 try!(self.print_associated_type(ii.name, None, Some(ty)));
1040 self.ann.post(self, NodeSubItem(ii.id))
1043 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1044 try!(self.maybe_print_comment(st.span.lo));
1046 hir::StmtDecl(ref decl, _) => {
1047 try!(self.print_decl(&**decl));
1049 hir::StmtExpr(ref expr, _) => {
1050 try!(self.space_if_not_bol());
1051 try!(self.print_expr(&**expr));
1053 hir::StmtSemi(ref expr, _) => {
1054 try!(self.space_if_not_bol());
1055 try!(self.print_expr(&**expr));
1056 try!(word(&mut self.s, ";"));
1059 if stmt_ends_with_semi(&st.node) {
1060 try!(word(&mut self.s, ";"));
1062 self.maybe_print_trailing_comment(st.span, None)
1065 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1066 self.print_block_with_attrs(blk, &[])
1069 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1070 self.print_block_unclosed_indent(blk, indent_unit)
1073 pub fn print_block_unclosed_indent(&mut self, blk: &hir::Block,
1074 indented: usize) -> io::Result<()> {
1075 self.print_block_maybe_unclosed(blk, indented, &[], false)
1078 pub fn print_block_with_attrs(&mut self,
1080 attrs: &[ast::Attribute]) -> io::Result<()> {
1081 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1084 pub fn print_block_maybe_unclosed(&mut self,
1087 attrs: &[ast::Attribute],
1088 close_box: bool) -> io::Result<()> {
1090 hir::UnsafeBlock(..) | hir::PushUnsafeBlock(..) => try!(self.word_space("unsafe")),
1091 hir::DefaultBlock | hir::PopUnsafeBlock(..) => ()
1093 try!(self.maybe_print_comment(blk.span.lo));
1094 try!(self.ann.pre(self, NodeBlock(blk)));
1097 try!(self.print_inner_attributes(attrs));
1099 for st in &blk.stmts {
1100 try!(self.print_stmt(&**st));
1104 try!(self.space_if_not_bol());
1105 try!(self.print_expr(&**expr));
1106 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1110 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1111 self.ann.post(self, NodeBlock(blk))
1114 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1118 // "another else-if"
1119 hir::ExprIf(ref i, ref then, ref e) => {
1120 try!(self.cbox(indent_unit - 1));
1122 try!(word(&mut self.s, " else if "));
1123 try!(self.print_expr(&**i));
1124 try!(space(&mut self.s));
1125 try!(self.print_block(&**then));
1126 self.print_else(e.as_ref().map(|e| &**e))
1129 hir::ExprBlock(ref b) => {
1130 try!(self.cbox(indent_unit - 1));
1132 try!(word(&mut self.s, " else "));
1133 self.print_block(&**b)
1135 // BLEAH, constraints would be great here
1137 panic!("print_if saw if with weird alternative");
1145 pub fn print_if(&mut self, test: &hir::Expr, blk: &hir::Block,
1146 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1147 try!(self.head("if"));
1148 try!(self.print_expr(test));
1149 try!(space(&mut self.s));
1150 try!(self.print_block(blk));
1151 self.print_else(elseopt)
1154 pub fn print_if_let(&mut self, pat: &hir::Pat, expr: &hir::Expr, blk: &hir::Block,
1155 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1156 try!(self.head("if let"));
1157 try!(self.print_pat(pat));
1158 try!(space(&mut self.s));
1159 try!(self.word_space("="));
1160 try!(self.print_expr(expr));
1161 try!(space(&mut self.s));
1162 try!(self.print_block(blk));
1163 self.print_else(elseopt)
1167 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1169 try!(self.commasep_exprs(Inconsistent, args));
1173 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1174 let needs_par = needs_parentheses(expr);
1178 try!(self.print_expr(expr));
1180 try!(self.pclose());
1185 fn print_expr_box(&mut self,
1186 place: &Option<P<hir::Expr>>,
1187 expr: &hir::Expr) -> io::Result<()> {
1188 try!(word(&mut self.s, "box"));
1189 try!(word(&mut self.s, "("));
1190 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1191 try!(self.word_space(")"));
1192 self.print_expr(expr)
1195 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1196 try!(self.ibox(indent_unit));
1197 try!(word(&mut self.s, "["));
1198 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1199 try!(word(&mut self.s, "]"));
1203 fn print_expr_repeat(&mut self,
1204 element: &hir::Expr,
1205 count: &hir::Expr) -> io::Result<()> {
1206 try!(self.ibox(indent_unit));
1207 try!(word(&mut self.s, "["));
1208 try!(self.print_expr(element));
1209 try!(self.word_space(";"));
1210 try!(self.print_expr(count));
1211 try!(word(&mut self.s, "]"));
1215 fn print_expr_struct(&mut self,
1217 fields: &[hir::Field],
1218 wth: &Option<P<hir::Expr>>) -> io::Result<()> {
1219 try!(self.print_path(path, true, 0));
1220 try!(word(&mut self.s, "{"));
1221 try!(self.commasep_cmnt(
1225 try!(s.ibox(indent_unit));
1226 try!(s.print_name(field.name.node));
1227 try!(s.word_space(":"));
1228 try!(s.print_expr(&*field.expr));
1234 try!(self.ibox(indent_unit));
1235 if !fields.is_empty() {
1236 try!(word(&mut self.s, ","));
1237 try!(space(&mut self.s));
1239 try!(word(&mut self.s, ".."));
1240 try!(self.print_expr(&**expr));
1243 _ => if !fields.is_empty() {
1244 try!(word(&mut self.s, ","))
1247 try!(word(&mut self.s, "}"));
1251 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1253 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1254 if exprs.len() == 1 {
1255 try!(word(&mut self.s, ","));
1260 fn print_expr_call(&mut self,
1262 args: &[P<hir::Expr>]) -> io::Result<()> {
1263 try!(self.print_expr_maybe_paren(func));
1264 self.print_call_post(args)
1267 fn print_expr_method_call(&mut self,
1268 name: Spanned<ast::Name>,
1270 args: &[P<hir::Expr>]) -> io::Result<()> {
1271 let base_args = &args[1..];
1272 try!(self.print_expr(&*args[0]));
1273 try!(word(&mut self.s, "."));
1274 try!(self.print_name(name.node));
1275 if !tys.is_empty() {
1276 try!(word(&mut self.s, "::<"));
1277 try!(self.commasep(Inconsistent, tys,
1278 |s, ty| s.print_type(&**ty)));
1279 try!(word(&mut self.s, ">"));
1281 self.print_call_post(base_args)
1284 fn print_expr_binary(&mut self,
1287 rhs: &hir::Expr) -> io::Result<()> {
1288 try!(self.print_expr(lhs));
1289 try!(space(&mut self.s));
1290 try!(self.word_space(::util::binop_to_string(op.node)));
1291 self.print_expr(rhs)
1294 fn print_expr_unary(&mut self,
1296 expr: &hir::Expr) -> io::Result<()> {
1297 try!(word(&mut self.s, ::util::unop_to_string(op)));
1298 self.print_expr_maybe_paren(expr)
1301 fn print_expr_addr_of(&mut self,
1302 mutability: hir::Mutability,
1303 expr: &hir::Expr) -> io::Result<()> {
1304 try!(word(&mut self.s, "&"));
1305 try!(self.print_mutability(mutability));
1306 self.print_expr_maybe_paren(expr)
1309 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1310 try!(self.maybe_print_comment(expr.span.lo));
1311 try!(self.ibox(indent_unit));
1312 try!(self.ann.pre(self, NodeExpr(expr)));
1314 hir::ExprBox(ref place, ref expr) => {
1315 try!(self.print_expr_box(place, &**expr));
1317 hir::ExprVec(ref exprs) => {
1318 try!(self.print_expr_vec(&exprs[..]));
1320 hir::ExprRepeat(ref element, ref count) => {
1321 try!(self.print_expr_repeat(&**element, &**count));
1323 hir::ExprStruct(ref path, ref fields, ref wth) => {
1324 try!(self.print_expr_struct(path, &fields[..], wth));
1326 hir::ExprTup(ref exprs) => {
1327 try!(self.print_expr_tup(&exprs[..]));
1329 hir::ExprCall(ref func, ref args) => {
1330 try!(self.print_expr_call(&**func, &args[..]));
1332 hir::ExprMethodCall(name, ref tys, ref args) => {
1333 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1335 hir::ExprBinary(op, ref lhs, ref rhs) => {
1336 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1338 hir::ExprUnary(op, ref expr) => {
1339 try!(self.print_expr_unary(op, &**expr));
1341 hir::ExprAddrOf(m, ref expr) => {
1342 try!(self.print_expr_addr_of(m, &**expr));
1344 hir::ExprLit(ref lit) => {
1345 try!(self.print_literal(&**lit));
1347 hir::ExprCast(ref expr, ref ty) => {
1348 try!(self.print_expr(&**expr));
1349 try!(space(&mut self.s));
1350 try!(self.word_space("as"));
1351 try!(self.print_type(&**ty));
1353 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1354 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1356 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1357 if let Some(ident) = opt_ident {
1358 try!(self.print_ident(ident));
1359 try!(self.word_space(":"));
1361 try!(self.head("while"));
1362 try!(self.print_expr(&**test));
1363 try!(space(&mut self.s));
1364 try!(self.print_block(&**blk));
1366 hir::ExprLoop(ref blk, opt_ident) => {
1367 if let Some(ident) = opt_ident {
1368 try!(self.print_ident(ident));
1369 try!(self.word_space(":"));
1371 try!(self.head("loop"));
1372 try!(space(&mut self.s));
1373 try!(self.print_block(&**blk));
1375 hir::ExprMatch(ref expr, ref arms, _) => {
1376 try!(self.cbox(indent_unit));
1378 try!(self.word_nbsp("match"));
1379 try!(self.print_expr(&**expr));
1380 try!(space(&mut self.s));
1383 try!(self.print_arm(arm));
1385 try!(self.bclose_(expr.span, indent_unit));
1387 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1388 try!(self.print_capture_clause(capture_clause));
1390 try!(self.print_fn_block_args(&**decl));
1391 try!(space(&mut self.s));
1393 let default_return = match decl.output {
1394 hir::DefaultReturn(..) => true,
1398 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1399 try!(self.print_block_unclosed(&**body));
1401 // we extract the block, so as not to create another set of boxes
1402 match body.expr.as_ref().unwrap().node {
1403 hir::ExprBlock(ref blk) => {
1404 try!(self.print_block_unclosed(&**blk));
1407 // this is a bare expression
1408 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1409 try!(self.end()); // need to close a box
1413 // a box will be closed by print_expr, but we didn't want an overall
1414 // wrapper so we closed the corresponding opening. so create an
1415 // empty box to satisfy the close.
1418 hir::ExprBlock(ref blk) => {
1419 // containing cbox, will be closed by print-block at }
1420 try!(self.cbox(indent_unit));
1421 // head-box, will be closed by print-block after {
1423 try!(self.print_block(&**blk));
1425 hir::ExprAssign(ref lhs, ref rhs) => {
1426 try!(self.print_expr(&**lhs));
1427 try!(space(&mut self.s));
1428 try!(self.word_space("="));
1429 try!(self.print_expr(&**rhs));
1431 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1432 try!(self.print_expr(&**lhs));
1433 try!(space(&mut self.s));
1434 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1435 try!(self.word_space("="));
1436 try!(self.print_expr(&**rhs));
1438 hir::ExprField(ref expr, name) => {
1439 try!(self.print_expr(&**expr));
1440 try!(word(&mut self.s, "."));
1441 try!(self.print_name(name.node));
1443 hir::ExprTupField(ref expr, id) => {
1444 try!(self.print_expr(&**expr));
1445 try!(word(&mut self.s, "."));
1446 try!(self.print_usize(id.node));
1448 hir::ExprIndex(ref expr, ref index) => {
1449 try!(self.print_expr(&**expr));
1450 try!(word(&mut self.s, "["));
1451 try!(self.print_expr(&**index));
1452 try!(word(&mut self.s, "]"));
1454 hir::ExprRange(ref start, ref end) => {
1455 if let &Some(ref e) = start {
1456 try!(self.print_expr(&**e));
1458 try!(word(&mut self.s, ".."));
1459 if let &Some(ref e) = end {
1460 try!(self.print_expr(&**e));
1463 hir::ExprPath(None, ref path) => {
1464 try!(self.print_path(path, true, 0))
1466 hir::ExprPath(Some(ref qself), ref path) => {
1467 try!(self.print_qpath(path, qself, true))
1469 hir::ExprBreak(opt_ident) => {
1470 try!(word(&mut self.s, "break"));
1471 try!(space(&mut self.s));
1472 if let Some(ident) = opt_ident {
1473 try!(self.print_ident(ident.node));
1474 try!(space(&mut self.s));
1477 hir::ExprAgain(opt_ident) => {
1478 try!(word(&mut self.s, "continue"));
1479 try!(space(&mut self.s));
1480 if let Some(ident) = opt_ident {
1481 try!(self.print_ident(ident.node));
1482 try!(space(&mut self.s))
1485 hir::ExprRet(ref result) => {
1486 try!(word(&mut self.s, "return"));
1489 try!(word(&mut self.s, " "));
1490 try!(self.print_expr(&**expr));
1495 hir::ExprInlineAsm(ref a) => {
1496 try!(word(&mut self.s, "asm!"));
1498 try!(self.print_string(&a.asm, a.asm_str_style));
1499 try!(self.word_space(":"));
1501 try!(self.commasep(Inconsistent, &a.outputs,
1502 |s, &(ref co, ref o, is_rw)| {
1503 match co.slice_shift_char() {
1504 Some(('=', operand)) if is_rw => {
1505 try!(s.print_string(&format!("+{}", operand),
1508 _ => try!(s.print_string(&co, ast::CookedStr))
1511 try!(s.print_expr(&**o));
1515 try!(space(&mut self.s));
1516 try!(self.word_space(":"));
1518 try!(self.commasep(Inconsistent, &a.inputs,
1519 |s, &(ref co, ref o)| {
1520 try!(s.print_string(&co, ast::CookedStr));
1522 try!(s.print_expr(&**o));
1526 try!(space(&mut self.s));
1527 try!(self.word_space(":"));
1529 try!(self.commasep(Inconsistent, &a.clobbers,
1531 try!(s.print_string(&co, ast::CookedStr));
1535 let mut options = vec!();
1537 options.push("volatile");
1540 options.push("alignstack");
1542 if a.dialect == ast::AsmDialect::Intel {
1543 options.push("intel");
1546 if !options.is_empty() {
1547 try!(space(&mut self.s));
1548 try!(self.word_space(":"));
1549 try!(self.commasep(Inconsistent, &*options,
1551 try!(s.print_string(co, ast::CookedStr));
1556 try!(self.pclose());
1559 try!(self.ann.post(self, NodeExpr(expr)));
1563 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1564 try!(self.print_pat(&*loc.pat));
1565 if let Some(ref ty) = loc.ty {
1566 try!(self.word_space(":"));
1567 try!(self.print_type(&**ty));
1572 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1573 try!(self.maybe_print_comment(decl.span.lo));
1575 hir::DeclLocal(ref loc) => {
1576 try!(self.space_if_not_bol());
1577 try!(self.ibox(indent_unit));
1578 try!(self.word_nbsp("let"));
1580 try!(self.ibox(indent_unit));
1581 try!(self.print_local_decl(&**loc));
1583 if let Some(ref init) = loc.init {
1585 try!(self.word_space("="));
1586 try!(self.print_expr(&**init));
1590 hir::DeclItem(ref item) => self.print_item(&**item)
1594 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1595 try!(word(&mut self.s, &ident.name.as_str()));
1596 self.ann.post(self, NodeIdent(&ident))
1599 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1600 word(&mut self.s, &i.to_string())
1603 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1604 try!(word(&mut self.s, &name.as_str()));
1605 self.ann.post(self, NodeName(&name))
1608 pub fn print_for_decl(&mut self, loc: &hir::Local,
1609 coll: &hir::Expr) -> io::Result<()> {
1610 try!(self.print_local_decl(loc));
1611 try!(space(&mut self.s));
1612 try!(self.word_space("in"));
1613 self.print_expr(coll)
1616 fn print_path(&mut self,
1618 colons_before_params: bool,
1622 try!(self.maybe_print_comment(path.span.lo));
1624 let mut first = !path.global;
1625 for segment in &path.segments[..path.segments.len()-depth] {
1629 try!(word(&mut self.s, "::"))
1632 try!(self.print_ident(segment.identifier));
1634 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1640 fn print_qpath(&mut self,
1643 colons_before_params: bool)
1646 try!(word(&mut self.s, "<"));
1647 try!(self.print_type(&qself.ty));
1648 if qself.position > 0 {
1649 try!(space(&mut self.s));
1650 try!(self.word_space("as"));
1651 let depth = path.segments.len() - qself.position;
1652 try!(self.print_path(&path, false, depth));
1654 try!(word(&mut self.s, ">"));
1655 try!(word(&mut self.s, "::"));
1656 let item_segment = path.segments.last().unwrap();
1657 try!(self.print_ident(item_segment.identifier));
1658 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1661 fn print_path_parameters(&mut self,
1662 parameters: &hir::PathParameters,
1663 colons_before_params: bool)
1666 if parameters.is_empty() {
1670 if colons_before_params {
1671 try!(word(&mut self.s, "::"))
1675 hir::AngleBracketedParameters(ref data) => {
1676 try!(word(&mut self.s, "<"));
1678 let mut comma = false;
1679 for lifetime in &data.lifetimes {
1681 try!(self.word_space(","))
1683 try!(self.print_lifetime(lifetime));
1687 if !data.types.is_empty() {
1689 try!(self.word_space(","))
1694 |s, ty| s.print_type(&**ty)));
1698 for binding in data.bindings.iter() {
1700 try!(self.word_space(","))
1702 try!(self.print_ident(binding.ident));
1703 try!(space(&mut self.s));
1704 try!(self.word_space("="));
1705 try!(self.print_type(&*binding.ty));
1709 try!(word(&mut self.s, ">"))
1712 hir::ParenthesizedParameters(ref data) => {
1713 try!(word(&mut self.s, "("));
1717 |s, ty| s.print_type(&**ty)));
1718 try!(word(&mut self.s, ")"));
1723 try!(self.space_if_not_bol());
1724 try!(self.word_space("->"));
1725 try!(self.print_type(&**ty));
1734 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1735 try!(self.maybe_print_comment(pat.span.lo));
1736 try!(self.ann.pre(self, NodePat(pat)));
1737 /* Pat isn't normalized, but the beauty of it
1738 is that it doesn't matter */
1740 hir::PatWild(hir::PatWildSingle) => try!(word(&mut self.s, "_")),
1741 hir::PatWild(hir::PatWildMulti) => try!(word(&mut self.s, "..")),
1742 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1743 match binding_mode {
1744 hir::BindByRef(mutbl) => {
1745 try!(self.word_nbsp("ref"));
1746 try!(self.print_mutability(mutbl));
1748 hir::BindByValue(hir::MutImmutable) => {}
1749 hir::BindByValue(hir::MutMutable) => {
1750 try!(self.word_nbsp("mut"));
1753 try!(self.print_ident(path1.node));
1756 try!(word(&mut self.s, "@"));
1757 try!(self.print_pat(&**p));
1762 hir::PatEnum(ref path, ref args_) => {
1763 try!(self.print_path(path, true, 0));
1765 None => try!(word(&mut self.s, "(..)")),
1767 if !args.is_empty() {
1769 try!(self.commasep(Inconsistent, &args[..],
1770 |s, p| s.print_pat(&**p)));
1771 try!(self.pclose());
1776 hir::PatQPath(ref qself, ref path) => {
1777 try!(self.print_qpath(path, qself, false));
1779 hir::PatStruct(ref path, ref fields, etc) => {
1780 try!(self.print_path(path, true, 0));
1782 try!(self.word_space("{"));
1783 try!(self.commasep_cmnt(
1784 Consistent, &fields[..],
1786 try!(s.cbox(indent_unit));
1787 if !f.node.is_shorthand {
1788 try!(s.print_ident(f.node.ident));
1789 try!(s.word_nbsp(":"));
1791 try!(s.print_pat(&*f.node.pat));
1794 |f| f.node.pat.span));
1796 if !fields.is_empty() { try!(self.word_space(",")); }
1797 try!(word(&mut self.s, ".."));
1799 try!(space(&mut self.s));
1800 try!(word(&mut self.s, "}"));
1802 hir::PatTup(ref elts) => {
1804 try!(self.commasep(Inconsistent,
1806 |s, p| s.print_pat(&**p)));
1807 if elts.len() == 1 {
1808 try!(word(&mut self.s, ","));
1810 try!(self.pclose());
1812 hir::PatBox(ref inner) => {
1813 try!(word(&mut self.s, "box "));
1814 try!(self.print_pat(&**inner));
1816 hir::PatRegion(ref inner, mutbl) => {
1817 try!(word(&mut self.s, "&"));
1818 if mutbl == hir::MutMutable {
1819 try!(word(&mut self.s, "mut "));
1821 try!(self.print_pat(&**inner));
1823 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1824 hir::PatRange(ref begin, ref end) => {
1825 try!(self.print_expr(&**begin));
1826 try!(space(&mut self.s));
1827 try!(word(&mut self.s, "..."));
1828 try!(self.print_expr(&**end));
1830 hir::PatVec(ref before, ref slice, ref after) => {
1831 try!(word(&mut self.s, "["));
1832 try!(self.commasep(Inconsistent,
1834 |s, p| s.print_pat(&**p)));
1835 if let Some(ref p) = *slice {
1836 if !before.is_empty() { try!(self.word_space(",")); }
1837 try!(self.print_pat(&**p));
1839 hir::Pat { node: hir::PatWild(hir::PatWildMulti), .. } => {
1840 // this case is handled by print_pat
1842 _ => try!(word(&mut self.s, "..")),
1844 if !after.is_empty() { try!(self.word_space(",")); }
1846 try!(self.commasep(Inconsistent,
1848 |s, p| s.print_pat(&**p)));
1849 try!(word(&mut self.s, "]"));
1852 self.ann.post(self, NodePat(pat))
1855 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1856 // I have no idea why this check is necessary, but here it
1858 if arm.attrs.is_empty() {
1859 try!(space(&mut self.s));
1861 try!(self.cbox(indent_unit));
1863 try!(self.print_outer_attributes(&arm.attrs));
1864 let mut first = true;
1865 for p in &arm.pats {
1869 try!(space(&mut self.s));
1870 try!(self.word_space("|"));
1872 try!(self.print_pat(&**p));
1874 try!(space(&mut self.s));
1875 if let Some(ref e) = arm.guard {
1876 try!(self.word_space("if"));
1877 try!(self.print_expr(&**e));
1878 try!(space(&mut self.s));
1880 try!(self.word_space("=>"));
1882 match arm.body.node {
1883 hir::ExprBlock(ref blk) => {
1884 // the block will close the pattern's ibox
1885 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1887 // If it is a user-provided unsafe block, print a comma after it
1888 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1889 try!(word(&mut self.s, ","));
1893 try!(self.end()); // close the ibox for the pattern
1894 try!(self.print_expr(&*arm.body));
1895 try!(word(&mut self.s, ","));
1898 self.end() // close enclosing cbox
1901 // Returns whether it printed anything
1902 fn print_explicit_self(&mut self,
1903 explicit_self: &hir::ExplicitSelf_,
1904 mutbl: hir::Mutability) -> io::Result<bool> {
1905 try!(self.print_mutability(mutbl));
1906 match *explicit_self {
1907 hir::SelfStatic => { return Ok(false); }
1908 hir::SelfValue(_) => {
1909 try!(word(&mut self.s, "self"));
1911 hir::SelfRegion(ref lt, m, _) => {
1912 try!(word(&mut self.s, "&"));
1913 try!(self.print_opt_lifetime(lt));
1914 try!(self.print_mutability(m));
1915 try!(word(&mut self.s, "self"));
1917 hir::SelfExplicit(ref typ, _) => {
1918 try!(word(&mut self.s, "self"));
1919 try!(self.word_space(":"));
1920 try!(self.print_type(&**typ));
1926 pub fn print_fn(&mut self,
1928 unsafety: hir::Unsafety,
1929 constness: hir::Constness,
1931 name: Option<ast::Name>,
1932 generics: &hir::Generics,
1933 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1934 vis: hir::Visibility) -> io::Result<()> {
1935 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1937 if let Some(name) = name {
1939 try!(self.print_name(name));
1941 try!(self.print_generics(generics));
1942 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1943 self.print_where_clause(&generics.where_clause)
1946 pub fn print_fn_args(&mut self, decl: &hir::FnDecl,
1947 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1949 // It is unfortunate to duplicate the commasep logic, but we want the
1950 // self type and the args all in the same box.
1951 try!(self.rbox(0, Inconsistent));
1952 let mut first = true;
1953 if let Some(explicit_self) = opt_explicit_self {
1954 let m = match explicit_self {
1955 &hir::SelfStatic => hir::MutImmutable,
1956 _ => match decl.inputs[0].pat.node {
1957 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1958 _ => hir::MutImmutable
1961 first = !try!(self.print_explicit_self(explicit_self, m));
1964 // HACK(eddyb) ignore the separately printed self argument.
1965 let args = if first {
1972 if first { first = false; } else { try!(self.word_space(",")); }
1973 try!(self.print_arg(arg));
1979 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl,
1980 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1983 try!(self.print_fn_args(decl, opt_explicit_self));
1985 try!(word(&mut self.s, ", ..."));
1987 try!(self.pclose());
1989 self.print_fn_output(decl)
1992 pub fn print_fn_block_args(
1996 try!(word(&mut self.s, "|"));
1997 try!(self.print_fn_args(decl, None));
1998 try!(word(&mut self.s, "|"));
2000 if let hir::DefaultReturn(..) = decl.output {
2004 try!(self.space_if_not_bol());
2005 try!(self.word_space("->"));
2007 hir::Return(ref ty) => {
2008 try!(self.print_type(&**ty));
2009 self.maybe_print_comment(ty.span.lo)
2011 hir::DefaultReturn(..) => unreachable!(),
2012 hir::NoReturn(span) => {
2013 try!(self.word_nbsp("!"));
2014 self.maybe_print_comment(span.lo)
2019 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause)
2021 match capture_clause {
2022 hir::CaptureByValue => self.word_space("move"),
2023 hir::CaptureByRef => Ok(()),
2027 pub fn print_bounds(&mut self,
2029 bounds: &[hir::TyParamBound])
2031 if !bounds.is_empty() {
2032 try!(word(&mut self.s, prefix));
2033 let mut first = true;
2034 for bound in bounds {
2039 try!(self.word_space("+"));
2043 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2044 self.print_poly_trait_ref(tref)
2046 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2047 try!(word(&mut self.s, "?"));
2048 self.print_poly_trait_ref(tref)
2050 RegionTyParamBound(ref lt) => {
2051 self.print_lifetime(lt)
2061 pub fn print_lifetime(&mut self,
2062 lifetime: &hir::Lifetime)
2065 self.print_name(lifetime.name)
2068 pub fn print_lifetime_def(&mut self,
2069 lifetime: &hir::LifetimeDef)
2072 try!(self.print_lifetime(&lifetime.lifetime));
2074 for v in &lifetime.bounds {
2075 try!(word(&mut self.s, sep));
2076 try!(self.print_lifetime(v));
2082 pub fn print_generics(&mut self,
2083 generics: &hir::Generics)
2086 let total = generics.lifetimes.len() + generics.ty_params.len();
2091 try!(word(&mut self.s, "<"));
2093 let mut ints = Vec::new();
2098 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2099 if idx < generics.lifetimes.len() {
2100 let lifetime = &generics.lifetimes[idx];
2101 s.print_lifetime_def(lifetime)
2103 let idx = idx - generics.lifetimes.len();
2104 let param = &generics.ty_params[idx];
2105 s.print_ty_param(param)
2109 try!(word(&mut self.s, ">"));
2113 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2114 try!(self.print_ident(param.ident));
2115 try!(self.print_bounds(":", ¶m.bounds));
2116 match param.default {
2117 Some(ref default) => {
2118 try!(space(&mut self.s));
2119 try!(self.word_space("="));
2120 self.print_type(&**default)
2126 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause)
2128 if where_clause.predicates.is_empty() {
2132 try!(space(&mut self.s));
2133 try!(self.word_space("where"));
2135 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2137 try!(self.word_space(","));
2141 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2145 try!(self.print_formal_lifetime_list(bound_lifetimes));
2146 try!(self.print_type(&**bounded_ty));
2147 try!(self.print_bounds(":", bounds));
2149 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2152 try!(self.print_lifetime(lifetime));
2153 try!(word(&mut self.s, ":"));
2155 for (i, bound) in bounds.iter().enumerate() {
2156 try!(self.print_lifetime(bound));
2159 try!(word(&mut self.s, ":"));
2163 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2164 try!(self.print_path(path, false, 0));
2165 try!(space(&mut self.s));
2166 try!(self.word_space("="));
2167 try!(self.print_type(&**ty));
2175 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2177 hir::ViewPathSimple(name, ref path) => {
2178 try!(self.print_path(path, false, 0));
2180 // FIXME(#6993) can't compare identifiers directly here
2181 if path.segments.last().unwrap().identifier.name != name {
2182 try!(space(&mut self.s));
2183 try!(self.word_space("as"));
2184 try!(self.print_name(name));
2190 hir::ViewPathGlob(ref path) => {
2191 try!(self.print_path(path, false, 0));
2192 word(&mut self.s, "::*")
2195 hir::ViewPathList(ref path, ref idents) => {
2196 if path.segments.is_empty() {
2197 try!(word(&mut self.s, "{"));
2199 try!(self.print_path(path, false, 0));
2200 try!(word(&mut self.s, "::{"));
2202 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2204 hir::PathListIdent { name, .. } => {
2207 hir::PathListMod { .. } => {
2208 word(&mut s.s, "self")
2212 word(&mut self.s, "}")
2217 pub fn print_mutability(&mut self,
2218 mutbl: hir::Mutability) -> io::Result<()> {
2220 hir::MutMutable => self.word_nbsp("mut"),
2221 hir::MutImmutable => Ok(()),
2225 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2226 try!(self.print_mutability(mt.mutbl));
2227 self.print_type(&*mt.ty)
2230 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2231 try!(self.ibox(indent_unit));
2232 match input.ty.node {
2233 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2235 match input.pat.node {
2236 hir::PatIdent(_, ref path1, _) if
2238 parse::token::special_idents::invalid.name => {
2242 try!(self.print_pat(&*input.pat));
2243 try!(word(&mut self.s, ":"));
2244 try!(space(&mut self.s));
2247 try!(self.print_type(&*input.ty));
2253 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2254 if let hir::DefaultReturn(..) = decl.output {
2258 try!(self.space_if_not_bol());
2259 try!(self.ibox(indent_unit));
2260 try!(self.word_space("->"));
2263 try!(self.word_nbsp("!")),
2264 hir::DefaultReturn(..) => unreachable!(),
2265 hir::Return(ref ty) =>
2266 try!(self.print_type(&**ty))
2271 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2276 pub fn print_ty_fn(&mut self,
2278 unsafety: hir::Unsafety,
2280 name: Option<ast::Ident>,
2281 generics: &hir::Generics,
2282 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2284 try!(self.ibox(indent_unit));
2285 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2286 try!(word(&mut self.s, "for"));
2287 try!(self.print_generics(generics));
2289 let generics = hir::Generics {
2290 lifetimes: Vec::new(),
2291 ty_params: OwnedSlice::empty(),
2292 where_clause: hir::WhereClause {
2293 id: ast::DUMMY_NODE_ID,
2294 predicates: Vec::new(),
2297 try!(self.print_fn(decl,
2299 hir::Constness::NotConst,
2301 name.map(|x| x.name),
2308 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2309 next_pos: Option<BytePos>)
2311 let cm = match self.cm {
2315 match self.next_comment() {
2317 if (*cmnt).style != comments::Trailing { return Ok(()) }
2318 let span_line = cm.lookup_char_pos(span.hi);
2319 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2320 let mut next = (*cmnt).pos + BytePos(1);
2321 match next_pos { None => (), Some(p) => next = p }
2322 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2323 span_line.line == comment_line.line {
2324 try!(self.print_comment(cmnt));
2325 self.cur_cmnt_and_lit.cur_cmnt += 1;
2333 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2334 // If there aren't any remaining comments, then we need to manually
2335 // make sure there is a line break at the end.
2336 if self.next_comment().is_none() {
2337 try!(hardbreak(&mut self.s));
2340 match self.next_comment() {
2342 try!(self.print_comment(cmnt));
2343 self.cur_cmnt_and_lit.cur_cmnt += 1;
2351 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2352 opt_abi: Option<abi::Abi>)
2355 Some(abi::Rust) => Ok(()),
2357 try!(self.word_nbsp("extern"));
2358 self.word_nbsp(&abi.to_string())
2364 pub fn print_extern_opt_abi(&mut self,
2365 opt_abi: Option<abi::Abi>) -> io::Result<()> {
2368 try!(self.word_nbsp("extern"));
2369 self.word_nbsp(&abi.to_string())
2375 pub fn print_fn_header_info(&mut self,
2376 unsafety: hir::Unsafety,
2377 constness: hir::Constness,
2379 vis: hir::Visibility) -> io::Result<()> {
2380 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2381 try!(self.print_unsafety(unsafety));
2384 hir::Constness::NotConst => {}
2385 hir::Constness::Const => try!(self.word_nbsp("const"))
2388 if abi != abi::Rust {
2389 try!(self.word_nbsp("extern"));
2390 try!(self.word_nbsp(&abi.to_string()));
2393 word(&mut self.s, "fn")
2396 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2398 hir::Unsafety::Normal => Ok(()),
2399 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2404 // Dup'ed from parse::classify, but adapted for the HIR.
2405 /// Does this expression require a semicolon to be treated
2406 /// as a statement? The negation of this: 'can this expression
2407 /// be used as a statement without a semicolon' -- is used
2408 /// as an early-bail-out in the parser so that, for instance,
2409 /// if true {...} else {...}
2411 /// isn't parsed as (if true {...} else {...} | x) | 5
2412 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2415 | hir::ExprMatch(..)
2417 | hir::ExprWhile(..)
2418 | hir::ExprLoop(..) => false,
2423 /// this statement requires a semicolon after it.
2424 /// note that in one case (stmt_semi), we've already
2425 /// seen the semicolon, and thus don't need another.
2426 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2428 hir::StmtDecl(ref d, _) => {
2430 hir::DeclLocal(_) => true,
2431 hir::DeclItem(_) => false
2434 hir::StmtExpr(ref e, _) => { expr_requires_semi_to_be_stmt(&**e) }
2435 hir::StmtSemi(..) => { false }