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::codemap::{self, CodeMap, BytePos, Spanned};
17 use syntax::parse::token::{self, BinOpToken};
18 use syntax::parse::lexer::comments;
20 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
21 use syntax::print::pp::{Breaks, eof};
22 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
23 use syntax::print::pprust::{self as ast_pp, PrintState};
27 use hir::{Crate, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
29 use std::io::{self, Write, Read};
31 pub enum AnnNode<'a> {
32 NodeName(&'a ast::Name),
33 NodeBlock(&'a hir::Block),
34 NodeItem(&'a hir::Item),
35 NodeSubItem(ast::NodeId),
36 NodeExpr(&'a hir::Expr),
37 NodePat(&'a hir::Pat),
41 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
44 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
49 #[derive(Copy, Clone)]
52 impl PpAnn for NoAnn {}
55 pub struct State<'a> {
56 krate: Option<&'a Crate>,
57 pub s: pp::Printer<'a>,
58 cm: Option<&'a CodeMap>,
59 comments: Option<Vec<comments::Comment>>,
60 literals: Option<Vec<comments::Literal>>,
61 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
62 boxes: Vec<pp::Breaks>,
63 ann: &'a (PpAnn + 'a),
66 impl<'a> PrintState<'a> for State<'a> {
67 fn writer(&mut self) -> &mut pp::Printer<'a> {
71 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
75 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
79 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
80 &mut self.cur_cmnt_and_lit
83 fn literals(&self) -> &Option<Vec<comments::Literal>> {
88 pub fn rust_printer<'a>(writer: Box<Write + 'a>, krate: Option<&'a Crate>) -> State<'a> {
89 static NO_ANN: NoAnn = NoAnn;
90 rust_printer_annotated(writer, &NO_ANN, krate)
93 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>,
95 krate: Option<&'a Crate>)
99 s: pp::mk_printer(writer, default_columns),
103 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
112 #[allow(non_upper_case_globals)]
113 pub const indent_unit: usize = 4;
115 #[allow(non_upper_case_globals)]
116 pub const default_columns: usize = 78;
119 /// Requires you to pass an input filename and reader so that
120 /// it can scan the input text for comments and literals to
122 pub fn print_crate<'a>(cm: &'a CodeMap,
123 span_diagnostic: &errors::Handler,
127 out: Box<Write + 'a>,
131 let mut s = State::new_from_input(cm, span_diagnostic, filename, input,
132 out, ann, is_expanded, Some(krate));
134 // When printing the AST, we sometimes need to inject `#[no_std]` here.
135 // Since you can't compile the HIR, it's not necessary.
137 try!(s.print_mod(&krate.module, &krate.attrs));
138 try!(s.print_remaining_comments());
143 pub fn new_from_input(cm: &'a CodeMap,
144 span_diagnostic: &errors::Handler,
147 out: Box<Write + 'a>,
150 krate: Option<&'a Crate>)
152 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
160 // If the code is post expansion, don't use the table of
161 // literals, since it doesn't correspond with the literals
162 // in the AST anymore.
171 pub fn new(cm: &'a CodeMap,
172 out: Box<Write + 'a>,
174 comments: Option<Vec<comments::Comment>>,
175 literals: Option<Vec<comments::Literal>>,
176 krate: Option<&'a Crate>)
180 s: pp::mk_printer(out, default_columns),
182 comments: comments.clone(),
183 literals: literals.clone(),
184 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
194 pub fn to_string<F>(f: F) -> String
195 where F: FnOnce(&mut State) -> io::Result<()>
197 let mut wr = Vec::new();
199 let mut printer = rust_printer(Box::new(&mut wr), None);
200 f(&mut printer).unwrap();
201 eof(&mut printer.s).unwrap();
203 String::from_utf8(wr).unwrap()
206 pub fn binop_to_string(op: BinOpToken) -> &'static str {
212 token::Percent => "%",
221 pub fn ty_to_string(ty: &hir::Ty) -> String {
222 to_string(|s| s.print_type(ty))
225 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
226 to_string(|s| s.print_bounds("", bounds))
229 pub fn pat_to_string(pat: &hir::Pat) -> String {
230 to_string(|s| s.print_pat(pat))
233 pub fn arm_to_string(arm: &hir::Arm) -> String {
234 to_string(|s| s.print_arm(arm))
237 pub fn expr_to_string(e: &hir::Expr) -> String {
238 to_string(|s| s.print_expr(e))
241 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
242 to_string(|s| s.print_lifetime(e))
245 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
246 to_string(|s| s.print_stmt(stmt))
249 pub fn item_to_string(i: &hir::Item) -> String {
250 to_string(|s| s.print_item(i))
253 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
254 to_string(|s| s.print_impl_item(i))
257 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
258 to_string(|s| s.print_trait_item(i))
261 pub fn generics_to_string(generics: &hir::Generics) -> String {
262 to_string(|s| s.print_generics(generics))
265 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
266 to_string(|s| s.print_where_clause(i))
269 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
270 to_string(|s| s.print_fn_block_args(p))
273 pub fn path_to_string(p: &hir::Path) -> String {
274 to_string(|s| s.print_path(p, false, 0))
277 pub fn name_to_string(name: ast::Name) -> String {
278 to_string(|s| s.print_name(name))
281 pub fn fun_to_string(decl: &hir::FnDecl,
282 unsafety: hir::Unsafety,
283 constness: hir::Constness,
285 opt_explicit_self: Option<&hir::ExplicitSelf_>,
286 generics: &hir::Generics)
290 try!(s.print_fn(decl,
298 try!(s.end()); // Close the head box
299 s.end() // Close the outer box
303 pub fn block_to_string(blk: &hir::Block) -> String {
305 // containing cbox, will be closed by print-block at }
306 try!(s.cbox(indent_unit));
307 // head-ibox, will be closed by print-block after {
313 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
314 to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
317 pub fn variant_to_string(var: &hir::Variant) -> String {
318 to_string(|s| s.print_variant(var))
321 pub fn arg_to_string(arg: &hir::Arg) -> String {
322 to_string(|s| s.print_arg(arg, false))
325 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
327 hir::Public => format!("pub {}", s),
328 hir::Inherited => s.to_string(),
332 fn needs_parentheses(expr: &hir::Expr) -> bool {
334 hir::ExprAssign(..) |
335 hir::ExprBinary(..) |
336 hir::ExprClosure(..) |
337 hir::ExprAssignOp(..) |
339 hir::ExprType(..) => true,
345 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
346 self.boxes.push(pp::Breaks::Consistent);
347 pp::cbox(&mut self.s, u)
350 pub fn nbsp(&mut self) -> io::Result<()> {
351 word(&mut self.s, " ")
354 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
355 try!(word(&mut self.s, w));
359 pub fn head(&mut self, w: &str) -> io::Result<()> {
360 // outer-box is consistent
361 try!(self.cbox(indent_unit));
362 // head-box is inconsistent
363 try!(self.ibox(w.len() + 1));
364 // keyword that starts the head
366 try!(self.word_nbsp(w));
371 pub fn bopen(&mut self) -> io::Result<()> {
372 try!(word(&mut self.s, "{"));
373 self.end() // close the head-box
376 pub fn bclose_(&mut self, span: codemap::Span, indented: usize) -> io::Result<()> {
377 self.bclose_maybe_open(span, indented, true)
379 pub fn bclose_maybe_open(&mut self,
384 try!(self.maybe_print_comment(span.hi));
385 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
386 try!(word(&mut self.s, "}"));
388 try!(self.end()); // close the outer-box
392 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
393 self.bclose_(span, indent_unit)
396 pub fn in_cbox(&self) -> bool {
397 match self.boxes.last() {
398 Some(&last_box) => last_box == pp::Breaks::Consistent,
402 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
404 try!(space(&mut self.s));
408 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
410 break_offset(&mut self.s, n, off)
412 if off != 0 && self.s.last_token().is_hardbreak_tok() {
413 // We do something pretty sketchy here: tuck the nonzero
414 // offset-adjustment we were going to deposit along with the
415 // break into the previous hardbreak.
416 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
422 // Synthesizes a comment that was not textually present in the original source
424 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
425 try!(word(&mut self.s, "/*"));
426 try!(space(&mut self.s));
427 try!(word(&mut self.s, &text[..]));
428 try!(space(&mut self.s));
429 word(&mut self.s, "*/")
433 pub fn commasep_cmnt<T, F, G>(&mut self,
439 where F: FnMut(&mut State, &T) -> io::Result<()>,
440 G: FnMut(&T) -> codemap::Span
442 try!(self.rbox(0, b));
443 let len = elts.len();
446 try!(self.maybe_print_comment(get_span(elt).hi));
450 try!(word(&mut self.s, ","));
451 try!(self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi)));
452 try!(self.space_if_not_bol());
458 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<hir::Expr>]) -> io::Result<()> {
459 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
462 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
463 try!(self.print_inner_attributes(attrs));
464 for item_id in &_mod.item_ids {
465 try!(self.print_item_id(item_id));
470 pub fn print_foreign_mod(&mut self,
471 nmod: &hir::ForeignMod,
472 attrs: &[ast::Attribute])
474 try!(self.print_inner_attributes(attrs));
475 for item in &nmod.items {
476 try!(self.print_foreign_item(item));
481 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
482 if let Some(l) = *lifetime {
483 try!(self.print_lifetime(&l));
489 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
490 try!(self.maybe_print_comment(ty.span.lo));
493 hir::TyVec(ref ty) => {
494 try!(word(&mut self.s, "["));
495 try!(self.print_type(&ty));
496 try!(word(&mut self.s, "]"));
498 hir::TyPtr(ref mt) => {
499 try!(word(&mut self.s, "*"));
501 hir::MutMutable => try!(self.word_nbsp("mut")),
502 hir::MutImmutable => try!(self.word_nbsp("const")),
504 try!(self.print_type(&mt.ty));
506 hir::TyRptr(ref lifetime, ref mt) => {
507 try!(word(&mut self.s, "&"));
508 try!(self.print_opt_lifetime(lifetime));
509 try!(self.print_mt(mt));
511 hir::TyTup(ref elts) => {
513 try!(self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty)));
515 try!(word(&mut self.s, ","));
519 hir::TyBareFn(ref f) => {
520 let generics = hir::Generics {
521 lifetimes: f.lifetimes.clone(),
522 ty_params: hir::HirVec::new(),
523 where_clause: hir::WhereClause {
524 id: ast::DUMMY_NODE_ID,
525 predicates: hir::HirVec::new(),
528 try!(self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics, None));
530 hir::TyPath(None, ref path) => {
531 try!(self.print_path(path, false, 0));
533 hir::TyPath(Some(ref qself), ref path) => {
534 try!(self.print_qpath(path, qself, false))
536 hir::TyObjectSum(ref ty, ref bounds) => {
537 try!(self.print_type(&ty));
538 try!(self.print_bounds("+", &bounds[..]));
540 hir::TyPolyTraitRef(ref bounds) => {
541 try!(self.print_bounds("", &bounds[..]));
543 hir::TyFixedLengthVec(ref ty, ref v) => {
544 try!(word(&mut self.s, "["));
545 try!(self.print_type(&ty));
546 try!(word(&mut self.s, "; "));
547 try!(self.print_expr(&v));
548 try!(word(&mut self.s, "]"));
550 hir::TyTypeof(ref e) => {
551 try!(word(&mut self.s, "typeof("));
552 try!(self.print_expr(&e));
553 try!(word(&mut self.s, ")"));
556 try!(word(&mut self.s, "_"));
562 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
563 try!(self.hardbreak_if_not_bol());
564 try!(self.maybe_print_comment(item.span.lo));
565 try!(self.print_outer_attributes(&item.attrs));
567 hir::ForeignItemFn(ref decl, ref generics) => {
569 try!(self.print_fn(decl,
570 hir::Unsafety::Normal,
571 hir::Constness::NotConst,
577 try!(self.end()); // end head-ibox
578 try!(word(&mut self.s, ";"));
579 self.end() // end the outer fn box
581 hir::ForeignItemStatic(ref t, m) => {
582 try!(self.head(&visibility_qualified(item.vis, "static")));
584 try!(self.word_space("mut"));
586 try!(self.print_name(item.name));
587 try!(self.word_space(":"));
588 try!(self.print_type(&t));
589 try!(word(&mut self.s, ";"));
590 try!(self.end()); // end the head-ibox
591 self.end() // end the outer cbox
596 fn print_associated_const(&mut self,
599 default: Option<&hir::Expr>,
600 vis: hir::Visibility)
602 try!(word(&mut self.s, &visibility_qualified(vis, "")));
603 try!(self.word_space("const"));
604 try!(self.print_name(name));
605 try!(self.word_space(":"));
606 try!(self.print_type(ty));
607 if let Some(expr) = default {
608 try!(space(&mut self.s));
609 try!(self.word_space("="));
610 try!(self.print_expr(expr));
612 word(&mut self.s, ";")
615 fn print_associated_type(&mut self,
617 bounds: Option<&hir::TyParamBounds>,
618 ty: Option<&hir::Ty>)
620 try!(self.word_space("type"));
621 try!(self.print_name(name));
622 if let Some(bounds) = bounds {
623 try!(self.print_bounds(":", bounds));
625 if let Some(ty) = ty {
626 try!(space(&mut self.s));
627 try!(self.word_space("="));
628 try!(self.print_type(ty));
630 word(&mut self.s, ";")
633 pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
634 if let Some(krate) = self.krate {
635 // skip nested items if krate context was not provided
636 let item = &krate.items[&item_id.id];
637 self.print_item(item)
643 /// Pretty-print an item
644 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
645 try!(self.hardbreak_if_not_bol());
646 try!(self.maybe_print_comment(item.span.lo));
647 try!(self.print_outer_attributes(&item.attrs));
648 try!(self.ann.pre(self, NodeItem(item)));
650 hir::ItemExternCrate(ref optional_path) => {
651 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
652 if let Some(p) = *optional_path {
653 let val = p.as_str();
654 if val.contains("-") {
655 try!(self.print_string(&val, ast::StrStyle::Cooked));
657 try!(self.print_name(p));
659 try!(space(&mut self.s));
660 try!(word(&mut self.s, "as"));
661 try!(space(&mut self.s));
663 try!(self.print_name(item.name));
664 try!(word(&mut self.s, ";"));
665 try!(self.end()); // end inner head-block
666 try!(self.end()); // end outer head-block
668 hir::ItemUse(ref vp) => {
669 try!(self.head(&visibility_qualified(item.vis, "use")));
670 try!(self.print_view_path(&vp));
671 try!(word(&mut self.s, ";"));
672 try!(self.end()); // end inner head-block
673 try!(self.end()); // end outer head-block
675 hir::ItemStatic(ref ty, m, ref expr) => {
676 try!(self.head(&visibility_qualified(item.vis, "static")));
677 if m == hir::MutMutable {
678 try!(self.word_space("mut"));
680 try!(self.print_name(item.name));
681 try!(self.word_space(":"));
682 try!(self.print_type(&ty));
683 try!(space(&mut self.s));
684 try!(self.end()); // end the head-ibox
686 try!(self.word_space("="));
687 try!(self.print_expr(&expr));
688 try!(word(&mut self.s, ";"));
689 try!(self.end()); // end the outer cbox
691 hir::ItemConst(ref ty, ref expr) => {
692 try!(self.head(&visibility_qualified(item.vis, "const")));
693 try!(self.print_name(item.name));
694 try!(self.word_space(":"));
695 try!(self.print_type(&ty));
696 try!(space(&mut self.s));
697 try!(self.end()); // end the head-ibox
699 try!(self.word_space("="));
700 try!(self.print_expr(&expr));
701 try!(word(&mut self.s, ";"));
702 try!(self.end()); // end the outer cbox
704 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
706 try!(self.print_fn(decl,
714 try!(word(&mut self.s, " "));
715 try!(self.print_block_with_attrs(&body, &item.attrs));
717 hir::ItemMod(ref _mod) => {
718 try!(self.head(&visibility_qualified(item.vis, "mod")));
719 try!(self.print_name(item.name));
722 try!(self.print_mod(_mod, &item.attrs));
723 try!(self.bclose(item.span));
725 hir::ItemForeignMod(ref nmod) => {
726 try!(self.head("extern"));
727 try!(self.word_nbsp(&nmod.abi.to_string()));
729 try!(self.print_foreign_mod(nmod, &item.attrs));
730 try!(self.bclose(item.span));
732 hir::ItemTy(ref ty, ref params) => {
733 try!(self.ibox(indent_unit));
735 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
736 try!(self.print_name(item.name));
737 try!(self.print_generics(params));
738 try!(self.end()); // end the inner ibox
740 try!(self.print_where_clause(¶ms.where_clause));
741 try!(space(&mut self.s));
742 try!(self.word_space("="));
743 try!(self.print_type(&ty));
744 try!(word(&mut self.s, ";"));
745 try!(self.end()); // end the outer ibox
747 hir::ItemEnum(ref enum_definition, ref params) => {
748 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
750 hir::ItemStruct(ref struct_def, ref generics) => {
751 try!(self.head(&visibility_qualified(item.vis, "struct")));
752 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
755 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
757 try!(self.print_visibility(item.vis));
758 try!(self.print_unsafety(unsafety));
759 try!(self.word_nbsp("impl"));
760 try!(self.print_trait_ref(trait_ref));
761 try!(space(&mut self.s));
762 try!(self.word_space("for"));
763 try!(self.word_space(".."));
765 try!(self.bclose(item.span));
767 hir::ItemImpl(unsafety,
774 try!(self.print_visibility(item.vis));
775 try!(self.print_unsafety(unsafety));
776 try!(self.word_nbsp("impl"));
778 if generics.is_parameterized() {
779 try!(self.print_generics(generics));
780 try!(space(&mut self.s));
784 hir::ImplPolarity::Negative => {
785 try!(word(&mut self.s, "!"));
792 try!(self.print_trait_ref(t));
793 try!(space(&mut self.s));
794 try!(self.word_space("for"));
799 try!(self.print_type(&ty));
800 try!(self.print_where_clause(&generics.where_clause));
802 try!(space(&mut self.s));
804 try!(self.print_inner_attributes(&item.attrs));
805 for impl_item in impl_items {
806 try!(self.print_impl_item(impl_item));
808 try!(self.bclose(item.span));
810 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
812 try!(self.print_visibility(item.vis));
813 try!(self.print_unsafety(unsafety));
814 try!(self.word_nbsp("trait"));
815 try!(self.print_name(item.name));
816 try!(self.print_generics(generics));
817 let mut real_bounds = Vec::with_capacity(bounds.len());
818 for b in bounds.iter() {
819 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
820 try!(space(&mut self.s));
821 try!(self.word_space("for ?"));
822 try!(self.print_trait_ref(&ptr.trait_ref));
824 real_bounds.push(b.clone());
827 try!(self.print_bounds(":", &real_bounds[..]));
828 try!(self.print_where_clause(&generics.where_clause));
829 try!(word(&mut self.s, " "));
831 for trait_item in trait_items {
832 try!(self.print_trait_item(trait_item));
834 try!(self.bclose(item.span));
837 self.ann.post(self, NodeItem(item))
840 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
841 self.print_path(&t.path, false, 0)
844 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
845 if !lifetimes.is_empty() {
846 try!(word(&mut self.s, "for<"));
847 let mut comma = false;
848 for lifetime_def in lifetimes {
850 try!(self.word_space(","))
852 try!(self.print_lifetime_def(lifetime_def));
855 try!(word(&mut self.s, ">"));
860 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
861 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
862 self.print_trait_ref(&t.trait_ref)
865 pub fn print_enum_def(&mut self,
866 enum_definition: &hir::EnumDef,
867 generics: &hir::Generics,
870 visibility: hir::Visibility)
872 try!(self.head(&visibility_qualified(visibility, "enum")));
873 try!(self.print_name(name));
874 try!(self.print_generics(generics));
875 try!(self.print_where_clause(&generics.where_clause));
876 try!(space(&mut self.s));
877 self.print_variants(&enum_definition.variants, span)
880 pub fn print_variants(&mut self,
881 variants: &[hir::Variant],
886 try!(self.space_if_not_bol());
887 try!(self.maybe_print_comment(v.span.lo));
888 try!(self.print_outer_attributes(&v.node.attrs));
889 try!(self.ibox(indent_unit));
890 try!(self.print_variant(v));
891 try!(word(&mut self.s, ","));
893 try!(self.maybe_print_trailing_comment(v.span, None));
898 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
900 hir::Public => self.word_nbsp("pub"),
901 hir::Inherited => Ok(()),
905 pub fn print_struct(&mut self,
906 struct_def: &hir::VariantData,
907 generics: &hir::Generics,
910 print_finalizer: bool)
912 try!(self.print_name(name));
913 try!(self.print_generics(generics));
914 if !struct_def.is_struct() {
915 if struct_def.is_tuple() {
917 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
918 match field.node.kind {
919 hir::NamedField(..) => panic!("unexpected named field"),
920 hir::UnnamedField(vis) => {
921 try!(s.print_visibility(vis));
922 try!(s.maybe_print_comment(field.span.lo));
923 s.print_type(&field.node.ty)
929 try!(self.print_where_clause(&generics.where_clause));
931 try!(word(&mut self.s, ";"));
934 self.end() // close the outer-box
936 try!(self.print_where_clause(&generics.where_clause));
939 try!(self.hardbreak_if_not_bol());
941 for field in struct_def.fields() {
942 match field.node.kind {
943 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
944 hir::NamedField(name, visibility) => {
945 try!(self.hardbreak_if_not_bol());
946 try!(self.maybe_print_comment(field.span.lo));
947 try!(self.print_outer_attributes(&field.node.attrs));
948 try!(self.print_visibility(visibility));
949 try!(self.print_name(name));
950 try!(self.word_nbsp(":"));
951 try!(self.print_type(&field.node.ty));
952 try!(word(&mut self.s, ","));
961 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
963 let generics = ::util::empty_generics();
964 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
965 match v.node.disr_expr {
967 try!(space(&mut self.s));
968 try!(self.word_space("="));
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) -> io::Result<()> {
990 try!(self.ann.pre(self, NodeSubItem(ti.id)));
991 try!(self.hardbreak_if_not_bol());
992 try!(self.maybe_print_comment(ti.span.lo));
993 try!(self.print_outer_attributes(&ti.attrs));
995 hir::ConstTraitItem(ref ty, ref default) => {
996 try!(self.print_associated_const(ti.name,
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,
1016 default.as_ref().map(|ty| &**ty)));
1019 self.ann.post(self, NodeSubItem(ti.id))
1022 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1023 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1024 try!(self.hardbreak_if_not_bol());
1025 try!(self.maybe_print_comment(ii.span.lo));
1026 try!(self.print_outer_attributes(&ii.attrs));
1028 hir::ImplItemKind::Const(ref ty, ref expr) => {
1029 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1031 hir::ImplItemKind::Method(ref sig, ref body) => {
1032 try!(self.head(""));
1033 try!(self.print_method_sig(ii.name, sig, ii.vis));
1035 try!(self.print_block_with_attrs(body, &ii.attrs));
1037 hir::ImplItemKind::Type(ref ty) => {
1038 try!(self.print_associated_type(ii.name, None, Some(ty)));
1041 self.ann.post(self, NodeSubItem(ii.id))
1044 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1045 try!(self.maybe_print_comment(st.span.lo));
1047 hir::StmtDecl(ref decl, _) => {
1048 try!(self.print_decl(&decl));
1050 hir::StmtExpr(ref expr, _) => {
1051 try!(self.space_if_not_bol());
1052 try!(self.print_expr(&expr));
1054 hir::StmtSemi(ref expr, _) => {
1055 try!(self.space_if_not_bol());
1056 try!(self.print_expr(&expr));
1057 try!(word(&mut self.s, ";"));
1060 if stmt_ends_with_semi(&st.node) {
1061 try!(word(&mut self.s, ";"));
1063 self.maybe_print_trailing_comment(st.span, None)
1066 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1067 self.print_block_with_attrs(blk, &[])
1070 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1071 self.print_block_unclosed_indent(blk, indent_unit)
1074 pub fn print_block_unclosed_indent(&mut self,
1078 self.print_block_maybe_unclosed(blk, indented, &[], false)
1081 pub fn print_block_with_attrs(&mut self,
1083 attrs: &[ast::Attribute])
1085 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1088 pub fn print_block_maybe_unclosed(&mut self,
1091 attrs: &[ast::Attribute],
1095 hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1096 hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1097 hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1098 hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1099 hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1100 hir::DefaultBlock => (),
1102 try!(self.maybe_print_comment(blk.span.lo));
1103 try!(self.ann.pre(self, NodeBlock(blk)));
1106 try!(self.print_inner_attributes(attrs));
1108 for st in &blk.stmts {
1109 try!(self.print_stmt(st));
1113 try!(self.space_if_not_bol());
1114 try!(self.print_expr(&expr));
1115 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1119 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1120 self.ann.post(self, NodeBlock(blk))
1123 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1127 // "another else-if"
1128 hir::ExprIf(ref i, ref then, ref e) => {
1129 try!(self.cbox(indent_unit - 1));
1131 try!(word(&mut self.s, " else if "));
1132 try!(self.print_expr(&i));
1133 try!(space(&mut self.s));
1134 try!(self.print_block(&then));
1135 self.print_else(e.as_ref().map(|e| &**e))
1138 hir::ExprBlock(ref b) => {
1139 try!(self.cbox(indent_unit - 1));
1141 try!(word(&mut self.s, " else "));
1142 self.print_block(&b)
1144 // BLEAH, constraints would be great here
1146 panic!("print_if saw if with weird alternative");
1154 pub fn print_if(&mut self,
1157 elseopt: Option<&hir::Expr>)
1159 try!(self.head("if"));
1160 try!(self.print_expr(test));
1161 try!(space(&mut self.s));
1162 try!(self.print_block(blk));
1163 self.print_else(elseopt)
1166 pub fn print_if_let(&mut self,
1170 elseopt: Option<&hir::Expr>)
1172 try!(self.head("if let"));
1173 try!(self.print_pat(pat));
1174 try!(space(&mut self.s));
1175 try!(self.word_space("="));
1176 try!(self.print_expr(expr));
1177 try!(space(&mut self.s));
1178 try!(self.print_block(blk));
1179 self.print_else(elseopt)
1183 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1185 try!(self.commasep_exprs(Inconsistent, args));
1189 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1190 let needs_par = needs_parentheses(expr);
1194 try!(self.print_expr(expr));
1196 try!(self.pclose());
1201 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1202 try!(self.ibox(indent_unit));
1203 try!(word(&mut self.s, "["));
1204 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1205 try!(word(&mut self.s, "]"));
1209 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1210 try!(self.ibox(indent_unit));
1211 try!(word(&mut self.s, "["));
1212 try!(self.print_expr(element));
1213 try!(self.word_space(";"));
1214 try!(self.print_expr(count));
1215 try!(word(&mut self.s, "]"));
1219 fn print_expr_struct(&mut self,
1221 fields: &[hir::Field],
1222 wth: &Option<P<hir::Expr>>)
1224 try!(self.print_path(path, true, 0));
1225 try!(word(&mut self.s, "{"));
1226 try!(self.commasep_cmnt(Consistent,
1229 try!(s.ibox(indent_unit));
1230 try!(s.print_name(field.name.node));
1231 try!(s.word_space(":"));
1232 try!(s.print_expr(&field.expr));
1238 try!(self.ibox(indent_unit));
1239 if !fields.is_empty() {
1240 try!(word(&mut self.s, ","));
1241 try!(space(&mut self.s));
1243 try!(word(&mut self.s, ".."));
1244 try!(self.print_expr(&expr));
1247 _ => if !fields.is_empty() {
1248 try!(word(&mut self.s, ","))
1251 try!(word(&mut self.s, "}"));
1255 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1257 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1258 if exprs.len() == 1 {
1259 try!(word(&mut self.s, ","));
1264 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1265 try!(self.print_expr_maybe_paren(func));
1266 self.print_call_post(args)
1269 fn print_expr_method_call(&mut self,
1270 name: Spanned<ast::Name>,
1272 args: &[P<hir::Expr>])
1274 let base_args = &args[1..];
1275 try!(self.print_expr(&args[0]));
1276 try!(word(&mut self.s, "."));
1277 try!(self.print_name(name.node));
1278 if !tys.is_empty() {
1279 try!(word(&mut self.s, "::<"));
1280 try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty)));
1281 try!(word(&mut self.s, ">"));
1283 self.print_call_post(base_args)
1286 fn print_expr_binary(&mut self,
1291 try!(self.print_expr(lhs));
1292 try!(space(&mut self.s));
1293 try!(self.word_space(::util::binop_to_string(op.node)));
1294 self.print_expr(rhs)
1297 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1298 try!(word(&mut self.s, ::util::unop_to_string(op)));
1299 self.print_expr_maybe_paren(expr)
1302 fn print_expr_addr_of(&mut self,
1303 mutability: hir::Mutability,
1306 try!(word(&mut self.s, "&"));
1307 try!(self.print_mutability(mutability));
1308 self.print_expr_maybe_paren(expr)
1311 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1312 try!(self.maybe_print_comment(expr.span.lo));
1313 try!(self.ibox(indent_unit));
1314 try!(self.ann.pre(self, NodeExpr(expr)));
1316 hir::ExprBox(ref expr) => {
1317 try!(self.word_space("box"));
1318 try!(self.print_expr(expr));
1320 hir::ExprVec(ref exprs) => {
1321 try!(self.print_expr_vec(&exprs[..]));
1323 hir::ExprRepeat(ref element, ref count) => {
1324 try!(self.print_expr_repeat(&element, &count));
1326 hir::ExprStruct(ref path, ref fields, ref wth) => {
1327 try!(self.print_expr_struct(path, &fields[..], wth));
1329 hir::ExprTup(ref exprs) => {
1330 try!(self.print_expr_tup(&exprs[..]));
1332 hir::ExprCall(ref func, ref args) => {
1333 try!(self.print_expr_call(&func, &args[..]));
1335 hir::ExprMethodCall(name, ref tys, ref args) => {
1336 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1338 hir::ExprBinary(op, ref lhs, ref rhs) => {
1339 try!(self.print_expr_binary(op, &lhs, &rhs));
1341 hir::ExprUnary(op, ref expr) => {
1342 try!(self.print_expr_unary(op, &expr));
1344 hir::ExprAddrOf(m, ref expr) => {
1345 try!(self.print_expr_addr_of(m, &expr));
1347 hir::ExprLit(ref lit) => {
1348 try!(self.print_literal(&lit));
1350 hir::ExprCast(ref expr, ref ty) => {
1351 try!(self.print_expr(&expr));
1352 try!(space(&mut self.s));
1353 try!(self.word_space("as"));
1354 try!(self.print_type(&ty));
1356 hir::ExprType(ref expr, ref ty) => {
1357 try!(self.print_expr(&expr));
1358 try!(self.word_space(":"));
1359 try!(self.print_type(&ty));
1361 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1362 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
1364 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1365 if let Some(ident) = opt_ident {
1366 try!(self.print_name(ident.name));
1367 try!(self.word_space(":"));
1369 try!(self.head("while"));
1370 try!(self.print_expr(&test));
1371 try!(space(&mut self.s));
1372 try!(self.print_block(&blk));
1374 hir::ExprLoop(ref blk, opt_ident) => {
1375 if let Some(ident) = opt_ident {
1376 try!(self.print_name(ident.name));
1377 try!(self.word_space(":"));
1379 try!(self.head("loop"));
1380 try!(space(&mut self.s));
1381 try!(self.print_block(&blk));
1383 hir::ExprMatch(ref expr, ref arms, _) => {
1384 try!(self.cbox(indent_unit));
1386 try!(self.word_nbsp("match"));
1387 try!(self.print_expr(&expr));
1388 try!(space(&mut self.s));
1391 try!(self.print_arm(arm));
1393 try!(self.bclose_(expr.span, indent_unit));
1395 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1396 try!(self.print_capture_clause(capture_clause));
1398 try!(self.print_fn_block_args(&decl));
1399 try!(space(&mut self.s));
1401 let default_return = match decl.output {
1402 hir::DefaultReturn(..) => true,
1406 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1407 try!(self.print_block_unclosed(&body));
1409 // we extract the block, so as not to create another set of boxes
1410 match body.expr.as_ref().unwrap().node {
1411 hir::ExprBlock(ref blk) => {
1412 try!(self.print_block_unclosed(&blk));
1415 // this is a bare expression
1416 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1417 try!(self.end()); // need to close a box
1421 // a box will be closed by print_expr, but we didn't want an overall
1422 // wrapper so we closed the corresponding opening. so create an
1423 // empty box to satisfy the close.
1426 hir::ExprBlock(ref blk) => {
1427 // containing cbox, will be closed by print-block at }
1428 try!(self.cbox(indent_unit));
1429 // head-box, will be closed by print-block after {
1431 try!(self.print_block(&blk));
1433 hir::ExprAssign(ref lhs, ref rhs) => {
1434 try!(self.print_expr(&lhs));
1435 try!(space(&mut self.s));
1436 try!(self.word_space("="));
1437 try!(self.print_expr(&rhs));
1439 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1440 try!(self.print_expr(&lhs));
1441 try!(space(&mut self.s));
1442 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1443 try!(self.word_space("="));
1444 try!(self.print_expr(&rhs));
1446 hir::ExprField(ref expr, name) => {
1447 try!(self.print_expr(&expr));
1448 try!(word(&mut self.s, "."));
1449 try!(self.print_name(name.node));
1451 hir::ExprTupField(ref expr, id) => {
1452 try!(self.print_expr(&expr));
1453 try!(word(&mut self.s, "."));
1454 try!(self.print_usize(id.node));
1456 hir::ExprIndex(ref expr, ref index) => {
1457 try!(self.print_expr(&expr));
1458 try!(word(&mut self.s, "["));
1459 try!(self.print_expr(&index));
1460 try!(word(&mut self.s, "]"));
1462 hir::ExprRange(ref start, ref end) => {
1463 if let &Some(ref e) = start {
1464 try!(self.print_expr(&e));
1466 try!(word(&mut self.s, ".."));
1467 if let &Some(ref e) = end {
1468 try!(self.print_expr(&e));
1471 hir::ExprPath(None, ref path) => {
1472 try!(self.print_path(path, true, 0))
1474 hir::ExprPath(Some(ref qself), ref path) => {
1475 try!(self.print_qpath(path, qself, true))
1477 hir::ExprBreak(opt_ident) => {
1478 try!(word(&mut self.s, "break"));
1479 try!(space(&mut self.s));
1480 if let Some(ident) = opt_ident {
1481 try!(self.print_name(ident.node.name));
1482 try!(space(&mut self.s));
1485 hir::ExprAgain(opt_ident) => {
1486 try!(word(&mut self.s, "continue"));
1487 try!(space(&mut self.s));
1488 if let Some(ident) = opt_ident {
1489 try!(self.print_name(ident.node.name));
1490 try!(space(&mut self.s))
1493 hir::ExprRet(ref result) => {
1494 try!(word(&mut self.s, "return"));
1497 try!(word(&mut self.s, " "));
1498 try!(self.print_expr(&expr));
1503 hir::ExprInlineAsm(ref a) => {
1504 try!(word(&mut self.s, "asm!"));
1506 try!(self.print_string(&a.asm, a.asm_str_style));
1507 try!(self.word_space(":"));
1509 try!(self.commasep(Inconsistent, &a.outputs, |s, out| {
1510 match out.constraint.slice_shift_char() {
1511 Some(('=', operand)) if out.is_rw => {
1512 try!(s.print_string(&format!("+{}", operand), ast::StrStyle::Cooked))
1514 _ => try!(s.print_string(&out.constraint, ast::StrStyle::Cooked)),
1517 try!(s.print_expr(&out.expr));
1521 try!(space(&mut self.s));
1522 try!(self.word_space(":"));
1524 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1525 try!(s.print_string(&co, ast::StrStyle::Cooked));
1527 try!(s.print_expr(&o));
1531 try!(space(&mut self.s));
1532 try!(self.word_space(":"));
1534 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1535 try!(s.print_string(&co, ast::StrStyle::Cooked));
1539 let mut options = vec![];
1541 options.push("volatile");
1544 options.push("alignstack");
1546 if a.dialect == ast::AsmDialect::Intel {
1547 options.push("intel");
1550 if !options.is_empty() {
1551 try!(space(&mut self.s));
1552 try!(self.word_space(":"));
1553 try!(self.commasep(Inconsistent, &options, |s, &co| {
1554 try!(s.print_string(co, ast::StrStyle::Cooked));
1559 try!(self.pclose());
1562 try!(self.ann.post(self, NodeExpr(expr)));
1566 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1567 try!(self.print_pat(&loc.pat));
1568 if let Some(ref ty) = loc.ty {
1569 try!(self.word_space(":"));
1570 try!(self.print_type(&ty));
1575 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1576 try!(self.maybe_print_comment(decl.span.lo));
1578 hir::DeclLocal(ref loc) => {
1579 try!(self.space_if_not_bol());
1580 try!(self.ibox(indent_unit));
1581 try!(self.word_nbsp("let"));
1583 try!(self.ibox(indent_unit));
1584 try!(self.print_local_decl(&loc));
1586 if let Some(ref init) = loc.init {
1588 try!(self.word_space("="));
1589 try!(self.print_expr(&init));
1593 hir::DeclItem(ref item) => {
1594 self.print_item_id(item)
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, coll: &hir::Expr) -> io::Result<()> {
1609 try!(self.print_local_decl(loc));
1610 try!(space(&mut self.s));
1611 try!(self.word_space("in"));
1612 self.print_expr(coll)
1615 fn print_path(&mut self,
1617 colons_before_params: bool,
1620 try!(self.maybe_print_comment(path.span.lo));
1622 let mut first = !path.global;
1623 for segment in &path.segments[..path.segments.len() - depth] {
1627 try!(word(&mut self.s, "::"))
1630 try!(self.print_name(segment.identifier.name));
1632 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1638 fn print_qpath(&mut self,
1641 colons_before_params: bool)
1643 try!(word(&mut self.s, "<"));
1644 try!(self.print_type(&qself.ty));
1645 if qself.position > 0 {
1646 try!(space(&mut self.s));
1647 try!(self.word_space("as"));
1648 let depth = path.segments.len() - qself.position;
1649 try!(self.print_path(&path, false, depth));
1651 try!(word(&mut self.s, ">"));
1652 try!(word(&mut self.s, "::"));
1653 let item_segment = path.segments.last().unwrap();
1654 try!(self.print_name(item_segment.identifier.name));
1655 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1658 fn print_path_parameters(&mut self,
1659 parameters: &hir::PathParameters,
1660 colons_before_params: bool)
1662 if parameters.is_empty() {
1666 if colons_before_params {
1667 try!(word(&mut self.s, "::"))
1671 hir::AngleBracketedParameters(ref data) => {
1672 try!(word(&mut self.s, "<"));
1674 let mut comma = false;
1675 for lifetime in &data.lifetimes {
1677 try!(self.word_space(","))
1679 try!(self.print_lifetime(lifetime));
1683 if !data.types.is_empty() {
1685 try!(self.word_space(","))
1687 try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty)));
1691 for binding in data.bindings.iter() {
1693 try!(self.word_space(","))
1695 try!(self.print_name(binding.name));
1696 try!(space(&mut self.s));
1697 try!(self.word_space("="));
1698 try!(self.print_type(&binding.ty));
1702 try!(word(&mut self.s, ">"))
1705 hir::ParenthesizedParameters(ref data) => {
1706 try!(word(&mut self.s, "("));
1707 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty)));
1708 try!(word(&mut self.s, ")"));
1713 try!(self.space_if_not_bol());
1714 try!(self.word_space("->"));
1715 try!(self.print_type(&ty));
1724 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1725 try!(self.maybe_print_comment(pat.span.lo));
1726 try!(self.ann.pre(self, NodePat(pat)));
1727 // Pat isn't normalized, but the beauty of it
1728 // is that it doesn't matter
1730 hir::PatWild => try!(word(&mut self.s, "_")),
1731 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1732 match binding_mode {
1733 hir::BindByRef(mutbl) => {
1734 try!(self.word_nbsp("ref"));
1735 try!(self.print_mutability(mutbl));
1737 hir::BindByValue(hir::MutImmutable) => {}
1738 hir::BindByValue(hir::MutMutable) => {
1739 try!(self.word_nbsp("mut"));
1742 try!(self.print_name(path1.node.name));
1745 try!(word(&mut self.s, "@"));
1746 try!(self.print_pat(&p));
1751 hir::PatEnum(ref path, ref args_) => {
1752 try!(self.print_path(path, true, 0));
1754 None => try!(word(&mut self.s, "(..)")),
1756 if !args.is_empty() {
1758 try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&p)));
1759 try!(self.pclose());
1764 hir::PatQPath(ref qself, ref path) => {
1765 try!(self.print_qpath(path, qself, false));
1767 hir::PatStruct(ref path, ref fields, etc) => {
1768 try!(self.print_path(path, true, 0));
1770 try!(self.word_space("{"));
1771 try!(self.commasep_cmnt(Consistent,
1774 try!(s.cbox(indent_unit));
1775 if !f.node.is_shorthand {
1776 try!(s.print_name(f.node.name));
1777 try!(s.word_nbsp(":"));
1779 try!(s.print_pat(&f.node.pat));
1782 |f| f.node.pat.span));
1784 if !fields.is_empty() {
1785 try!(self.word_space(","));
1787 try!(word(&mut self.s, ".."));
1789 try!(space(&mut self.s));
1790 try!(word(&mut self.s, "}"));
1792 hir::PatTup(ref elts) => {
1794 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
1795 if elts.len() == 1 {
1796 try!(word(&mut self.s, ","));
1798 try!(self.pclose());
1800 hir::PatBox(ref inner) => {
1801 try!(word(&mut self.s, "box "));
1802 try!(self.print_pat(&inner));
1804 hir::PatRegion(ref inner, mutbl) => {
1805 try!(word(&mut self.s, "&"));
1806 if mutbl == hir::MutMutable {
1807 try!(word(&mut self.s, "mut "));
1809 try!(self.print_pat(&inner));
1811 hir::PatLit(ref e) => try!(self.print_expr(&e)),
1812 hir::PatRange(ref begin, ref end) => {
1813 try!(self.print_expr(&begin));
1814 try!(space(&mut self.s));
1815 try!(word(&mut self.s, "..."));
1816 try!(self.print_expr(&end));
1818 hir::PatVec(ref before, ref slice, ref after) => {
1819 try!(word(&mut self.s, "["));
1820 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p)));
1821 if let Some(ref p) = *slice {
1822 if !before.is_empty() {
1823 try!(self.word_space(","));
1825 if p.node != hir::PatWild {
1826 try!(self.print_pat(&p));
1828 try!(word(&mut self.s, ".."));
1829 if !after.is_empty() {
1830 try!(self.word_space(","));
1833 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p)));
1834 try!(word(&mut self.s, "]"));
1837 self.ann.post(self, NodePat(pat))
1840 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1841 // I have no idea why this check is necessary, but here it
1843 if arm.attrs.is_empty() {
1844 try!(space(&mut self.s));
1846 try!(self.cbox(indent_unit));
1848 try!(self.print_outer_attributes(&arm.attrs));
1849 let mut first = true;
1850 for p in &arm.pats {
1854 try!(space(&mut self.s));
1855 try!(self.word_space("|"));
1857 try!(self.print_pat(&p));
1859 try!(space(&mut self.s));
1860 if let Some(ref e) = arm.guard {
1861 try!(self.word_space("if"));
1862 try!(self.print_expr(&e));
1863 try!(space(&mut self.s));
1865 try!(self.word_space("=>"));
1867 match arm.body.node {
1868 hir::ExprBlock(ref blk) => {
1869 // the block will close the pattern's ibox
1870 try!(self.print_block_unclosed_indent(&blk, indent_unit));
1872 // If it is a user-provided unsafe block, print a comma after it
1873 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1874 try!(word(&mut self.s, ","));
1878 try!(self.end()); // close the ibox for the pattern
1879 try!(self.print_expr(&arm.body));
1880 try!(word(&mut self.s, ","));
1883 self.end() // close enclosing cbox
1886 // Returns whether it printed anything
1887 fn print_explicit_self(&mut self,
1888 explicit_self: &hir::ExplicitSelf_,
1889 mutbl: hir::Mutability)
1890 -> io::Result<bool> {
1891 try!(self.print_mutability(mutbl));
1892 match *explicit_self {
1893 hir::SelfStatic => {
1896 hir::SelfValue(_) => {
1897 try!(word(&mut self.s, "self"));
1899 hir::SelfRegion(ref lt, m, _) => {
1900 try!(word(&mut self.s, "&"));
1901 try!(self.print_opt_lifetime(lt));
1902 try!(self.print_mutability(m));
1903 try!(word(&mut self.s, "self"));
1905 hir::SelfExplicit(ref typ, _) => {
1906 try!(word(&mut self.s, "self"));
1907 try!(self.word_space(":"));
1908 try!(self.print_type(&typ));
1914 pub fn print_fn(&mut self,
1916 unsafety: hir::Unsafety,
1917 constness: hir::Constness,
1919 name: Option<ast::Name>,
1920 generics: &hir::Generics,
1921 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1922 vis: hir::Visibility)
1924 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1926 if let Some(name) = name {
1928 try!(self.print_name(name));
1930 try!(self.print_generics(generics));
1931 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1932 self.print_where_clause(&generics.where_clause)
1935 pub fn print_fn_args(&mut self,
1937 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1940 // It is unfortunate to duplicate the commasep logic, but we want the
1941 // self type and the args all in the same box.
1942 try!(self.rbox(0, Inconsistent));
1943 let mut first = true;
1944 if let Some(explicit_self) = opt_explicit_self {
1945 let m = match explicit_self {
1946 &hir::SelfStatic => hir::MutImmutable,
1947 _ => match decl.inputs[0].pat.node {
1948 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1949 _ => hir::MutImmutable,
1952 first = !try!(self.print_explicit_self(explicit_self, m));
1955 // HACK(eddyb) ignore the separately printed self argument.
1956 let args = if first {
1966 try!(self.word_space(","));
1968 try!(self.print_arg(arg, is_closure));
1974 pub fn print_fn_args_and_ret(&mut self,
1976 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1979 try!(self.print_fn_args(decl, opt_explicit_self, false));
1981 try!(word(&mut self.s, ", ..."));
1983 try!(self.pclose());
1985 self.print_fn_output(decl)
1988 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1989 try!(word(&mut self.s, "|"));
1990 try!(self.print_fn_args(decl, None, true));
1991 try!(word(&mut self.s, "|"));
1993 if let hir::DefaultReturn(..) = decl.output {
1997 try!(self.space_if_not_bol());
1998 try!(self.word_space("->"));
2000 hir::Return(ref ty) => {
2001 try!(self.print_type(&ty));
2002 self.maybe_print_comment(ty.span.lo)
2004 hir::DefaultReturn(..) => unreachable!(),
2005 hir::NoReturn(span) => {
2006 try!(self.word_nbsp("!"));
2007 self.maybe_print_comment(span.lo)
2012 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2013 match capture_clause {
2014 hir::CaptureByValue => self.word_space("move"),
2015 hir::CaptureByRef => Ok(()),
2019 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
2020 if !bounds.is_empty() {
2021 try!(word(&mut self.s, prefix));
2022 let mut first = true;
2023 for bound in bounds {
2028 try!(self.word_space("+"));
2032 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2033 self.print_poly_trait_ref(tref)
2035 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2036 try!(word(&mut self.s, "?"));
2037 self.print_poly_trait_ref(tref)
2039 RegionTyParamBound(ref lt) => {
2040 self.print_lifetime(lt)
2050 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2051 self.print_name(lifetime.name)
2054 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2055 try!(self.print_lifetime(&lifetime.lifetime));
2057 for v in &lifetime.bounds {
2058 try!(word(&mut self.s, sep));
2059 try!(self.print_lifetime(v));
2065 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2066 let total = generics.lifetimes.len() + generics.ty_params.len();
2071 try!(word(&mut self.s, "<"));
2073 let mut ints = Vec::new();
2078 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2079 if idx < generics.lifetimes.len() {
2080 let lifetime = &generics.lifetimes[idx];
2081 s.print_lifetime_def(lifetime)
2083 let idx = idx - generics.lifetimes.len();
2084 let param = &generics.ty_params[idx];
2085 s.print_ty_param(param)
2089 try!(word(&mut self.s, ">"));
2093 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2094 try!(self.print_name(param.name));
2095 try!(self.print_bounds(":", ¶m.bounds));
2096 match param.default {
2097 Some(ref default) => {
2098 try!(space(&mut self.s));
2099 try!(self.word_space("="));
2100 self.print_type(&default)
2106 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2107 if where_clause.predicates.is_empty() {
2111 try!(space(&mut self.s));
2112 try!(self.word_space("where"));
2114 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2116 try!(self.word_space(","));
2120 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2124 try!(self.print_formal_lifetime_list(bound_lifetimes));
2125 try!(self.print_type(&bounded_ty));
2126 try!(self.print_bounds(":", bounds));
2128 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2131 try!(self.print_lifetime(lifetime));
2132 try!(word(&mut self.s, ":"));
2134 for (i, bound) in bounds.iter().enumerate() {
2135 try!(self.print_lifetime(bound));
2138 try!(word(&mut self.s, ":"));
2142 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2143 try!(self.print_path(path, false, 0));
2144 try!(space(&mut self.s));
2145 try!(self.word_space("="));
2146 try!(self.print_type(&ty));
2154 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2156 hir::ViewPathSimple(name, ref path) => {
2157 try!(self.print_path(path, false, 0));
2159 if path.segments.last().unwrap().identifier.name != name {
2160 try!(space(&mut self.s));
2161 try!(self.word_space("as"));
2162 try!(self.print_name(name));
2168 hir::ViewPathGlob(ref path) => {
2169 try!(self.print_path(path, false, 0));
2170 word(&mut self.s, "::*")
2173 hir::ViewPathList(ref path, ref segments) => {
2174 if path.segments.is_empty() {
2175 try!(word(&mut self.s, "{"));
2177 try!(self.print_path(path, false, 0));
2178 try!(word(&mut self.s, "::{"));
2180 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2182 hir::PathListIdent { name, .. } => {
2185 hir::PathListMod { .. } => {
2186 word(&mut s.s, "self")
2190 word(&mut self.s, "}")
2195 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2197 hir::MutMutable => self.word_nbsp("mut"),
2198 hir::MutImmutable => Ok(()),
2202 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2203 try!(self.print_mutability(mt.mutbl));
2204 self.print_type(&mt.ty)
2207 pub fn print_arg(&mut self, input: &hir::Arg, is_closure: bool) -> io::Result<()> {
2208 try!(self.ibox(indent_unit));
2209 match input.ty.node {
2210 hir::TyInfer if is_closure => try!(self.print_pat(&input.pat)),
2212 match input.pat.node {
2213 hir::PatIdent(_, ref path1, _) if
2215 parse::token::special_idents::invalid.name => {
2219 try!(self.print_pat(&input.pat));
2220 try!(word(&mut self.s, ":"));
2221 try!(space(&mut self.s));
2224 try!(self.print_type(&input.ty));
2230 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2231 if let hir::DefaultReturn(..) = decl.output {
2235 try!(self.space_if_not_bol());
2236 try!(self.ibox(indent_unit));
2237 try!(self.word_space("->"));
2239 hir::NoReturn(_) => try!(self.word_nbsp("!")),
2240 hir::DefaultReturn(..) => unreachable!(),
2241 hir::Return(ref ty) => try!(self.print_type(&ty)),
2246 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2251 pub fn print_ty_fn(&mut self,
2253 unsafety: hir::Unsafety,
2255 name: Option<ast::Name>,
2256 generics: &hir::Generics,
2257 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2259 try!(self.ibox(indent_unit));
2260 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2261 try!(word(&mut self.s, "for"));
2262 try!(self.print_generics(generics));
2264 let generics = hir::Generics {
2265 lifetimes: hir::HirVec::new(),
2266 ty_params: hir::HirVec::new(),
2267 where_clause: hir::WhereClause {
2268 id: ast::DUMMY_NODE_ID,
2269 predicates: hir::HirVec::new(),
2272 try!(self.print_fn(decl,
2274 hir::Constness::NotConst,
2283 pub fn maybe_print_trailing_comment(&mut self,
2284 span: codemap::Span,
2285 next_pos: Option<BytePos>)
2287 let cm = match self.cm {
2291 match self.next_comment() {
2293 if (*cmnt).style != comments::Trailing {
2296 let span_line = cm.lookup_char_pos(span.hi);
2297 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2298 let mut next = (*cmnt).pos + BytePos(1);
2301 Some(p) => next = p,
2303 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2304 span_line.line == comment_line.line {
2305 try!(self.print_comment(cmnt));
2306 self.cur_cmnt_and_lit.cur_cmnt += 1;
2314 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2315 // If there aren't any remaining comments, then we need to manually
2316 // make sure there is a line break at the end.
2317 if self.next_comment().is_none() {
2318 try!(hardbreak(&mut self.s));
2321 match self.next_comment() {
2323 try!(self.print_comment(cmnt));
2324 self.cur_cmnt_and_lit.cur_cmnt += 1;
2332 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2333 opt_abi: Option<Abi>)
2336 Some(Abi::Rust) => Ok(()),
2338 try!(self.word_nbsp("extern"));
2339 self.word_nbsp(&abi.to_string())
2345 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2348 try!(self.word_nbsp("extern"));
2349 self.word_nbsp(&abi.to_string())
2355 pub fn print_fn_header_info(&mut self,
2356 unsafety: hir::Unsafety,
2357 constness: hir::Constness,
2359 vis: hir::Visibility)
2361 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2362 try!(self.print_unsafety(unsafety));
2365 hir::Constness::NotConst => {}
2366 hir::Constness::Const => try!(self.word_nbsp("const")),
2369 if abi != Abi::Rust {
2370 try!(self.word_nbsp("extern"));
2371 try!(self.word_nbsp(&abi.to_string()));
2374 word(&mut self.s, "fn")
2377 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2379 hir::Unsafety::Normal => Ok(()),
2380 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2385 // Dup'ed from parse::classify, but adapted for the HIR.
2386 /// Does this expression require a semicolon to be treated
2387 /// as a statement? The negation of this: 'can this expression
2388 /// be used as a statement without a semicolon' -- is used
2389 /// as an early-bail-out in the parser so that, for instance,
2390 /// if true {...} else {...}
2392 /// isn't parsed as (if true {...} else {...} | x) | 5
2393 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2396 hir::ExprMatch(..) |
2398 hir::ExprWhile(..) |
2399 hir::ExprLoop(..) => false,
2404 /// this statement requires a semicolon after it.
2405 /// note that in one case (stmt_semi), we've already
2406 /// seen the semicolon, and thus don't need another.
2407 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2409 hir::StmtDecl(ref d, _) => {
2411 hir::DeclLocal(_) => true,
2412 hir::DeclItem(_) => false,
2415 hir::StmtExpr(ref e, _) => {
2416 expr_requires_semi_to_be_stmt(&e)
2418 hir::StmtSemi(..) => {