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, zerobreak, hardbreak};
22 use syntax::print::pp::{Breaks, eof};
23 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
27 use hir::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
28 use attr::{AttrMetaMethods, AttributeMethods};
31 use std::io::{self, Write, Read};
34 pub enum AnnNode<'a> {
35 NodeIdent(&'a ast::Ident),
36 NodeName(&'a ast::Name),
37 NodeBlock(&'a hir::Block),
38 NodeItem(&'a hir::Item),
39 NodeSubItem(ast::NodeId),
40 NodeExpr(&'a hir::Expr),
41 NodePat(&'a hir::Pat),
45 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
46 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
49 #[derive(Copy, Clone)]
52 impl PpAnn for NoAnn {}
54 #[derive(Copy, Clone)]
55 pub struct CurrentCommentAndLiteral {
60 pub struct State<'a> {
61 pub s: pp::Printer<'a>,
62 cm: Option<&'a CodeMap>,
63 comments: Option<Vec<comments::Comment> >,
64 literals: Option<Vec<comments::Literal> >,
65 cur_cmnt_and_lit: CurrentCommentAndLiteral,
66 boxes: Vec<pp::Breaks>,
70 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
71 static NO_ANN: NoAnn = NoAnn;
72 rust_printer_annotated(writer, &NO_ANN)
75 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
76 ann: &'a PpAnn) -> State<'a> {
78 s: pp::mk_printer(writer, default_columns),
82 cur_cmnt_and_lit: CurrentCommentAndLiteral {
91 #[allow(non_upper_case_globals)]
92 pub const indent_unit: usize = 4;
94 #[allow(non_upper_case_globals)]
95 pub const default_columns: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
102 span_diagnostic: &diagnostic::SpanHandler,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm,
117 // When printing the AST, we sometimes need to inject `#[no_std]` here.
118 // Since you can't compile the HIR, it's not necessary.
120 try!(s.print_mod(&krate.module, &krate.attrs));
121 try!(s.print_remaining_comments());
126 pub fn new_from_input(cm: &'a CodeMap,
127 span_diagnostic: &diagnostic::SpanHandler,
132 is_expanded: bool) -> State<'a> {
133 let (cmnts, lits) = comments::gather_comments_and_literals(
143 // If the code is post expansion, don't use the table of
144 // literals, since it doesn't correspond with the literals
145 // in the AST anymore.
146 if is_expanded { None } else { Some(lits) })
149 pub fn new(cm: &'a CodeMap,
152 comments: Option<Vec<comments::Comment>>,
153 literals: Option<Vec<comments::Literal>>) -> State<'a> {
155 s: pp::mk_printer(out, default_columns),
159 cur_cmnt_and_lit: CurrentCommentAndLiteral {
169 pub fn to_string<F>(f: F) -> String where
170 F: FnOnce(&mut State) -> io::Result<()>,
172 let mut wr = Vec::new();
174 let mut printer = rust_printer(Box::new(&mut wr));
175 f(&mut printer).unwrap();
176 eof(&mut printer.s).unwrap();
178 String::from_utf8(wr).unwrap()
181 pub fn binop_to_string(op: BinOpToken) -> &'static str {
187 token::Percent => "%",
196 pub fn ty_to_string(ty: &hir::Ty) -> String {
197 to_string(|s| s.print_type(ty))
200 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
201 to_string(|s| s.print_bounds("", bounds))
204 pub fn pat_to_string(pat: &hir::Pat) -> String {
205 to_string(|s| s.print_pat(pat))
208 pub fn arm_to_string(arm: &hir::Arm) -> String {
209 to_string(|s| s.print_arm(arm))
212 pub fn expr_to_string(e: &hir::Expr) -> String {
213 to_string(|s| s.print_expr(e))
216 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
217 to_string(|s| s.print_lifetime(e))
220 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
221 to_string(|s| s.print_stmt(stmt))
224 pub fn attr_to_string(attr: &hir::Attribute) -> String {
225 to_string(|s| s.print_attribute(attr))
228 pub fn item_to_string(i: &hir::Item) -> String {
229 to_string(|s| s.print_item(i))
232 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
233 to_string(|s| s.print_impl_item(i))
236 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
237 to_string(|s| s.print_trait_item(i))
240 pub fn generics_to_string(generics: &hir::Generics) -> String {
241 to_string(|s| s.print_generics(generics))
244 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
245 to_string(|s| s.print_where_clause(i))
248 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
249 to_string(|s| s.print_fn_block_args(p))
252 pub fn path_to_string(p: &hir::Path) -> String {
253 to_string(|s| s.print_path(p, false, 0))
256 pub fn ident_to_string(id: &ast::Ident) -> String {
257 to_string(|s| s.print_ident(*id))
260 pub fn fun_to_string(decl: &hir::FnDecl,
261 unsafety: hir::Unsafety,
262 constness: hir::Constness,
264 opt_explicit_self: Option<&hir::ExplicitSelf_>,
265 generics: &hir::Generics)
269 try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
270 generics, opt_explicit_self, hir::Inherited));
271 try!(s.end()); // Close the head box
272 s.end() // Close the outer box
276 pub fn block_to_string(blk: &hir::Block) -> String {
278 // containing cbox, will be closed by print-block at }
279 try!(s.cbox(indent_unit));
280 // head-ibox, will be closed by print-block after {
286 pub fn meta_item_to_string(mi: &hir::MetaItem) -> String {
287 to_string(|s| s.print_meta_item(mi))
290 pub fn attribute_to_string(attr: &hir::Attribute) -> String {
291 to_string(|s| s.print_attribute(attr))
294 pub fn lit_to_string(l: &hir::Lit) -> String {
295 to_string(|s| s.print_literal(l))
298 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
299 to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
302 pub fn variant_to_string(var: &hir::Variant) -> String {
303 to_string(|s| s.print_variant(var))
306 pub fn arg_to_string(arg: &hir::Arg) -> String {
307 to_string(|s| s.print_arg(arg))
310 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
312 hir::Public => format!("pub {}", s),
313 hir::Inherited => s.to_string()
317 fn needs_parentheses(expr: &hir::Expr) -> bool {
319 hir::ExprAssign(..) | hir::ExprBinary(..) |
320 hir::ExprClosure(..) |
321 hir::ExprAssignOp(..) | hir::ExprCast(..) => true,
327 pub fn ibox(&mut self, u: usize) -> io::Result<()> {
328 self.boxes.push(pp::Breaks::Inconsistent);
329 pp::ibox(&mut self.s, u)
332 pub fn end(&mut self) -> io::Result<()> {
333 self.boxes.pop().unwrap();
337 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
338 self.boxes.push(pp::Breaks::Consistent);
339 pp::cbox(&mut self.s, u)
343 pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
345 pp::rbox(&mut self.s, u, b)
348 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
350 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
351 try!(word(&mut self.s, w));
355 pub fn word_space(&mut self, w: &str) -> io::Result<()> {
356 try!(word(&mut self.s, w));
360 pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
362 pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
364 pub fn head(&mut self, w: &str) -> io::Result<()> {
365 // outer-box is consistent
366 try!(self.cbox(indent_unit));
367 // head-box is inconsistent
368 try!(self.ibox(w.len() + 1));
369 // keyword that starts the head
371 try!(self.word_nbsp(w));
376 pub fn bopen(&mut self) -> io::Result<()> {
377 try!(word(&mut self.s, "{"));
378 self.end() // close the head-box
381 pub fn bclose_(&mut self, span: codemap::Span,
382 indented: usize) -> io::Result<()> {
383 self.bclose_maybe_open(span, indented, true)
385 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
386 indented: usize, close_box: bool) -> io::Result<()> {
387 try!(self.maybe_print_comment(span.hi));
388 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
389 try!(word(&mut self.s, "}"));
391 try!(self.end()); // close the outer-box
395 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
396 self.bclose_(span, indent_unit)
399 pub fn is_begin(&mut self) -> bool {
400 match self.s.last_token() {
401 pp::Token::Begin(_) => true,
406 pub fn is_end(&mut self) -> bool {
407 match self.s.last_token() {
408 pp::Token::End => true,
413 // is this the beginning of a line?
414 pub fn is_bol(&mut self) -> bool {
415 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
418 pub fn in_cbox(&self) -> bool {
419 match self.boxes.last() {
420 Some(&last_box) => last_box == pp::Breaks::Consistent,
425 pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
427 try!(hardbreak(&mut self.s))
431 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
432 if !self.is_bol() { try!(space(&mut self.s)); }
435 pub fn break_offset_if_not_bol(&mut self, n: usize,
436 off: isize) -> io::Result<()> {
438 break_offset(&mut self.s, n, off)
440 if off != 0 && self.s.last_token().is_hardbreak_tok() {
441 // We do something pretty sketchy here: tuck the nonzero
442 // offset-adjustment we were going to deposit along with the
443 // break into the previous hardbreak.
444 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
450 // Synthesizes a comment that was not textually present in the original source
452 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
453 try!(word(&mut self.s, "/*"));
454 try!(space(&mut self.s));
455 try!(word(&mut self.s, &text[..]));
456 try!(space(&mut self.s));
457 word(&mut self.s, "*/")
460 pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
461 F: FnMut(&mut State, &T) -> io::Result<()>,
463 try!(self.rbox(0, b));
464 let mut first = true;
466 if first { first = false; } else { try!(self.word_space(",")); }
473 pub fn commasep_cmnt<T, F, G>(&mut self,
477 mut get_span: G) -> io::Result<()> where
478 F: FnMut(&mut State, &T) -> io::Result<()>,
479 G: FnMut(&T) -> codemap::Span,
481 try!(self.rbox(0, b));
482 let len = elts.len();
485 try!(self.maybe_print_comment(get_span(elt).hi));
489 try!(word(&mut self.s, ","));
490 try!(self.maybe_print_trailing_comment(get_span(elt),
491 Some(get_span(&elts[i]).hi)));
492 try!(self.space_if_not_bol());
498 pub fn commasep_exprs(&mut self, b: Breaks,
499 exprs: &[P<hir::Expr>]) -> io::Result<()> {
500 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
503 pub fn print_mod(&mut self, _mod: &hir::Mod,
504 attrs: &[hir::Attribute]) -> io::Result<()> {
505 try!(self.print_inner_attributes(attrs));
506 for item in &_mod.items {
507 try!(self.print_item(&**item));
512 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod,
513 attrs: &[hir::Attribute]) -> io::Result<()> {
514 try!(self.print_inner_attributes(attrs));
515 for item in &nmod.items {
516 try!(self.print_foreign_item(&**item));
521 pub fn print_opt_lifetime(&mut self,
522 lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
523 if let Some(l) = *lifetime {
524 try!(self.print_lifetime(&l));
530 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
531 try!(self.maybe_print_comment(ty.span.lo));
534 hir::TyVec(ref ty) => {
535 try!(word(&mut self.s, "["));
536 try!(self.print_type(&**ty));
537 try!(word(&mut self.s, "]"));
539 hir::TyPtr(ref mt) => {
540 try!(word(&mut self.s, "*"));
542 hir::MutMutable => try!(self.word_nbsp("mut")),
543 hir::MutImmutable => try!(self.word_nbsp("const")),
545 try!(self.print_type(&*mt.ty));
547 hir::TyRptr(ref lifetime, ref mt) => {
548 try!(word(&mut self.s, "&"));
549 try!(self.print_opt_lifetime(lifetime));
550 try!(self.print_mt(mt));
552 hir::TyTup(ref elts) => {
554 try!(self.commasep(Inconsistent, &elts[..],
555 |s, ty| s.print_type(&**ty)));
557 try!(word(&mut self.s, ","));
561 hir::TyParen(ref typ) => {
563 try!(self.print_type(&**typ));
566 hir::TyBareFn(ref f) => {
567 let generics = hir::Generics {
568 lifetimes: f.lifetimes.clone(),
569 ty_params: OwnedSlice::empty(),
570 where_clause: hir::WhereClause {
571 id: ast::DUMMY_NODE_ID,
572 predicates: Vec::new(),
575 try!(self.print_ty_fn(f.abi,
582 hir::TyPath(None, ref path) => {
583 try!(self.print_path(path, false, 0));
585 hir::TyPath(Some(ref qself), ref path) => {
586 try!(self.print_qpath(path, qself, false))
588 hir::TyObjectSum(ref ty, ref bounds) => {
589 try!(self.print_type(&**ty));
590 try!(self.print_bounds("+", &bounds[..]));
592 hir::TyPolyTraitRef(ref bounds) => {
593 try!(self.print_bounds("", &bounds[..]));
595 hir::TyFixedLengthVec(ref ty, ref v) => {
596 try!(word(&mut self.s, "["));
597 try!(self.print_type(&**ty));
598 try!(word(&mut self.s, "; "));
599 try!(self.print_expr(&**v));
600 try!(word(&mut self.s, "]"));
602 hir::TyTypeof(ref e) => {
603 try!(word(&mut self.s, "typeof("));
604 try!(self.print_expr(&**e));
605 try!(word(&mut self.s, ")"));
608 try!(word(&mut self.s, "_"));
614 pub fn print_foreign_item(&mut self,
615 item: &hir::ForeignItem) -> io::Result<()> {
616 try!(self.hardbreak_if_not_bol());
617 try!(self.maybe_print_comment(item.span.lo));
618 try!(self.print_outer_attributes(&item.attrs));
620 hir::ForeignItemFn(ref decl, ref generics) => {
622 try!(self.print_fn(decl, hir::Unsafety::Normal,
623 hir::Constness::NotConst,
624 abi::Rust, Some(item.ident),
625 generics, None, item.vis));
626 try!(self.end()); // end head-ibox
627 try!(word(&mut self.s, ";"));
628 self.end() // end the outer fn box
630 hir::ForeignItemStatic(ref t, m) => {
631 try!(self.head(&visibility_qualified(item.vis,
634 try!(self.word_space("mut"));
636 try!(self.print_ident(item.ident));
637 try!(self.word_space(":"));
638 try!(self.print_type(&**t));
639 try!(word(&mut self.s, ";"));
640 try!(self.end()); // end the head-ibox
641 self.end() // end the outer cbox
646 fn print_associated_const(&mut self,
649 default: Option<&hir::Expr>,
650 vis: hir::Visibility)
653 try!(word(&mut self.s, &visibility_qualified(vis, "")));
654 try!(self.word_space("const"));
655 try!(self.print_ident(ident));
656 try!(self.word_space(":"));
657 try!(self.print_type(ty));
658 if let Some(expr) = default {
659 try!(space(&mut self.s));
660 try!(self.word_space("="));
661 try!(self.print_expr(expr));
663 word(&mut self.s, ";")
666 fn print_associated_type(&mut self,
668 bounds: Option<&hir::TyParamBounds>,
669 ty: Option<&hir::Ty>)
671 try!(self.word_space("type"));
672 try!(self.print_ident(ident));
673 if let Some(bounds) = bounds {
674 try!(self.print_bounds(":", bounds));
676 if let Some(ty) = ty {
677 try!(space(&mut self.s));
678 try!(self.word_space("="));
679 try!(self.print_type(ty));
681 word(&mut self.s, ";")
684 /// Pretty-print an item
685 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
686 try!(self.hardbreak_if_not_bol());
687 try!(self.maybe_print_comment(item.span.lo));
688 try!(self.print_outer_attributes(&item.attrs));
689 try!(self.ann.pre(self, NodeItem(item)));
691 hir::ItemExternCrate(ref optional_path) => {
692 try!(self.head(&visibility_qualified(item.vis,
694 if let Some(p) = *optional_path {
695 let val = p.as_str();
696 if val.contains("-") {
697 try!(self.print_string(&val, hir::CookedStr));
699 try!(self.print_name(p));
701 try!(space(&mut self.s));
702 try!(word(&mut self.s, "as"));
703 try!(space(&mut self.s));
705 try!(self.print_ident(item.ident));
706 try!(word(&mut self.s, ";"));
707 try!(self.end()); // end inner head-block
708 try!(self.end()); // end outer head-block
710 hir::ItemUse(ref vp) => {
711 try!(self.head(&visibility_qualified(item.vis,
713 try!(self.print_view_path(&**vp));
714 try!(word(&mut self.s, ";"));
715 try!(self.end()); // end inner head-block
716 try!(self.end()); // end outer head-block
718 hir::ItemStatic(ref ty, m, ref expr) => {
719 try!(self.head(&visibility_qualified(item.vis,
721 if m == hir::MutMutable {
722 try!(self.word_space("mut"));
724 try!(self.print_ident(item.ident));
725 try!(self.word_space(":"));
726 try!(self.print_type(&**ty));
727 try!(space(&mut self.s));
728 try!(self.end()); // end the head-ibox
730 try!(self.word_space("="));
731 try!(self.print_expr(&**expr));
732 try!(word(&mut self.s, ";"));
733 try!(self.end()); // end the outer cbox
735 hir::ItemConst(ref ty, ref expr) => {
736 try!(self.head(&visibility_qualified(item.vis,
738 try!(self.print_ident(item.ident));
739 try!(self.word_space(":"));
740 try!(self.print_type(&**ty));
741 try!(space(&mut self.s));
742 try!(self.end()); // end the head-ibox
744 try!(self.word_space("="));
745 try!(self.print_expr(&**expr));
746 try!(word(&mut self.s, ";"));
747 try!(self.end()); // end the outer cbox
749 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
761 try!(word(&mut self.s, " "));
762 try!(self.print_block_with_attrs(&**body, &item.attrs));
764 hir::ItemMod(ref _mod) => {
765 try!(self.head(&visibility_qualified(item.vis,
767 try!(self.print_ident(item.ident));
770 try!(self.print_mod(_mod, &item.attrs));
771 try!(self.bclose(item.span));
773 hir::ItemForeignMod(ref nmod) => {
774 try!(self.head("extern"));
775 try!(self.word_nbsp(&nmod.abi.to_string()));
777 try!(self.print_foreign_mod(nmod, &item.attrs));
778 try!(self.bclose(item.span));
780 hir::ItemTy(ref ty, ref params) => {
781 try!(self.ibox(indent_unit));
783 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
784 try!(self.print_ident(item.ident));
785 try!(self.print_generics(params));
786 try!(self.end()); // end the inner ibox
788 try!(self.print_where_clause(¶ms.where_clause));
789 try!(space(&mut self.s));
790 try!(self.word_space("="));
791 try!(self.print_type(&**ty));
792 try!(word(&mut self.s, ";"));
793 try!(self.end()); // end the outer ibox
795 hir::ItemEnum(ref enum_definition, ref params) => {
796 try!(self.print_enum_def(
804 hir::ItemStruct(ref struct_def, ref generics) => {
805 try!(self.head(&visibility_qualified(item.vis,"struct")));
806 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
809 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
811 try!(self.print_visibility(item.vis));
812 try!(self.print_unsafety(unsafety));
813 try!(self.word_nbsp("impl"));
814 try!(self.print_trait_ref(trait_ref));
815 try!(space(&mut self.s));
816 try!(self.word_space("for"));
817 try!(self.word_space(".."));
819 try!(self.bclose(item.span));
821 hir::ItemImpl(unsafety,
828 try!(self.print_visibility(item.vis));
829 try!(self.print_unsafety(unsafety));
830 try!(self.word_nbsp("impl"));
832 if generics.is_parameterized() {
833 try!(self.print_generics(generics));
834 try!(space(&mut self.s));
838 hir::ImplPolarity::Negative => {
839 try!(word(&mut self.s, "!"));
846 try!(self.print_trait_ref(t));
847 try!(space(&mut self.s));
848 try!(self.word_space("for"));
853 try!(self.print_type(&**ty));
854 try!(self.print_where_clause(&generics.where_clause));
856 try!(space(&mut self.s));
858 try!(self.print_inner_attributes(&item.attrs));
859 for impl_item in impl_items {
860 try!(self.print_impl_item(impl_item));
862 try!(self.bclose(item.span));
864 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
866 try!(self.print_visibility(item.vis));
867 try!(self.print_unsafety(unsafety));
868 try!(self.word_nbsp("trait"));
869 try!(self.print_ident(item.ident));
870 try!(self.print_generics(generics));
871 let mut real_bounds = Vec::with_capacity(bounds.len());
872 for b in bounds.iter() {
873 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
874 try!(space(&mut self.s));
875 try!(self.word_space("for ?"));
876 try!(self.print_trait_ref(&ptr.trait_ref));
878 real_bounds.push(b.clone());
881 try!(self.print_bounds(":", &real_bounds[..]));
882 try!(self.print_where_clause(&generics.where_clause));
883 try!(word(&mut self.s, " "));
885 for trait_item in trait_items {
886 try!(self.print_trait_item(trait_item));
888 try!(self.bclose(item.span));
891 self.ann.post(self, NodeItem(item))
894 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
895 self.print_path(&t.path, false, 0)
898 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
899 if !lifetimes.is_empty() {
900 try!(word(&mut self.s, "for<"));
901 let mut comma = false;
902 for lifetime_def in lifetimes {
904 try!(self.word_space(","))
906 try!(self.print_lifetime_def(lifetime_def));
909 try!(word(&mut self.s, ">"));
914 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
915 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
916 self.print_trait_ref(&t.trait_ref)
919 pub fn print_enum_def(&mut self, enum_definition: &hir::EnumDef,
920 generics: &hir::Generics, ident: ast::Ident,
922 visibility: hir::Visibility) -> io::Result<()> {
923 try!(self.head(&visibility_qualified(visibility, "enum")));
924 try!(self.print_ident(ident));
925 try!(self.print_generics(generics));
926 try!(self.print_where_clause(&generics.where_clause));
927 try!(space(&mut self.s));
928 self.print_variants(&enum_definition.variants, span)
931 pub fn print_variants(&mut self,
932 variants: &[P<hir::Variant>],
933 span: codemap::Span) -> io::Result<()> {
936 try!(self.space_if_not_bol());
937 try!(self.maybe_print_comment(v.span.lo));
938 try!(self.print_outer_attributes(&v.node.attrs));
939 try!(self.ibox(indent_unit));
940 try!(self.print_variant(&**v));
941 try!(word(&mut self.s, ","));
943 try!(self.maybe_print_trailing_comment(v.span, None));
948 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
950 hir::Public => self.word_nbsp("pub"),
951 hir::Inherited => Ok(())
955 pub fn print_struct(&mut self,
956 struct_def: &hir::StructDef,
957 generics: &hir::Generics,
959 span: codemap::Span) -> io::Result<()> {
960 try!(self.print_ident(ident));
961 try!(self.print_generics(generics));
962 if ::util::struct_def_is_tuple_like(struct_def) {
963 if !struct_def.fields.is_empty() {
966 Inconsistent, &struct_def.fields,
968 match field.node.kind {
969 hir::NamedField(..) => panic!("unexpected named field"),
970 hir::UnnamedField(vis) => {
971 try!(s.print_visibility(vis));
972 try!(s.maybe_print_comment(field.span.lo));
973 s.print_type(&*field.node.ty)
980 try!(self.print_where_clause(&generics.where_clause));
981 try!(word(&mut self.s, ";"));
983 self.end() // close the outer-box
985 try!(self.print_where_clause(&generics.where_clause));
988 try!(self.hardbreak_if_not_bol());
990 for field in &struct_def.fields {
991 match field.node.kind {
992 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
993 hir::NamedField(ident, visibility) => {
994 try!(self.hardbreak_if_not_bol());
995 try!(self.maybe_print_comment(field.span.lo));
996 try!(self.print_outer_attributes(&field.node.attrs));
997 try!(self.print_visibility(visibility));
998 try!(self.print_ident(ident));
999 try!(self.word_nbsp(":"));
1000 try!(self.print_type(&*field.node.ty));
1001 try!(word(&mut self.s, ","));
1010 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
1011 try!(self.print_visibility(v.node.vis));
1013 hir::TupleVariantKind(ref args) => {
1014 try!(self.print_ident(v.node.name));
1015 if !args.is_empty() {
1017 try!(self.commasep(Consistent,
1019 |s, arg| s.print_type(&*arg.ty)));
1020 try!(self.pclose());
1023 hir::StructVariantKind(ref struct_def) => {
1024 try!(self.head(""));
1025 let generics = ::util::empty_generics();
1026 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1029 match v.node.disr_expr {
1031 try!(space(&mut self.s));
1032 try!(self.word_space("="));
1033 self.print_expr(&**d)
1039 pub fn print_method_sig(&mut self,
1042 vis: hir::Visibility)
1044 self.print_fn(&m.decl,
1050 Some(&m.explicit_self.node),
1054 pub fn print_trait_item(&mut self, ti: &hir::TraitItem)
1056 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1057 try!(self.hardbreak_if_not_bol());
1058 try!(self.maybe_print_comment(ti.span.lo));
1059 try!(self.print_outer_attributes(&ti.attrs));
1061 hir::ConstTraitItem(ref ty, ref default) => {
1062 try!(self.print_associated_const(ti.ident, &ty,
1063 default.as_ref().map(|expr| &**expr),
1066 hir::MethodTraitItem(ref sig, ref body) => {
1068 try!(self.head(""));
1070 try!(self.print_method_sig(ti.ident, sig, hir::Inherited));
1071 if let Some(ref body) = *body {
1073 try!(self.print_block_with_attrs(body, &ti.attrs));
1075 try!(word(&mut self.s, ";"));
1078 hir::TypeTraitItem(ref bounds, ref default) => {
1079 try!(self.print_associated_type(ti.ident, Some(bounds),
1080 default.as_ref().map(|ty| &**ty)));
1083 self.ann.post(self, NodeSubItem(ti.id))
1086 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1087 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1088 try!(self.hardbreak_if_not_bol());
1089 try!(self.maybe_print_comment(ii.span.lo));
1090 try!(self.print_outer_attributes(&ii.attrs));
1092 hir::ConstImplItem(ref ty, ref expr) => {
1093 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1095 hir::MethodImplItem(ref sig, ref body) => {
1096 try!(self.head(""));
1097 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1099 try!(self.print_block_with_attrs(body, &ii.attrs));
1101 hir::TypeImplItem(ref ty) => {
1102 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1105 self.ann.post(self, NodeSubItem(ii.id))
1108 pub fn print_outer_attributes(&mut self,
1109 attrs: &[hir::Attribute]) -> io::Result<()> {
1112 match attr.node.style {
1114 try!(self.print_attribute(attr));
1117 _ => {/* fallthrough */ }
1121 try!(self.hardbreak_if_not_bol());
1126 pub fn print_inner_attributes(&mut self,
1127 attrs: &[hir::Attribute]) -> io::Result<()> {
1130 match attr.node.style {
1132 try!(self.print_attribute(attr));
1135 _ => {/* fallthrough */ }
1139 try!(self.hardbreak_if_not_bol());
1144 pub fn print_attribute(&mut self, attr: &hir::Attribute) -> io::Result<()> {
1145 try!(self.hardbreak_if_not_bol());
1146 try!(self.maybe_print_comment(attr.span.lo));
1147 if attr.node.is_sugared_doc {
1148 word(&mut self.s, &attr.value_str().unwrap())
1150 match attr.node.style {
1151 hir::AttrInner => try!(word(&mut self.s, "#![")),
1152 hir::AttrOuter => try!(word(&mut self.s, "#[")),
1154 try!(self.print_meta_item(&*attr.meta()));
1155 word(&mut self.s, "]")
1160 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1161 try!(self.maybe_print_comment(st.span.lo));
1163 hir::StmtDecl(ref decl, _) => {
1164 try!(self.print_decl(&**decl));
1166 hir::StmtExpr(ref expr, _) => {
1167 try!(self.space_if_not_bol());
1168 try!(self.print_expr(&**expr));
1170 hir::StmtSemi(ref expr, _) => {
1171 try!(self.space_if_not_bol());
1172 try!(self.print_expr(&**expr));
1173 try!(word(&mut self.s, ";"));
1176 if stmt_ends_with_semi(&st.node) {
1177 try!(word(&mut self.s, ";"));
1179 self.maybe_print_trailing_comment(st.span, None)
1182 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1183 self.print_block_with_attrs(blk, &[])
1186 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1187 self.print_block_unclosed_indent(blk, indent_unit)
1190 pub fn print_block_unclosed_indent(&mut self, blk: &hir::Block,
1191 indented: usize) -> io::Result<()> {
1192 self.print_block_maybe_unclosed(blk, indented, &[], false)
1195 pub fn print_block_with_attrs(&mut self,
1197 attrs: &[hir::Attribute]) -> io::Result<()> {
1198 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1201 pub fn print_block_maybe_unclosed(&mut self,
1204 attrs: &[hir::Attribute],
1205 close_box: bool) -> io::Result<()> {
1207 hir::UnsafeBlock(..) | hir::PushUnsafeBlock(..) => try!(self.word_space("unsafe")),
1208 hir::DefaultBlock | hir::PopUnsafeBlock(..) => ()
1210 try!(self.maybe_print_comment(blk.span.lo));
1211 try!(self.ann.pre(self, NodeBlock(blk)));
1214 try!(self.print_inner_attributes(attrs));
1216 for st in &blk.stmts {
1217 try!(self.print_stmt(&**st));
1221 try!(self.space_if_not_bol());
1222 try!(self.print_expr(&**expr));
1223 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1227 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1228 self.ann.post(self, NodeBlock(blk))
1231 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1235 // "another else-if"
1236 hir::ExprIf(ref i, ref then, ref e) => {
1237 try!(self.cbox(indent_unit - 1));
1239 try!(word(&mut self.s, " else if "));
1240 try!(self.print_expr(&**i));
1241 try!(space(&mut self.s));
1242 try!(self.print_block(&**then));
1243 self.print_else(e.as_ref().map(|e| &**e))
1246 hir::ExprBlock(ref b) => {
1247 try!(self.cbox(indent_unit - 1));
1249 try!(word(&mut self.s, " else "));
1250 self.print_block(&**b)
1252 // BLEAH, constraints would be great here
1254 panic!("print_if saw if with weird alternative");
1262 pub fn print_if(&mut self, test: &hir::Expr, blk: &hir::Block,
1263 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1264 try!(self.head("if"));
1265 try!(self.print_expr(test));
1266 try!(space(&mut self.s));
1267 try!(self.print_block(blk));
1268 self.print_else(elseopt)
1271 pub fn print_if_let(&mut self, pat: &hir::Pat, expr: &hir::Expr, blk: &hir::Block,
1272 elseopt: Option<&hir::Expr>) -> io::Result<()> {
1273 try!(self.head("if let"));
1274 try!(self.print_pat(pat));
1275 try!(space(&mut self.s));
1276 try!(self.word_space("="));
1277 try!(self.print_expr(expr));
1278 try!(space(&mut self.s));
1279 try!(self.print_block(blk));
1280 self.print_else(elseopt)
1284 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1286 try!(self.commasep_exprs(Inconsistent, args));
1290 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1291 let needs_par = needs_parentheses(expr);
1295 try!(self.print_expr(expr));
1297 try!(self.pclose());
1302 fn print_expr_box(&mut self,
1303 place: &Option<P<hir::Expr>>,
1304 expr: &hir::Expr) -> io::Result<()> {
1305 try!(word(&mut self.s, "box"));
1306 try!(word(&mut self.s, "("));
1307 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1308 try!(self.word_space(")"));
1309 self.print_expr(expr)
1312 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1313 try!(self.ibox(indent_unit));
1314 try!(word(&mut self.s, "["));
1315 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1316 try!(word(&mut self.s, "]"));
1320 fn print_expr_repeat(&mut self,
1321 element: &hir::Expr,
1322 count: &hir::Expr) -> io::Result<()> {
1323 try!(self.ibox(indent_unit));
1324 try!(word(&mut self.s, "["));
1325 try!(self.print_expr(element));
1326 try!(self.word_space(";"));
1327 try!(self.print_expr(count));
1328 try!(word(&mut self.s, "]"));
1332 fn print_expr_struct(&mut self,
1334 fields: &[hir::Field],
1335 wth: &Option<P<hir::Expr>>) -> io::Result<()> {
1336 try!(self.print_path(path, true, 0));
1337 if !(fields.is_empty() && wth.is_none()) {
1338 try!(word(&mut self.s, "{"));
1339 try!(self.commasep_cmnt(
1343 try!(s.ibox(indent_unit));
1344 try!(s.print_ident(field.ident.node));
1345 try!(s.word_space(":"));
1346 try!(s.print_expr(&*field.expr));
1352 try!(self.ibox(indent_unit));
1353 if !fields.is_empty() {
1354 try!(word(&mut self.s, ","));
1355 try!(space(&mut self.s));
1357 try!(word(&mut self.s, ".."));
1358 try!(self.print_expr(&**expr));
1361 _ => try!(word(&mut self.s, ",")),
1363 try!(word(&mut self.s, "}"));
1368 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1370 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1371 if exprs.len() == 1 {
1372 try!(word(&mut self.s, ","));
1377 fn print_expr_call(&mut self,
1379 args: &[P<hir::Expr>]) -> io::Result<()> {
1380 try!(self.print_expr_maybe_paren(func));
1381 self.print_call_post(args)
1384 fn print_expr_method_call(&mut self,
1385 ident: hir::SpannedIdent,
1387 args: &[P<hir::Expr>]) -> io::Result<()> {
1388 let base_args = &args[1..];
1389 try!(self.print_expr(&*args[0]));
1390 try!(word(&mut self.s, "."));
1391 try!(self.print_ident(ident.node));
1392 if !tys.is_empty() {
1393 try!(word(&mut self.s, "::<"));
1394 try!(self.commasep(Inconsistent, tys,
1395 |s, ty| s.print_type(&**ty)));
1396 try!(word(&mut self.s, ">"));
1398 self.print_call_post(base_args)
1401 fn print_expr_binary(&mut self,
1404 rhs: &hir::Expr) -> io::Result<()> {
1405 try!(self.print_expr(lhs));
1406 try!(space(&mut self.s));
1407 try!(self.word_space(::util::binop_to_string(op.node)));
1408 self.print_expr(rhs)
1411 fn print_expr_unary(&mut self,
1413 expr: &hir::Expr) -> io::Result<()> {
1414 try!(word(&mut self.s, ::util::unop_to_string(op)));
1415 self.print_expr_maybe_paren(expr)
1418 fn print_expr_addr_of(&mut self,
1419 mutability: hir::Mutability,
1420 expr: &hir::Expr) -> io::Result<()> {
1421 try!(word(&mut self.s, "&"));
1422 try!(self.print_mutability(mutability));
1423 self.print_expr_maybe_paren(expr)
1426 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1427 try!(self.maybe_print_comment(expr.span.lo));
1428 try!(self.ibox(indent_unit));
1429 try!(self.ann.pre(self, NodeExpr(expr)));
1431 hir::ExprBox(ref place, ref expr) => {
1432 try!(self.print_expr_box(place, &**expr));
1434 hir::ExprVec(ref exprs) => {
1435 try!(self.print_expr_vec(&exprs[..]));
1437 hir::ExprRepeat(ref element, ref count) => {
1438 try!(self.print_expr_repeat(&**element, &**count));
1440 hir::ExprStruct(ref path, ref fields, ref wth) => {
1441 try!(self.print_expr_struct(path, &fields[..], wth));
1443 hir::ExprTup(ref exprs) => {
1444 try!(self.print_expr_tup(&exprs[..]));
1446 hir::ExprCall(ref func, ref args) => {
1447 try!(self.print_expr_call(&**func, &args[..]));
1449 hir::ExprMethodCall(ident, ref tys, ref args) => {
1450 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1452 hir::ExprBinary(op, ref lhs, ref rhs) => {
1453 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1455 hir::ExprUnary(op, ref expr) => {
1456 try!(self.print_expr_unary(op, &**expr));
1458 hir::ExprAddrOf(m, ref expr) => {
1459 try!(self.print_expr_addr_of(m, &**expr));
1461 hir::ExprLit(ref lit) => {
1462 try!(self.print_literal(&**lit));
1464 hir::ExprCast(ref expr, ref ty) => {
1465 try!(self.print_expr(&**expr));
1466 try!(space(&mut self.s));
1467 try!(self.word_space("as"));
1468 try!(self.print_type(&**ty));
1470 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1471 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1473 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1474 if let Some(ident) = opt_ident {
1475 try!(self.print_ident(ident));
1476 try!(self.word_space(":"));
1478 try!(self.head("while"));
1479 try!(self.print_expr(&**test));
1480 try!(space(&mut self.s));
1481 try!(self.print_block(&**blk));
1483 hir::ExprLoop(ref blk, opt_ident) => {
1484 if let Some(ident) = opt_ident {
1485 try!(self.print_ident(ident));
1486 try!(self.word_space(":"));
1488 try!(self.head("loop"));
1489 try!(space(&mut self.s));
1490 try!(self.print_block(&**blk));
1492 hir::ExprMatch(ref expr, ref arms, _) => {
1493 try!(self.cbox(indent_unit));
1495 try!(self.word_nbsp("match"));
1496 try!(self.print_expr(&**expr));
1497 try!(space(&mut self.s));
1500 try!(self.print_arm(arm));
1502 try!(self.bclose_(expr.span, indent_unit));
1504 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1505 try!(self.print_capture_clause(capture_clause));
1507 try!(self.print_fn_block_args(&**decl));
1508 try!(space(&mut self.s));
1510 let default_return = match decl.output {
1511 hir::DefaultReturn(..) => true,
1515 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1516 try!(self.print_block_unclosed(&**body));
1518 // we extract the block, so as not to create another set of boxes
1519 match body.expr.as_ref().unwrap().node {
1520 hir::ExprBlock(ref blk) => {
1521 try!(self.print_block_unclosed(&**blk));
1524 // this is a bare expression
1525 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1526 try!(self.end()); // need to close a box
1530 // a box will be closed by print_expr, but we didn't want an overall
1531 // wrapper so we closed the corresponding opening. so create an
1532 // empty box to satisfy the close.
1535 hir::ExprBlock(ref blk) => {
1536 // containing cbox, will be closed by print-block at }
1537 try!(self.cbox(indent_unit));
1538 // head-box, will be closed by print-block after {
1540 try!(self.print_block(&**blk));
1542 hir::ExprAssign(ref lhs, ref rhs) => {
1543 try!(self.print_expr(&**lhs));
1544 try!(space(&mut self.s));
1545 try!(self.word_space("="));
1546 try!(self.print_expr(&**rhs));
1548 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1549 try!(self.print_expr(&**lhs));
1550 try!(space(&mut self.s));
1551 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1552 try!(self.word_space("="));
1553 try!(self.print_expr(&**rhs));
1555 hir::ExprField(ref expr, id) => {
1556 try!(self.print_expr(&**expr));
1557 try!(word(&mut self.s, "."));
1558 try!(self.print_ident(id.node));
1560 hir::ExprTupField(ref expr, id) => {
1561 try!(self.print_expr(&**expr));
1562 try!(word(&mut self.s, "."));
1563 try!(self.print_usize(id.node));
1565 hir::ExprIndex(ref expr, ref index) => {
1566 try!(self.print_expr(&**expr));
1567 try!(word(&mut self.s, "["));
1568 try!(self.print_expr(&**index));
1569 try!(word(&mut self.s, "]"));
1571 hir::ExprRange(ref start, ref end) => {
1572 if let &Some(ref e) = start {
1573 try!(self.print_expr(&**e));
1575 try!(word(&mut self.s, ".."));
1576 if let &Some(ref e) = end {
1577 try!(self.print_expr(&**e));
1580 hir::ExprPath(None, ref path) => {
1581 try!(self.print_path(path, true, 0))
1583 hir::ExprPath(Some(ref qself), ref path) => {
1584 try!(self.print_qpath(path, qself, true))
1586 hir::ExprBreak(opt_ident) => {
1587 try!(word(&mut self.s, "break"));
1588 try!(space(&mut self.s));
1589 if let Some(ident) = opt_ident {
1590 try!(self.print_ident(ident.node));
1591 try!(space(&mut self.s));
1594 hir::ExprAgain(opt_ident) => {
1595 try!(word(&mut self.s, "continue"));
1596 try!(space(&mut self.s));
1597 if let Some(ident) = opt_ident {
1598 try!(self.print_ident(ident.node));
1599 try!(space(&mut self.s))
1602 hir::ExprRet(ref result) => {
1603 try!(word(&mut self.s, "return"));
1606 try!(word(&mut self.s, " "));
1607 try!(self.print_expr(&**expr));
1612 hir::ExprInlineAsm(ref a) => {
1613 try!(word(&mut self.s, "asm!"));
1615 try!(self.print_string(&a.asm, a.asm_str_style));
1616 try!(self.word_space(":"));
1618 try!(self.commasep(Inconsistent, &a.outputs,
1619 |s, &(ref co, ref o, is_rw)| {
1620 match co.slice_shift_char() {
1621 Some(('=', operand)) if is_rw => {
1622 try!(s.print_string(&format!("+{}", operand),
1625 _ => try!(s.print_string(&co, hir::CookedStr))
1628 try!(s.print_expr(&**o));
1632 try!(space(&mut self.s));
1633 try!(self.word_space(":"));
1635 try!(self.commasep(Inconsistent, &a.inputs,
1636 |s, &(ref co, ref o)| {
1637 try!(s.print_string(&co, hir::CookedStr));
1639 try!(s.print_expr(&**o));
1643 try!(space(&mut self.s));
1644 try!(self.word_space(":"));
1646 try!(self.commasep(Inconsistent, &a.clobbers,
1648 try!(s.print_string(&co, hir::CookedStr));
1652 let mut options = vec!();
1654 options.push("volatile");
1657 options.push("alignstack");
1659 if a.dialect == hir::AsmDialect::AsmIntel {
1660 options.push("intel");
1663 if !options.is_empty() {
1664 try!(space(&mut self.s));
1665 try!(self.word_space(":"));
1666 try!(self.commasep(Inconsistent, &*options,
1668 try!(s.print_string(co, hir::CookedStr));
1673 try!(self.pclose());
1675 hir::ExprParen(ref e) => {
1677 try!(self.print_expr(&**e));
1678 try!(self.pclose());
1681 try!(self.ann.post(self, NodeExpr(expr)));
1685 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1686 try!(self.print_pat(&*loc.pat));
1687 if let Some(ref ty) = loc.ty {
1688 try!(self.word_space(":"));
1689 try!(self.print_type(&**ty));
1694 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1695 try!(self.maybe_print_comment(decl.span.lo));
1697 hir::DeclLocal(ref loc) => {
1698 try!(self.space_if_not_bol());
1699 try!(self.ibox(indent_unit));
1700 try!(self.word_nbsp("let"));
1702 try!(self.ibox(indent_unit));
1703 try!(self.print_local_decl(&**loc));
1705 if let Some(ref init) = loc.init {
1707 try!(self.word_space("="));
1708 try!(self.print_expr(&**init));
1712 hir::DeclItem(ref item) => self.print_item(&**item)
1716 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1717 try!(word(&mut self.s, &ident.name.as_str()));
1718 self.ann.post(self, NodeIdent(&ident))
1721 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1722 word(&mut self.s, &i.to_string())
1725 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1726 try!(word(&mut self.s, &name.as_str()));
1727 self.ann.post(self, NodeName(&name))
1730 pub fn print_for_decl(&mut self, loc: &hir::Local,
1731 coll: &hir::Expr) -> io::Result<()> {
1732 try!(self.print_local_decl(loc));
1733 try!(space(&mut self.s));
1734 try!(self.word_space("in"));
1735 self.print_expr(coll)
1738 fn print_path(&mut self,
1740 colons_before_params: bool,
1744 try!(self.maybe_print_comment(path.span.lo));
1746 let mut first = !path.global;
1747 for segment in &path.segments[..path.segments.len()-depth] {
1751 try!(word(&mut self.s, "::"))
1754 try!(self.print_ident(segment.identifier));
1756 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1762 fn print_qpath(&mut self,
1765 colons_before_params: bool)
1768 try!(word(&mut self.s, "<"));
1769 try!(self.print_type(&qself.ty));
1770 if qself.position > 0 {
1771 try!(space(&mut self.s));
1772 try!(self.word_space("as"));
1773 let depth = path.segments.len() - qself.position;
1774 try!(self.print_path(&path, false, depth));
1776 try!(word(&mut self.s, ">"));
1777 try!(word(&mut self.s, "::"));
1778 let item_segment = path.segments.last().unwrap();
1779 try!(self.print_ident(item_segment.identifier));
1780 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1783 fn print_path_parameters(&mut self,
1784 parameters: &hir::PathParameters,
1785 colons_before_params: bool)
1788 if parameters.is_empty() {
1792 if colons_before_params {
1793 try!(word(&mut self.s, "::"))
1797 hir::AngleBracketedParameters(ref data) => {
1798 try!(word(&mut self.s, "<"));
1800 let mut comma = false;
1801 for lifetime in &data.lifetimes {
1803 try!(self.word_space(","))
1805 try!(self.print_lifetime(lifetime));
1809 if !data.types.is_empty() {
1811 try!(self.word_space(","))
1816 |s, ty| s.print_type(&**ty)));
1820 for binding in data.bindings.iter() {
1822 try!(self.word_space(","))
1824 try!(self.print_ident(binding.ident));
1825 try!(space(&mut self.s));
1826 try!(self.word_space("="));
1827 try!(self.print_type(&*binding.ty));
1831 try!(word(&mut self.s, ">"))
1834 hir::ParenthesizedParameters(ref data) => {
1835 try!(word(&mut self.s, "("));
1839 |s, ty| s.print_type(&**ty)));
1840 try!(word(&mut self.s, ")"));
1845 try!(self.space_if_not_bol());
1846 try!(self.word_space("->"));
1847 try!(self.print_type(&**ty));
1856 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1857 try!(self.maybe_print_comment(pat.span.lo));
1858 try!(self.ann.pre(self, NodePat(pat)));
1859 /* Pat isn't normalized, but the beauty of it
1860 is that it doesn't matter */
1862 hir::PatWild(hir::PatWildSingle) => try!(word(&mut self.s, "_")),
1863 hir::PatWild(hir::PatWildMulti) => try!(word(&mut self.s, "..")),
1864 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1865 match binding_mode {
1866 hir::BindByRef(mutbl) => {
1867 try!(self.word_nbsp("ref"));
1868 try!(self.print_mutability(mutbl));
1870 hir::BindByValue(hir::MutImmutable) => {}
1871 hir::BindByValue(hir::MutMutable) => {
1872 try!(self.word_nbsp("mut"));
1875 try!(self.print_ident(path1.node));
1878 try!(word(&mut self.s, "@"));
1879 try!(self.print_pat(&**p));
1884 hir::PatEnum(ref path, ref args_) => {
1885 try!(self.print_path(path, true, 0));
1887 None => try!(word(&mut self.s, "(..)")),
1889 if !args.is_empty() {
1891 try!(self.commasep(Inconsistent, &args[..],
1892 |s, p| s.print_pat(&**p)));
1893 try!(self.pclose());
1898 hir::PatQPath(ref qself, ref path) => {
1899 try!(self.print_qpath(path, qself, false));
1901 hir::PatStruct(ref path, ref fields, etc) => {
1902 try!(self.print_path(path, true, 0));
1904 try!(self.word_space("{"));
1905 try!(self.commasep_cmnt(
1906 Consistent, &fields[..],
1908 try!(s.cbox(indent_unit));
1909 if !f.node.is_shorthand {
1910 try!(s.print_ident(f.node.ident));
1911 try!(s.word_nbsp(":"));
1913 try!(s.print_pat(&*f.node.pat));
1916 |f| f.node.pat.span));
1918 if !fields.is_empty() { try!(self.word_space(",")); }
1919 try!(word(&mut self.s, ".."));
1921 try!(space(&mut self.s));
1922 try!(word(&mut self.s, "}"));
1924 hir::PatTup(ref elts) => {
1926 try!(self.commasep(Inconsistent,
1928 |s, p| s.print_pat(&**p)));
1929 if elts.len() == 1 {
1930 try!(word(&mut self.s, ","));
1932 try!(self.pclose());
1934 hir::PatBox(ref inner) => {
1935 try!(word(&mut self.s, "box "));
1936 try!(self.print_pat(&**inner));
1938 hir::PatRegion(ref inner, mutbl) => {
1939 try!(word(&mut self.s, "&"));
1940 if mutbl == hir::MutMutable {
1941 try!(word(&mut self.s, "mut "));
1943 try!(self.print_pat(&**inner));
1945 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1946 hir::PatRange(ref begin, ref end) => {
1947 try!(self.print_expr(&**begin));
1948 try!(space(&mut self.s));
1949 try!(word(&mut self.s, "..."));
1950 try!(self.print_expr(&**end));
1952 hir::PatVec(ref before, ref slice, ref after) => {
1953 try!(word(&mut self.s, "["));
1954 try!(self.commasep(Inconsistent,
1956 |s, p| s.print_pat(&**p)));
1957 if let Some(ref p) = *slice {
1958 if !before.is_empty() { try!(self.word_space(",")); }
1959 try!(self.print_pat(&**p));
1961 hir::Pat { node: hir::PatWild(hir::PatWildMulti), .. } => {
1962 // this case is handled by print_pat
1964 _ => try!(word(&mut self.s, "..")),
1966 if !after.is_empty() { try!(self.word_space(",")); }
1968 try!(self.commasep(Inconsistent,
1970 |s, p| s.print_pat(&**p)));
1971 try!(word(&mut self.s, "]"));
1974 self.ann.post(self, NodePat(pat))
1977 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1978 // I have no idea why this check is necessary, but here it
1980 if arm.attrs.is_empty() {
1981 try!(space(&mut self.s));
1983 try!(self.cbox(indent_unit));
1985 try!(self.print_outer_attributes(&arm.attrs));
1986 let mut first = true;
1987 for p in &arm.pats {
1991 try!(space(&mut self.s));
1992 try!(self.word_space("|"));
1994 try!(self.print_pat(&**p));
1996 try!(space(&mut self.s));
1997 if let Some(ref e) = arm.guard {
1998 try!(self.word_space("if"));
1999 try!(self.print_expr(&**e));
2000 try!(space(&mut self.s));
2002 try!(self.word_space("=>"));
2004 match arm.body.node {
2005 hir::ExprBlock(ref blk) => {
2006 // the block will close the pattern's ibox
2007 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2009 // If it is a user-provided unsafe block, print a comma after it
2010 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
2011 try!(word(&mut self.s, ","));
2015 try!(self.end()); // close the ibox for the pattern
2016 try!(self.print_expr(&*arm.body));
2017 try!(word(&mut self.s, ","));
2020 self.end() // close enclosing cbox
2023 // Returns whether it printed anything
2024 fn print_explicit_self(&mut self,
2025 explicit_self: &hir::ExplicitSelf_,
2026 mutbl: hir::Mutability) -> io::Result<bool> {
2027 try!(self.print_mutability(mutbl));
2028 match *explicit_self {
2029 hir::SelfStatic => { return Ok(false); }
2030 hir::SelfValue(_) => {
2031 try!(word(&mut self.s, "self"));
2033 hir::SelfRegion(ref lt, m, _) => {
2034 try!(word(&mut self.s, "&"));
2035 try!(self.print_opt_lifetime(lt));
2036 try!(self.print_mutability(m));
2037 try!(word(&mut self.s, "self"));
2039 hir::SelfExplicit(ref typ, _) => {
2040 try!(word(&mut self.s, "self"));
2041 try!(self.word_space(":"));
2042 try!(self.print_type(&**typ));
2048 pub fn print_fn(&mut self,
2050 unsafety: hir::Unsafety,
2051 constness: hir::Constness,
2053 name: Option<ast::Ident>,
2054 generics: &hir::Generics,
2055 opt_explicit_self: Option<&hir::ExplicitSelf_>,
2056 vis: hir::Visibility) -> io::Result<()> {
2057 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2059 if let Some(name) = name {
2061 try!(self.print_ident(name));
2063 try!(self.print_generics(generics));
2064 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2065 self.print_where_clause(&generics.where_clause)
2068 pub fn print_fn_args(&mut self, decl: &hir::FnDecl,
2069 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2071 // It is unfortunate to duplicate the commasep logic, but we want the
2072 // self type and the args all in the same box.
2073 try!(self.rbox(0, Inconsistent));
2074 let mut first = true;
2075 if let Some(explicit_self) = opt_explicit_self {
2076 let m = match explicit_self {
2077 &hir::SelfStatic => hir::MutImmutable,
2078 _ => match decl.inputs[0].pat.node {
2079 hir::PatIdent(hir::BindByValue(m), _, _) => m,
2080 _ => hir::MutImmutable
2083 first = !try!(self.print_explicit_self(explicit_self, m));
2086 // HACK(eddyb) ignore the separately printed self argument.
2087 let args = if first {
2094 if first { first = false; } else { try!(self.word_space(",")); }
2095 try!(self.print_arg(arg));
2101 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl,
2102 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2105 try!(self.print_fn_args(decl, opt_explicit_self));
2107 try!(word(&mut self.s, ", ..."));
2109 try!(self.pclose());
2111 self.print_fn_output(decl)
2114 pub fn print_fn_block_args(
2118 try!(word(&mut self.s, "|"));
2119 try!(self.print_fn_args(decl, None));
2120 try!(word(&mut self.s, "|"));
2122 if let hir::DefaultReturn(..) = decl.output {
2126 try!(self.space_if_not_bol());
2127 try!(self.word_space("->"));
2129 hir::Return(ref ty) => {
2130 try!(self.print_type(&**ty));
2131 self.maybe_print_comment(ty.span.lo)
2133 hir::DefaultReturn(..) => unreachable!(),
2134 hir::NoReturn(span) => {
2135 try!(self.word_nbsp("!"));
2136 self.maybe_print_comment(span.lo)
2141 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause)
2143 match capture_clause {
2144 hir::CaptureByValue => self.word_space("move"),
2145 hir::CaptureByRef => Ok(()),
2149 pub fn print_bounds(&mut self,
2151 bounds: &[hir::TyParamBound])
2153 if !bounds.is_empty() {
2154 try!(word(&mut self.s, prefix));
2155 let mut first = true;
2156 for bound in bounds {
2161 try!(self.word_space("+"));
2165 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2166 self.print_poly_trait_ref(tref)
2168 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2169 try!(word(&mut self.s, "?"));
2170 self.print_poly_trait_ref(tref)
2172 RegionTyParamBound(ref lt) => {
2173 self.print_lifetime(lt)
2183 pub fn print_lifetime(&mut self,
2184 lifetime: &hir::Lifetime)
2187 self.print_name(lifetime.name)
2190 pub fn print_lifetime_def(&mut self,
2191 lifetime: &hir::LifetimeDef)
2194 try!(self.print_lifetime(&lifetime.lifetime));
2196 for v in &lifetime.bounds {
2197 try!(word(&mut self.s, sep));
2198 try!(self.print_lifetime(v));
2204 pub fn print_generics(&mut self,
2205 generics: &hir::Generics)
2208 let total = generics.lifetimes.len() + generics.ty_params.len();
2213 try!(word(&mut self.s, "<"));
2215 let mut ints = Vec::new();
2220 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2221 if idx < generics.lifetimes.len() {
2222 let lifetime = &generics.lifetimes[idx];
2223 s.print_lifetime_def(lifetime)
2225 let idx = idx - generics.lifetimes.len();
2226 let param = &generics.ty_params[idx];
2227 s.print_ty_param(param)
2231 try!(word(&mut self.s, ">"));
2235 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2236 try!(self.print_ident(param.ident));
2237 try!(self.print_bounds(":", ¶m.bounds));
2238 match param.default {
2239 Some(ref default) => {
2240 try!(space(&mut self.s));
2241 try!(self.word_space("="));
2242 self.print_type(&**default)
2248 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause)
2250 if where_clause.predicates.is_empty() {
2254 try!(space(&mut self.s));
2255 try!(self.word_space("where"));
2257 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2259 try!(self.word_space(","));
2263 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2267 try!(self.print_formal_lifetime_list(bound_lifetimes));
2268 try!(self.print_type(&**bounded_ty));
2269 try!(self.print_bounds(":", bounds));
2271 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2274 try!(self.print_lifetime(lifetime));
2275 try!(word(&mut self.s, ":"));
2277 for (i, bound) in bounds.iter().enumerate() {
2278 try!(self.print_lifetime(bound));
2281 try!(word(&mut self.s, ":"));
2285 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2286 try!(self.print_path(path, false, 0));
2287 try!(space(&mut self.s));
2288 try!(self.word_space("="));
2289 try!(self.print_type(&**ty));
2297 pub fn print_meta_item(&mut self, item: &hir::MetaItem) -> io::Result<()> {
2298 try!(self.ibox(indent_unit));
2300 hir::MetaWord(ref name) => {
2301 try!(word(&mut self.s, &name));
2303 hir::MetaNameValue(ref name, ref value) => {
2304 try!(self.word_space(&name[..]));
2305 try!(self.word_space("="));
2306 try!(self.print_literal(value));
2308 hir::MetaList(ref name, ref items) => {
2309 try!(word(&mut self.s, &name));
2311 try!(self.commasep(Consistent,
2313 |s, i| s.print_meta_item(&**i)));
2314 try!(self.pclose());
2320 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2322 hir::ViewPathSimple(ident, ref path) => {
2323 try!(self.print_path(path, false, 0));
2325 // FIXME(#6993) can't compare identifiers directly here
2326 if path.segments.last().unwrap().identifier.name !=
2328 try!(space(&mut self.s));
2329 try!(self.word_space("as"));
2330 try!(self.print_ident(ident));
2336 hir::ViewPathGlob(ref path) => {
2337 try!(self.print_path(path, false, 0));
2338 word(&mut self.s, "::*")
2341 hir::ViewPathList(ref path, ref idents) => {
2342 if path.segments.is_empty() {
2343 try!(word(&mut self.s, "{"));
2345 try!(self.print_path(path, false, 0));
2346 try!(word(&mut self.s, "::{"));
2348 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2350 hir::PathListIdent { name, .. } => {
2353 hir::PathListMod { .. } => {
2354 word(&mut s.s, "self")
2358 word(&mut self.s, "}")
2363 pub fn print_mutability(&mut self,
2364 mutbl: hir::Mutability) -> io::Result<()> {
2366 hir::MutMutable => self.word_nbsp("mut"),
2367 hir::MutImmutable => Ok(()),
2371 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2372 try!(self.print_mutability(mt.mutbl));
2373 self.print_type(&*mt.ty)
2376 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2377 try!(self.ibox(indent_unit));
2378 match input.ty.node {
2379 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2381 match input.pat.node {
2382 hir::PatIdent(_, ref path1, _) if
2384 parse::token::special_idents::invalid.name => {
2388 try!(self.print_pat(&*input.pat));
2389 try!(word(&mut self.s, ":"));
2390 try!(space(&mut self.s));
2393 try!(self.print_type(&*input.ty));
2399 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2400 if let hir::DefaultReturn(..) = decl.output {
2404 try!(self.space_if_not_bol());
2405 try!(self.ibox(indent_unit));
2406 try!(self.word_space("->"));
2409 try!(self.word_nbsp("!")),
2410 hir::DefaultReturn(..) => unreachable!(),
2411 hir::Return(ref ty) =>
2412 try!(self.print_type(&**ty))
2417 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2422 pub fn print_ty_fn(&mut self,
2424 unsafety: hir::Unsafety,
2426 name: Option<ast::Ident>,
2427 generics: &hir::Generics,
2428 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2430 try!(self.ibox(indent_unit));
2431 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2432 try!(word(&mut self.s, "for"));
2433 try!(self.print_generics(generics));
2435 let generics = hir::Generics {
2436 lifetimes: Vec::new(),
2437 ty_params: OwnedSlice::empty(),
2438 where_clause: hir::WhereClause {
2439 id: ast::DUMMY_NODE_ID,
2440 predicates: Vec::new(),
2443 try!(self.print_fn(decl,
2445 hir::Constness::NotConst,
2454 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2455 next_pos: Option<BytePos>)
2457 let cm = match self.cm {
2461 match self.next_comment() {
2463 if (*cmnt).style != comments::Trailing { return Ok(()) }
2464 let span_line = cm.lookup_char_pos(span.hi);
2465 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2466 let mut next = (*cmnt).pos + BytePos(1);
2467 match next_pos { None => (), Some(p) => next = p }
2468 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2469 span_line.line == comment_line.line {
2470 try!(self.print_comment(cmnt));
2471 self.cur_cmnt_and_lit.cur_cmnt += 1;
2479 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2480 // If there aren't any remaining comments, then we need to manually
2481 // make sure there is a line break at the end.
2482 if self.next_comment().is_none() {
2483 try!(hardbreak(&mut self.s));
2486 match self.next_comment() {
2488 try!(self.print_comment(cmnt));
2489 self.cur_cmnt_and_lit.cur_cmnt += 1;
2497 pub fn print_literal(&mut self, lit: &hir::Lit) -> io::Result<()> {
2498 try!(self.maybe_print_comment(lit.span.lo));
2499 match self.next_lit(lit.span.lo) {
2501 return word(&mut self.s, &(*ltrl).lit);
2506 hir::LitStr(ref st, style) => self.print_string(&st, style),
2507 hir::LitByte(byte) => {
2508 let mut res = String::from("b'");
2509 res.extend(ascii::escape_default(byte).map(|c| c as char));
2511 word(&mut self.s, &res[..])
2513 hir::LitChar(ch) => {
2514 let mut res = String::from("'");
2515 res.extend(ch.escape_default());
2517 word(&mut self.s, &res[..])
2519 hir::LitInt(i, t) => {
2521 hir::SignedIntLit(st, hir::Plus) => {
2523 &::util::int_ty_to_string(st, Some(i as i64)))
2525 hir::SignedIntLit(st, hir::Minus) => {
2526 let istr = ::util::int_ty_to_string(st, Some(-(i as i64)));
2528 &format!("-{}", istr))
2530 hir::UnsignedIntLit(ut) => {
2531 word(&mut self.s, &::util::uint_ty_to_string(ut, Some(i)))
2533 hir::UnsuffixedIntLit(hir::Plus) => {
2534 word(&mut self.s, &format!("{}", i))
2536 hir::UnsuffixedIntLit(hir::Minus) => {
2537 word(&mut self.s, &format!("-{}", i))
2541 hir::LitFloat(ref f, t) => {
2546 &::util::float_ty_to_string(t)))
2548 hir::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]),
2549 hir::LitBool(val) => {
2550 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2552 hir::LitByteStr(ref v) => {
2553 let mut escaped: String = String::new();
2554 for &ch in v.iter() {
2555 escaped.extend(ascii::escape_default(ch)
2556 .map(|c| c as char));
2558 word(&mut self.s, &format!("b\"{}\"", escaped))
2563 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2564 match self.literals {
2566 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2567 let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2568 if ltrl.pos > pos { return None; }
2569 self.cur_cmnt_and_lit.cur_lit += 1;
2570 if ltrl.pos == pos { return Some(ltrl); }
2578 pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
2580 match self.next_comment() {
2582 if (*cmnt).pos < pos {
2583 try!(self.print_comment(cmnt));
2584 self.cur_cmnt_and_lit.cur_cmnt += 1;
2593 pub fn print_comment(&mut self,
2594 cmnt: &comments::Comment) -> io::Result<()> {
2596 comments::Mixed => {
2597 assert_eq!(cmnt.lines.len(), 1);
2598 try!(zerobreak(&mut self.s));
2599 try!(word(&mut self.s, &cmnt.lines[0]));
2600 zerobreak(&mut self.s)
2602 comments::Isolated => {
2603 try!(self.hardbreak_if_not_bol());
2604 for line in &cmnt.lines {
2605 // Don't print empty lines because they will end up as trailing
2607 if !line.is_empty() {
2608 try!(word(&mut self.s, &line[..]));
2610 try!(hardbreak(&mut self.s));
2614 comments::Trailing => {
2615 try!(word(&mut self.s, " "));
2616 if cmnt.lines.len() == 1 {
2617 try!(word(&mut self.s, &cmnt.lines[0]));
2618 hardbreak(&mut self.s)
2621 for line in &cmnt.lines {
2622 if !line.is_empty() {
2623 try!(word(&mut self.s, &line[..]));
2625 try!(hardbreak(&mut self.s));
2630 comments::BlankLine => {
2631 // We need to do at least one, possibly two hardbreaks.
2632 let is_semi = match self.s.last_token() {
2633 pp::Token::String(s, _) => ";" == s,
2636 if is_semi || self.is_begin() || self.is_end() {
2637 try!(hardbreak(&mut self.s));
2639 hardbreak(&mut self.s)
2644 pub fn print_string(&mut self, st: &str,
2645 style: hir::StrStyle) -> io::Result<()> {
2646 let st = match style {
2648 (format!("\"{}\"", st.escape_default()))
2651 (format!("r{delim}\"{string}\"{delim}",
2652 delim=repeat("#", n),
2656 word(&mut self.s, &st[..])
2659 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2660 match self.comments {
2661 Some(ref cmnts) => {
2662 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2663 Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2672 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2673 opt_abi: Option<abi::Abi>)
2676 Some(abi::Rust) => Ok(()),
2678 try!(self.word_nbsp("extern"));
2679 self.word_nbsp(&abi.to_string())
2685 pub fn print_extern_opt_abi(&mut self,
2686 opt_abi: Option<abi::Abi>) -> io::Result<()> {
2689 try!(self.word_nbsp("extern"));
2690 self.word_nbsp(&abi.to_string())
2696 pub fn print_fn_header_info(&mut self,
2697 unsafety: hir::Unsafety,
2698 constness: hir::Constness,
2700 vis: hir::Visibility) -> io::Result<()> {
2701 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2702 try!(self.print_unsafety(unsafety));
2705 hir::Constness::NotConst => {}
2706 hir::Constness::Const => try!(self.word_nbsp("const"))
2709 if abi != abi::Rust {
2710 try!(self.word_nbsp("extern"));
2711 try!(self.word_nbsp(&abi.to_string()));
2714 word(&mut self.s, "fn")
2717 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2719 hir::Unsafety::Normal => Ok(()),
2720 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2725 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
2727 // Dup'ed from parse::classify, but adapted for the HIR.
2728 /// Does this expression require a semicolon to be treated
2729 /// as a statement? The negation of this: 'can this expression
2730 /// be used as a statement without a semicolon' -- is used
2731 /// as an early-bail-out in the parser so that, for instance,
2732 /// if true {...} else {...}
2734 /// isn't parsed as (if true {...} else {...} | x) | 5
2735 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2738 | hir::ExprMatch(..)
2740 | hir::ExprWhile(..)
2741 | hir::ExprLoop(..) => false,
2746 /// this statement requires a semicolon after it.
2747 /// note that in one case (stmt_semi), we've already
2748 /// seen the semicolon, and thus don't need another.
2749 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2751 hir::StmtDecl(ref d, _) => {
2753 hir::DeclLocal(_) => true,
2754 hir::DeclItem(_) => false
2757 hir::StmtExpr(ref e, _) => { expr_requires_semi_to_be_stmt(&**e) }
2758 hir::StmtSemi(..) => { false }