1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
15 use syntax::owned_slice::OwnedSlice;
16 use syntax::codemap::{self, CodeMap, BytePos, Spanned};
17 use syntax::diagnostic;
18 use syntax::parse::token::{self, BinOpToken};
19 use syntax::parse::lexer::comments;
21 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
22 use syntax::print::pp::{Breaks, eof};
23 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
24 use syntax::print::pprust::{self as ast_pp, PrintState};
28 use hir::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
30 use std::io::{self, Write, Read};
32 pub enum AnnNode<'a> {
33 NodeName(&'a ast::Name),
34 NodeBlock(&'a hir::Block),
35 NodeItem(&'a hir::Item),
36 NodeSubItem(ast::NodeId),
37 NodeExpr(&'a hir::Expr),
38 NodePat(&'a hir::Pat),
42 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
45 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
50 #[derive(Copy, Clone)]
53 impl PpAnn for NoAnn {}
56 pub struct State<'a> {
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>) -> State<'a> {
89 static NO_ANN: NoAnn = NoAnn;
90 rust_printer_annotated(writer, &NO_ANN)
93 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>, ann: &'a PpAnn) -> State<'a> {
95 s: pp::mk_printer(writer, default_columns),
99 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
108 #[allow(non_upper_case_globals)]
109 pub const indent_unit: usize = 4;
111 #[allow(non_upper_case_globals)]
112 pub const default_columns: usize = 78;
115 /// Requires you to pass an input filename and reader so that
116 /// it can scan the input text for comments and literals to
118 pub fn print_crate<'a>(cm: &'a CodeMap,
119 span_diagnostic: &diagnostic::SpanHandler,
123 out: Box<Write + 'a>,
127 let mut s = State::new_from_input(cm, span_diagnostic, filename, input, out, ann, is_expanded);
129 // When printing the AST, we sometimes need to inject `#[no_std]` here.
130 // Since you can't compile the HIR, it's not necessary.
132 try!(s.print_mod(&krate.module, &krate.attrs));
133 try!(s.print_remaining_comments());
138 pub fn new_from_input(cm: &'a CodeMap,
139 span_diagnostic: &diagnostic::SpanHandler,
142 out: Box<Write + 'a>,
146 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
154 // If the code is post expansion, don't use the table of
155 // literals, since it doesn't correspond with the literals
156 // in the AST anymore.
164 pub fn new(cm: &'a CodeMap,
165 out: Box<Write + 'a>,
167 comments: Option<Vec<comments::Comment>>,
168 literals: Option<Vec<comments::Literal>>)
171 s: pp::mk_printer(out, default_columns),
173 comments: comments.clone(),
174 literals: literals.clone(),
175 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
185 pub fn to_string<F>(f: F) -> String
186 where F: FnOnce(&mut State) -> io::Result<()>
188 let mut wr = Vec::new();
190 let mut printer = rust_printer(Box::new(&mut wr));
191 f(&mut printer).unwrap();
192 eof(&mut printer.s).unwrap();
194 String::from_utf8(wr).unwrap()
197 pub fn binop_to_string(op: BinOpToken) -> &'static str {
203 token::Percent => "%",
212 pub fn ty_to_string(ty: &hir::Ty) -> String {
213 to_string(|s| s.print_type(ty))
216 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
217 to_string(|s| s.print_bounds("", bounds))
220 pub fn pat_to_string(pat: &hir::Pat) -> String {
221 to_string(|s| s.print_pat(pat))
224 pub fn arm_to_string(arm: &hir::Arm) -> String {
225 to_string(|s| s.print_arm(arm))
228 pub fn expr_to_string(e: &hir::Expr) -> String {
229 to_string(|s| s.print_expr(e))
232 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
233 to_string(|s| s.print_lifetime(e))
236 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
237 to_string(|s| s.print_stmt(stmt))
240 pub fn item_to_string(i: &hir::Item) -> String {
241 to_string(|s| s.print_item(i))
244 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
245 to_string(|s| s.print_impl_item(i))
248 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
249 to_string(|s| s.print_trait_item(i))
252 pub fn generics_to_string(generics: &hir::Generics) -> String {
253 to_string(|s| s.print_generics(generics))
256 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
257 to_string(|s| s.print_where_clause(i))
260 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
261 to_string(|s| s.print_fn_block_args(p))
264 pub fn path_to_string(p: &hir::Path) -> String {
265 to_string(|s| s.print_path(p, false, 0))
268 pub fn name_to_string(name: ast::Name) -> String {
269 to_string(|s| s.print_name(name))
272 pub fn fun_to_string(decl: &hir::FnDecl,
273 unsafety: hir::Unsafety,
274 constness: hir::Constness,
276 opt_explicit_self: Option<&hir::ExplicitSelf_>,
277 generics: &hir::Generics)
281 try!(s.print_fn(decl,
289 try!(s.end()); // Close the head box
290 s.end() // Close the outer box
294 pub fn block_to_string(blk: &hir::Block) -> String {
296 // containing cbox, will be closed by print-block at }
297 try!(s.cbox(indent_unit));
298 // head-ibox, will be closed by print-block after {
304 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
305 to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
308 pub fn variant_to_string(var: &hir::Variant) -> String {
309 to_string(|s| s.print_variant(var))
312 pub fn arg_to_string(arg: &hir::Arg) -> String {
313 to_string(|s| s.print_arg(arg))
316 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
318 hir::Public => format!("pub {}", s),
319 hir::Inherited => s.to_string(),
323 fn needs_parentheses(expr: &hir::Expr) -> bool {
325 hir::ExprAssign(..) |
326 hir::ExprBinary(..) |
327 hir::ExprClosure(..) |
328 hir::ExprAssignOp(..) |
329 hir::ExprCast(..) => true,
335 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
336 self.boxes.push(pp::Breaks::Consistent);
337 pp::cbox(&mut self.s, u)
340 pub fn nbsp(&mut self) -> io::Result<()> {
341 word(&mut self.s, " ")
344 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
345 try!(word(&mut self.s, w));
349 pub fn head(&mut self, w: &str) -> io::Result<()> {
350 // outer-box is consistent
351 try!(self.cbox(indent_unit));
352 // head-box is inconsistent
353 try!(self.ibox(w.len() + 1));
354 // keyword that starts the head
356 try!(self.word_nbsp(w));
361 pub fn bopen(&mut self) -> io::Result<()> {
362 try!(word(&mut self.s, "{"));
363 self.end() // close the head-box
366 pub fn bclose_(&mut self, span: codemap::Span, indented: usize) -> io::Result<()> {
367 self.bclose_maybe_open(span, indented, true)
369 pub fn bclose_maybe_open(&mut self,
374 try!(self.maybe_print_comment(span.hi));
375 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
376 try!(word(&mut self.s, "}"));
378 try!(self.end()); // close the outer-box
382 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
383 self.bclose_(span, indent_unit)
386 pub fn in_cbox(&self) -> bool {
387 match self.boxes.last() {
388 Some(&last_box) => last_box == pp::Breaks::Consistent,
392 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
394 try!(space(&mut self.s));
398 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
400 break_offset(&mut self.s, n, off)
402 if off != 0 && self.s.last_token().is_hardbreak_tok() {
403 // We do something pretty sketchy here: tuck the nonzero
404 // offset-adjustment we were going to deposit along with the
405 // break into the previous hardbreak.
406 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
412 // Synthesizes a comment that was not textually present in the original source
414 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
415 try!(word(&mut self.s, "/*"));
416 try!(space(&mut self.s));
417 try!(word(&mut self.s, &text[..]));
418 try!(space(&mut self.s));
419 word(&mut self.s, "*/")
423 pub fn commasep_cmnt<T, F, G>(&mut self,
429 where F: FnMut(&mut State, &T) -> io::Result<()>,
430 G: FnMut(&T) -> codemap::Span
432 try!(self.rbox(0, b));
433 let len = elts.len();
436 try!(self.maybe_print_comment(get_span(elt).hi));
440 try!(word(&mut self.s, ","));
441 try!(self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi)));
442 try!(self.space_if_not_bol());
448 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<hir::Expr>]) -> io::Result<()> {
449 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
452 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
453 try!(self.print_inner_attributes(attrs));
454 for item in &_mod.items {
455 try!(self.print_item(&**item));
460 pub fn print_foreign_mod(&mut self,
461 nmod: &hir::ForeignMod,
462 attrs: &[ast::Attribute])
464 try!(self.print_inner_attributes(attrs));
465 for item in &nmod.items {
466 try!(self.print_foreign_item(&**item));
471 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
472 if let Some(l) = *lifetime {
473 try!(self.print_lifetime(&l));
479 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
480 try!(self.maybe_print_comment(ty.span.lo));
483 hir::TyVec(ref ty) => {
484 try!(word(&mut self.s, "["));
485 try!(self.print_type(&**ty));
486 try!(word(&mut self.s, "]"));
488 hir::TyPtr(ref mt) => {
489 try!(word(&mut self.s, "*"));
491 hir::MutMutable => try!(self.word_nbsp("mut")),
492 hir::MutImmutable => try!(self.word_nbsp("const")),
494 try!(self.print_type(&*mt.ty));
496 hir::TyRptr(ref lifetime, ref mt) => {
497 try!(word(&mut self.s, "&"));
498 try!(self.print_opt_lifetime(lifetime));
499 try!(self.print_mt(mt));
501 hir::TyTup(ref elts) => {
503 try!(self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&**ty)));
505 try!(word(&mut self.s, ","));
509 hir::TyBareFn(ref f) => {
510 let generics = hir::Generics {
511 lifetimes: f.lifetimes.clone(),
512 ty_params: OwnedSlice::empty(),
513 where_clause: hir::WhereClause {
514 id: ast::DUMMY_NODE_ID,
515 predicates: Vec::new(),
518 try!(self.print_ty_fn(f.abi, f.unsafety, &*f.decl, None, &generics, None));
520 hir::TyPath(None, ref path) => {
521 try!(self.print_path(path, false, 0));
523 hir::TyPath(Some(ref qself), ref path) => {
524 try!(self.print_qpath(path, qself, false))
526 hir::TyObjectSum(ref ty, ref bounds) => {
527 try!(self.print_type(&**ty));
528 try!(self.print_bounds("+", &bounds[..]));
530 hir::TyPolyTraitRef(ref bounds) => {
531 try!(self.print_bounds("", &bounds[..]));
533 hir::TyFixedLengthVec(ref ty, ref v) => {
534 try!(word(&mut self.s, "["));
535 try!(self.print_type(&**ty));
536 try!(word(&mut self.s, "; "));
537 try!(self.print_expr(&**v));
538 try!(word(&mut self.s, "]"));
540 hir::TyTypeof(ref e) => {
541 try!(word(&mut self.s, "typeof("));
542 try!(self.print_expr(&**e));
543 try!(word(&mut self.s, ")"));
546 try!(word(&mut self.s, "_"));
552 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
553 try!(self.hardbreak_if_not_bol());
554 try!(self.maybe_print_comment(item.span.lo));
555 try!(self.print_outer_attributes(&item.attrs));
557 hir::ForeignItemFn(ref decl, ref generics) => {
559 try!(self.print_fn(decl,
560 hir::Unsafety::Normal,
561 hir::Constness::NotConst,
567 try!(self.end()); // end head-ibox
568 try!(word(&mut self.s, ";"));
569 self.end() // end the outer fn box
571 hir::ForeignItemStatic(ref t, m) => {
572 try!(self.head(&visibility_qualified(item.vis, "static")));
574 try!(self.word_space("mut"));
576 try!(self.print_name(item.name));
577 try!(self.word_space(":"));
578 try!(self.print_type(&**t));
579 try!(word(&mut self.s, ";"));
580 try!(self.end()); // end the head-ibox
581 self.end() // end the outer cbox
586 fn print_associated_const(&mut self,
589 default: Option<&hir::Expr>,
590 vis: hir::Visibility)
592 try!(word(&mut self.s, &visibility_qualified(vis, "")));
593 try!(self.word_space("const"));
594 try!(self.print_name(name));
595 try!(self.word_space(":"));
596 try!(self.print_type(ty));
597 if let Some(expr) = default {
598 try!(space(&mut self.s));
599 try!(self.word_space("="));
600 try!(self.print_expr(expr));
602 word(&mut self.s, ";")
605 fn print_associated_type(&mut self,
607 bounds: Option<&hir::TyParamBounds>,
608 ty: Option<&hir::Ty>)
610 try!(self.word_space("type"));
611 try!(self.print_name(name));
612 if let Some(bounds) = bounds {
613 try!(self.print_bounds(":", bounds));
615 if let Some(ty) = ty {
616 try!(space(&mut self.s));
617 try!(self.word_space("="));
618 try!(self.print_type(ty));
620 word(&mut self.s, ";")
623 /// Pretty-print an item
624 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
625 try!(self.hardbreak_if_not_bol());
626 try!(self.maybe_print_comment(item.span.lo));
627 try!(self.print_outer_attributes(&item.attrs));
628 try!(self.ann.pre(self, NodeItem(item)));
630 hir::ItemExternCrate(ref optional_path) => {
631 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
632 if let Some(p) = *optional_path {
633 let val = p.as_str();
634 if val.contains("-") {
635 try!(self.print_string(&val, ast::CookedStr));
637 try!(self.print_name(p));
639 try!(space(&mut self.s));
640 try!(word(&mut self.s, "as"));
641 try!(space(&mut self.s));
643 try!(self.print_name(item.name));
644 try!(word(&mut self.s, ";"));
645 try!(self.end()); // end inner head-block
646 try!(self.end()); // end outer head-block
648 hir::ItemUse(ref vp) => {
649 try!(self.head(&visibility_qualified(item.vis, "use")));
650 try!(self.print_view_path(&**vp));
651 try!(word(&mut self.s, ";"));
652 try!(self.end()); // end inner head-block
653 try!(self.end()); // end outer head-block
655 hir::ItemStatic(ref ty, m, ref expr) => {
656 try!(self.head(&visibility_qualified(item.vis, "static")));
657 if m == hir::MutMutable {
658 try!(self.word_space("mut"));
660 try!(self.print_name(item.name));
661 try!(self.word_space(":"));
662 try!(self.print_type(&**ty));
663 try!(space(&mut self.s));
664 try!(self.end()); // end the head-ibox
666 try!(self.word_space("="));
667 try!(self.print_expr(&**expr));
668 try!(word(&mut self.s, ";"));
669 try!(self.end()); // end the outer cbox
671 hir::ItemConst(ref ty, ref expr) => {
672 try!(self.head(&visibility_qualified(item.vis, "const")));
673 try!(self.print_name(item.name));
674 try!(self.word_space(":"));
675 try!(self.print_type(&**ty));
676 try!(space(&mut self.s));
677 try!(self.end()); // end the head-ibox
679 try!(self.word_space("="));
680 try!(self.print_expr(&**expr));
681 try!(word(&mut self.s, ";"));
682 try!(self.end()); // end the outer cbox
684 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
686 try!(self.print_fn(decl,
694 try!(word(&mut self.s, " "));
695 try!(self.print_block_with_attrs(&**body, &item.attrs));
697 hir::ItemMod(ref _mod) => {
698 try!(self.head(&visibility_qualified(item.vis, "mod")));
699 try!(self.print_name(item.name));
702 try!(self.print_mod(_mod, &item.attrs));
703 try!(self.bclose(item.span));
705 hir::ItemForeignMod(ref nmod) => {
706 try!(self.head("extern"));
707 try!(self.word_nbsp(&nmod.abi.to_string()));
709 try!(self.print_foreign_mod(nmod, &item.attrs));
710 try!(self.bclose(item.span));
712 hir::ItemTy(ref ty, ref params) => {
713 try!(self.ibox(indent_unit));
715 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
716 try!(self.print_name(item.name));
717 try!(self.print_generics(params));
718 try!(self.end()); // end the inner ibox
720 try!(self.print_where_clause(¶ms.where_clause));
721 try!(space(&mut self.s));
722 try!(self.word_space("="));
723 try!(self.print_type(&**ty));
724 try!(word(&mut self.s, ";"));
725 try!(self.end()); // end the outer ibox
727 hir::ItemEnum(ref enum_definition, ref params) => {
728 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
730 hir::ItemStruct(ref struct_def, ref generics) => {
731 try!(self.head(&visibility_qualified(item.vis, "struct")));
732 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
735 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
737 try!(self.print_visibility(item.vis));
738 try!(self.print_unsafety(unsafety));
739 try!(self.word_nbsp("impl"));
740 try!(self.print_trait_ref(trait_ref));
741 try!(space(&mut self.s));
742 try!(self.word_space("for"));
743 try!(self.word_space(".."));
745 try!(self.bclose(item.span));
747 hir::ItemImpl(unsafety,
754 try!(self.print_visibility(item.vis));
755 try!(self.print_unsafety(unsafety));
756 try!(self.word_nbsp("impl"));
758 if generics.is_parameterized() {
759 try!(self.print_generics(generics));
760 try!(space(&mut self.s));
764 hir::ImplPolarity::Negative => {
765 try!(word(&mut self.s, "!"));
772 try!(self.print_trait_ref(t));
773 try!(space(&mut self.s));
774 try!(self.word_space("for"));
779 try!(self.print_type(&**ty));
780 try!(self.print_where_clause(&generics.where_clause));
782 try!(space(&mut self.s));
784 try!(self.print_inner_attributes(&item.attrs));
785 for impl_item in impl_items {
786 try!(self.print_impl_item(impl_item));
788 try!(self.bclose(item.span));
790 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
792 try!(self.print_visibility(item.vis));
793 try!(self.print_unsafety(unsafety));
794 try!(self.word_nbsp("trait"));
795 try!(self.print_name(item.name));
796 try!(self.print_generics(generics));
797 let mut real_bounds = Vec::with_capacity(bounds.len());
798 for b in bounds.iter() {
799 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
800 try!(space(&mut self.s));
801 try!(self.word_space("for ?"));
802 try!(self.print_trait_ref(&ptr.trait_ref));
804 real_bounds.push(b.clone());
807 try!(self.print_bounds(":", &real_bounds[..]));
808 try!(self.print_where_clause(&generics.where_clause));
809 try!(word(&mut self.s, " "));
811 for trait_item in trait_items {
812 try!(self.print_trait_item(trait_item));
814 try!(self.bclose(item.span));
817 self.ann.post(self, NodeItem(item))
820 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
821 self.print_path(&t.path, false, 0)
824 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
825 if !lifetimes.is_empty() {
826 try!(word(&mut self.s, "for<"));
827 let mut comma = false;
828 for lifetime_def in lifetimes {
830 try!(self.word_space(","))
832 try!(self.print_lifetime_def(lifetime_def));
835 try!(word(&mut self.s, ">"));
840 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
841 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
842 self.print_trait_ref(&t.trait_ref)
845 pub fn print_enum_def(&mut self,
846 enum_definition: &hir::EnumDef,
847 generics: &hir::Generics,
850 visibility: hir::Visibility)
852 try!(self.head(&visibility_qualified(visibility, "enum")));
853 try!(self.print_name(name));
854 try!(self.print_generics(generics));
855 try!(self.print_where_clause(&generics.where_clause));
856 try!(space(&mut self.s));
857 self.print_variants(&enum_definition.variants, span)
860 pub fn print_variants(&mut self,
861 variants: &[P<hir::Variant>],
866 try!(self.space_if_not_bol());
867 try!(self.maybe_print_comment(v.span.lo));
868 try!(self.print_outer_attributes(&v.node.attrs));
869 try!(self.ibox(indent_unit));
870 try!(self.print_variant(&**v));
871 try!(word(&mut self.s, ","));
873 try!(self.maybe_print_trailing_comment(v.span, None));
878 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
880 hir::Public => self.word_nbsp("pub"),
881 hir::Inherited => Ok(()),
885 pub fn print_struct(&mut self,
886 struct_def: &hir::VariantData,
887 generics: &hir::Generics,
890 print_finalizer: bool)
892 try!(self.print_name(name));
893 try!(self.print_generics(generics));
894 if !struct_def.is_struct() {
895 if struct_def.is_tuple() {
897 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
898 match field.node.kind {
899 hir::NamedField(..) => panic!("unexpected named field"),
900 hir::UnnamedField(vis) => {
901 try!(s.print_visibility(vis));
902 try!(s.maybe_print_comment(field.span.lo));
903 s.print_type(&*field.node.ty)
909 try!(self.print_where_clause(&generics.where_clause));
911 try!(word(&mut self.s, ";"));
914 self.end() // close the outer-box
916 try!(self.print_where_clause(&generics.where_clause));
919 try!(self.hardbreak_if_not_bol());
921 for field in struct_def.fields() {
922 match field.node.kind {
923 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
924 hir::NamedField(name, visibility) => {
925 try!(self.hardbreak_if_not_bol());
926 try!(self.maybe_print_comment(field.span.lo));
927 try!(self.print_outer_attributes(&field.node.attrs));
928 try!(self.print_visibility(visibility));
929 try!(self.print_name(name));
930 try!(self.word_nbsp(":"));
931 try!(self.print_type(&*field.node.ty));
932 try!(word(&mut self.s, ","));
941 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
943 let generics = ::util::empty_generics();
944 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
945 match v.node.disr_expr {
947 try!(space(&mut self.s));
948 try!(self.word_space("="));
949 self.print_expr(&**d)
955 pub fn print_method_sig(&mut self,
958 vis: hir::Visibility)
960 self.print_fn(&m.decl,
966 Some(&m.explicit_self.node),
970 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
971 try!(self.ann.pre(self, NodeSubItem(ti.id)));
972 try!(self.hardbreak_if_not_bol());
973 try!(self.maybe_print_comment(ti.span.lo));
974 try!(self.print_outer_attributes(&ti.attrs));
976 hir::ConstTraitItem(ref ty, ref default) => {
977 try!(self.print_associated_const(ti.name,
979 default.as_ref().map(|expr| &**expr),
982 hir::MethodTraitItem(ref sig, ref body) => {
986 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
987 if let Some(ref body) = *body {
989 try!(self.print_block_with_attrs(body, &ti.attrs));
991 try!(word(&mut self.s, ";"));
994 hir::TypeTraitItem(ref bounds, ref default) => {
995 try!(self.print_associated_type(ti.name,
997 default.as_ref().map(|ty| &**ty)));
1000 self.ann.post(self, NodeSubItem(ti.id))
1003 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1004 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1005 try!(self.hardbreak_if_not_bol());
1006 try!(self.maybe_print_comment(ii.span.lo));
1007 try!(self.print_outer_attributes(&ii.attrs));
1009 hir::ImplItemKind::Const(ref ty, ref expr) => {
1010 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1012 hir::ImplItemKind::Method(ref sig, ref body) => {
1013 try!(self.head(""));
1014 try!(self.print_method_sig(ii.name, sig, ii.vis));
1016 try!(self.print_block_with_attrs(body, &ii.attrs));
1018 hir::ImplItemKind::Type(ref ty) => {
1019 try!(self.print_associated_type(ii.name, None, Some(ty)));
1022 self.ann.post(self, NodeSubItem(ii.id))
1025 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1026 try!(self.maybe_print_comment(st.span.lo));
1028 hir::StmtDecl(ref decl, _) => {
1029 try!(self.print_decl(&**decl));
1031 hir::StmtExpr(ref expr, _) => {
1032 try!(self.space_if_not_bol());
1033 try!(self.print_expr(&**expr));
1035 hir::StmtSemi(ref expr, _) => {
1036 try!(self.space_if_not_bol());
1037 try!(self.print_expr(&**expr));
1038 try!(word(&mut self.s, ";"));
1041 if stmt_ends_with_semi(&st.node) {
1042 try!(word(&mut self.s, ";"));
1044 self.maybe_print_trailing_comment(st.span, None)
1047 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1048 self.print_block_with_attrs(blk, &[])
1051 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1052 self.print_block_unclosed_indent(blk, indent_unit)
1055 pub fn print_block_unclosed_indent(&mut self,
1059 self.print_block_maybe_unclosed(blk, indented, &[], false)
1062 pub fn print_block_with_attrs(&mut self,
1064 attrs: &[ast::Attribute])
1066 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1069 pub fn print_block_maybe_unclosed(&mut self,
1072 attrs: &[ast::Attribute],
1076 hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1077 hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1078 hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1079 hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1080 hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1081 hir::DefaultBlock => (),
1083 try!(self.maybe_print_comment(blk.span.lo));
1084 try!(self.ann.pre(self, NodeBlock(blk)));
1087 try!(self.print_inner_attributes(attrs));
1089 for st in &blk.stmts {
1090 try!(self.print_stmt(&**st));
1094 try!(self.space_if_not_bol());
1095 try!(self.print_expr(&**expr));
1096 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1100 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1101 self.ann.post(self, NodeBlock(blk))
1104 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1108 // "another else-if"
1109 hir::ExprIf(ref i, ref then, ref e) => {
1110 try!(self.cbox(indent_unit - 1));
1112 try!(word(&mut self.s, " else if "));
1113 try!(self.print_expr(&**i));
1114 try!(space(&mut self.s));
1115 try!(self.print_block(&**then));
1116 self.print_else(e.as_ref().map(|e| &**e))
1119 hir::ExprBlock(ref b) => {
1120 try!(self.cbox(indent_unit - 1));
1122 try!(word(&mut self.s, " else "));
1123 self.print_block(&**b)
1125 // BLEAH, constraints would be great here
1127 panic!("print_if saw if with weird alternative");
1135 pub fn print_if(&mut self,
1138 elseopt: Option<&hir::Expr>)
1140 try!(self.head("if"));
1141 try!(self.print_expr(test));
1142 try!(space(&mut self.s));
1143 try!(self.print_block(blk));
1144 self.print_else(elseopt)
1147 pub fn print_if_let(&mut self,
1151 elseopt: Option<&hir::Expr>)
1153 try!(self.head("if let"));
1154 try!(self.print_pat(pat));
1155 try!(space(&mut self.s));
1156 try!(self.word_space("="));
1157 try!(self.print_expr(expr));
1158 try!(space(&mut self.s));
1159 try!(self.print_block(blk));
1160 self.print_else(elseopt)
1164 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1166 try!(self.commasep_exprs(Inconsistent, args));
1170 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1171 let needs_par = needs_parentheses(expr);
1175 try!(self.print_expr(expr));
1177 try!(self.pclose());
1182 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1183 try!(self.ibox(indent_unit));
1184 try!(word(&mut self.s, "["));
1185 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1186 try!(word(&mut self.s, "]"));
1190 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1191 try!(self.ibox(indent_unit));
1192 try!(word(&mut self.s, "["));
1193 try!(self.print_expr(element));
1194 try!(self.word_space(";"));
1195 try!(self.print_expr(count));
1196 try!(word(&mut self.s, "]"));
1200 fn print_expr_struct(&mut self,
1202 fields: &[hir::Field],
1203 wth: &Option<P<hir::Expr>>)
1205 try!(self.print_path(path, true, 0));
1206 try!(word(&mut self.s, "{"));
1207 try!(self.commasep_cmnt(Consistent,
1210 try!(s.ibox(indent_unit));
1211 try!(s.print_name(field.name.node));
1212 try!(s.word_space(":"));
1213 try!(s.print_expr(&*field.expr));
1219 try!(self.ibox(indent_unit));
1220 if !fields.is_empty() {
1221 try!(word(&mut self.s, ","));
1222 try!(space(&mut self.s));
1224 try!(word(&mut self.s, ".."));
1225 try!(self.print_expr(&**expr));
1228 _ => if !fields.is_empty() {
1229 try!(word(&mut self.s, ","))
1232 try!(word(&mut self.s, "}"));
1236 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1238 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1239 if exprs.len() == 1 {
1240 try!(word(&mut self.s, ","));
1245 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1246 try!(self.print_expr_maybe_paren(func));
1247 self.print_call_post(args)
1250 fn print_expr_method_call(&mut self,
1251 name: Spanned<ast::Name>,
1253 args: &[P<hir::Expr>])
1255 let base_args = &args[1..];
1256 try!(self.print_expr(&*args[0]));
1257 try!(word(&mut self.s, "."));
1258 try!(self.print_name(name.node));
1259 if !tys.is_empty() {
1260 try!(word(&mut self.s, "::<"));
1261 try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty)));
1262 try!(word(&mut self.s, ">"));
1264 self.print_call_post(base_args)
1267 fn print_expr_binary(&mut self,
1272 try!(self.print_expr(lhs));
1273 try!(space(&mut self.s));
1274 try!(self.word_space(::util::binop_to_string(op.node)));
1275 self.print_expr(rhs)
1278 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1279 try!(word(&mut self.s, ::util::unop_to_string(op)));
1280 self.print_expr_maybe_paren(expr)
1283 fn print_expr_addr_of(&mut self,
1284 mutability: hir::Mutability,
1287 try!(word(&mut self.s, "&"));
1288 try!(self.print_mutability(mutability));
1289 self.print_expr_maybe_paren(expr)
1292 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1293 try!(self.maybe_print_comment(expr.span.lo));
1294 try!(self.ibox(indent_unit));
1295 try!(self.ann.pre(self, NodeExpr(expr)));
1297 hir::ExprBox(ref expr) => {
1298 try!(self.word_space("box"));
1299 try!(self.print_expr(expr));
1301 hir::ExprVec(ref exprs) => {
1302 try!(self.print_expr_vec(&exprs[..]));
1304 hir::ExprRepeat(ref element, ref count) => {
1305 try!(self.print_expr_repeat(&**element, &**count));
1307 hir::ExprStruct(ref path, ref fields, ref wth) => {
1308 try!(self.print_expr_struct(path, &fields[..], wth));
1310 hir::ExprTup(ref exprs) => {
1311 try!(self.print_expr_tup(&exprs[..]));
1313 hir::ExprCall(ref func, ref args) => {
1314 try!(self.print_expr_call(&**func, &args[..]));
1316 hir::ExprMethodCall(name, ref tys, ref args) => {
1317 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1319 hir::ExprBinary(op, ref lhs, ref rhs) => {
1320 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1322 hir::ExprUnary(op, ref expr) => {
1323 try!(self.print_expr_unary(op, &**expr));
1325 hir::ExprAddrOf(m, ref expr) => {
1326 try!(self.print_expr_addr_of(m, &**expr));
1328 hir::ExprLit(ref lit) => {
1329 try!(self.print_literal(&**lit));
1331 hir::ExprCast(ref expr, ref ty) => {
1332 try!(self.print_expr(&**expr));
1333 try!(space(&mut self.s));
1334 try!(self.word_space("as"));
1335 try!(self.print_type(&**ty));
1337 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1338 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1340 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1341 if let Some(ident) = opt_ident {
1342 try!(self.print_name(ident.name));
1343 try!(self.word_space(":"));
1345 try!(self.head("while"));
1346 try!(self.print_expr(&**test));
1347 try!(space(&mut self.s));
1348 try!(self.print_block(&**blk));
1350 hir::ExprLoop(ref blk, opt_ident) => {
1351 if let Some(ident) = opt_ident {
1352 try!(self.print_name(ident.name));
1353 try!(self.word_space(":"));
1355 try!(self.head("loop"));
1356 try!(space(&mut self.s));
1357 try!(self.print_block(&**blk));
1359 hir::ExprMatch(ref expr, ref arms, _) => {
1360 try!(self.cbox(indent_unit));
1362 try!(self.word_nbsp("match"));
1363 try!(self.print_expr(&**expr));
1364 try!(space(&mut self.s));
1367 try!(self.print_arm(arm));
1369 try!(self.bclose_(expr.span, indent_unit));
1371 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1372 try!(self.print_capture_clause(capture_clause));
1374 try!(self.print_fn_block_args(&**decl));
1375 try!(space(&mut self.s));
1377 let default_return = match decl.output {
1378 hir::DefaultReturn(..) => true,
1382 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1383 try!(self.print_block_unclosed(&**body));
1385 // we extract the block, so as not to create another set of boxes
1386 match body.expr.as_ref().unwrap().node {
1387 hir::ExprBlock(ref blk) => {
1388 try!(self.print_block_unclosed(&**blk));
1391 // this is a bare expression
1392 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1393 try!(self.end()); // need to close a box
1397 // a box will be closed by print_expr, but we didn't want an overall
1398 // wrapper so we closed the corresponding opening. so create an
1399 // empty box to satisfy the close.
1402 hir::ExprBlock(ref blk) => {
1403 // containing cbox, will be closed by print-block at }
1404 try!(self.cbox(indent_unit));
1405 // head-box, will be closed by print-block after {
1407 try!(self.print_block(&**blk));
1409 hir::ExprAssign(ref lhs, ref rhs) => {
1410 try!(self.print_expr(&**lhs));
1411 try!(space(&mut self.s));
1412 try!(self.word_space("="));
1413 try!(self.print_expr(&**rhs));
1415 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1416 try!(self.print_expr(&**lhs));
1417 try!(space(&mut self.s));
1418 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1419 try!(self.word_space("="));
1420 try!(self.print_expr(&**rhs));
1422 hir::ExprField(ref expr, name) => {
1423 try!(self.print_expr(&**expr));
1424 try!(word(&mut self.s, "."));
1425 try!(self.print_name(name.node));
1427 hir::ExprTupField(ref expr, id) => {
1428 try!(self.print_expr(&**expr));
1429 try!(word(&mut self.s, "."));
1430 try!(self.print_usize(id.node));
1432 hir::ExprIndex(ref expr, ref index) => {
1433 try!(self.print_expr(&**expr));
1434 try!(word(&mut self.s, "["));
1435 try!(self.print_expr(&**index));
1436 try!(word(&mut self.s, "]"));
1438 hir::ExprRange(ref start, ref end) => {
1439 if let &Some(ref e) = start {
1440 try!(self.print_expr(&**e));
1442 try!(word(&mut self.s, ".."));
1443 if let &Some(ref e) = end {
1444 try!(self.print_expr(&**e));
1447 hir::ExprPath(None, ref path) => {
1448 try!(self.print_path(path, true, 0))
1450 hir::ExprPath(Some(ref qself), ref path) => {
1451 try!(self.print_qpath(path, qself, true))
1453 hir::ExprBreak(opt_ident) => {
1454 try!(word(&mut self.s, "break"));
1455 try!(space(&mut self.s));
1456 if let Some(ident) = opt_ident {
1457 try!(self.print_name(ident.node.name));
1458 try!(space(&mut self.s));
1461 hir::ExprAgain(opt_ident) => {
1462 try!(word(&mut self.s, "continue"));
1463 try!(space(&mut self.s));
1464 if let Some(ident) = opt_ident {
1465 try!(self.print_name(ident.node.name));
1466 try!(space(&mut self.s))
1469 hir::ExprRet(ref result) => {
1470 try!(word(&mut self.s, "return"));
1473 try!(word(&mut self.s, " "));
1474 try!(self.print_expr(&**expr));
1479 hir::ExprInlineAsm(ref a) => {
1480 try!(word(&mut self.s, "asm!"));
1482 try!(self.print_string(&a.asm, a.asm_str_style));
1483 try!(self.word_space(":"));
1485 try!(self.commasep(Inconsistent, &a.outputs, |s, &(ref co, ref o, is_rw)| {
1486 match co.slice_shift_char() {
1487 Some(('=', operand)) if is_rw => {
1488 try!(s.print_string(&format!("+{}", operand), ast::CookedStr))
1490 _ => try!(s.print_string(&co, ast::CookedStr)),
1493 try!(s.print_expr(&**o));
1497 try!(space(&mut self.s));
1498 try!(self.word_space(":"));
1500 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1501 try!(s.print_string(&co, ast::CookedStr));
1503 try!(s.print_expr(&**o));
1507 try!(space(&mut self.s));
1508 try!(self.word_space(":"));
1510 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1511 try!(s.print_string(&co, ast::CookedStr));
1515 let mut options = vec![];
1517 options.push("volatile");
1520 options.push("alignstack");
1522 if a.dialect == ast::AsmDialect::Intel {
1523 options.push("intel");
1526 if !options.is_empty() {
1527 try!(space(&mut self.s));
1528 try!(self.word_space(":"));
1529 try!(self.commasep(Inconsistent, &*options, |s, &co| {
1530 try!(s.print_string(co, ast::CookedStr));
1535 try!(self.pclose());
1538 try!(self.ann.post(self, NodeExpr(expr)));
1542 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1543 try!(self.print_pat(&*loc.pat));
1544 if let Some(ref ty) = loc.ty {
1545 try!(self.word_space(":"));
1546 try!(self.print_type(&**ty));
1551 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1552 try!(self.maybe_print_comment(decl.span.lo));
1554 hir::DeclLocal(ref loc) => {
1555 try!(self.space_if_not_bol());
1556 try!(self.ibox(indent_unit));
1557 try!(self.word_nbsp("let"));
1559 try!(self.ibox(indent_unit));
1560 try!(self.print_local_decl(&**loc));
1562 if let Some(ref init) = loc.init {
1564 try!(self.word_space("="));
1565 try!(self.print_expr(&**init));
1569 hir::DeclItem(ref item) => self.print_item(&**item),
1573 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1574 word(&mut self.s, &i.to_string())
1577 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1578 try!(word(&mut self.s, &name.as_str()));
1579 self.ann.post(self, NodeName(&name))
1582 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1583 try!(self.print_local_decl(loc));
1584 try!(space(&mut self.s));
1585 try!(self.word_space("in"));
1586 self.print_expr(coll)
1589 fn print_path(&mut self,
1591 colons_before_params: bool,
1594 try!(self.maybe_print_comment(path.span.lo));
1596 let mut first = !path.global;
1597 for segment in &path.segments[..path.segments.len() - depth] {
1601 try!(word(&mut self.s, "::"))
1604 try!(self.print_name(segment.identifier.name));
1606 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1612 fn print_qpath(&mut self,
1615 colons_before_params: bool)
1617 try!(word(&mut self.s, "<"));
1618 try!(self.print_type(&qself.ty));
1619 if qself.position > 0 {
1620 try!(space(&mut self.s));
1621 try!(self.word_space("as"));
1622 let depth = path.segments.len() - qself.position;
1623 try!(self.print_path(&path, false, depth));
1625 try!(word(&mut self.s, ">"));
1626 try!(word(&mut self.s, "::"));
1627 let item_segment = path.segments.last().unwrap();
1628 try!(self.print_name(item_segment.identifier.name));
1629 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1632 fn print_path_parameters(&mut self,
1633 parameters: &hir::PathParameters,
1634 colons_before_params: bool)
1636 if parameters.is_empty() {
1640 if colons_before_params {
1641 try!(word(&mut self.s, "::"))
1645 hir::AngleBracketedParameters(ref data) => {
1646 try!(word(&mut self.s, "<"));
1648 let mut comma = false;
1649 for lifetime in &data.lifetimes {
1651 try!(self.word_space(","))
1653 try!(self.print_lifetime(lifetime));
1657 if !data.types.is_empty() {
1659 try!(self.word_space(","))
1661 try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&**ty)));
1665 for binding in data.bindings.iter() {
1667 try!(self.word_space(","))
1669 try!(self.print_name(binding.name));
1670 try!(space(&mut self.s));
1671 try!(self.word_space("="));
1672 try!(self.print_type(&*binding.ty));
1676 try!(word(&mut self.s, ">"))
1679 hir::ParenthesizedParameters(ref data) => {
1680 try!(word(&mut self.s, "("));
1681 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&**ty)));
1682 try!(word(&mut self.s, ")"));
1687 try!(self.space_if_not_bol());
1688 try!(self.word_space("->"));
1689 try!(self.print_type(&**ty));
1698 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1699 try!(self.maybe_print_comment(pat.span.lo));
1700 try!(self.ann.pre(self, NodePat(pat)));
1701 // Pat isn't normalized, but the beauty of it
1702 // is that it doesn't matter
1704 hir::PatWild => try!(word(&mut self.s, "_")),
1705 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1706 match binding_mode {
1707 hir::BindByRef(mutbl) => {
1708 try!(self.word_nbsp("ref"));
1709 try!(self.print_mutability(mutbl));
1711 hir::BindByValue(hir::MutImmutable) => {}
1712 hir::BindByValue(hir::MutMutable) => {
1713 try!(self.word_nbsp("mut"));
1716 try!(self.print_name(path1.node.name));
1719 try!(word(&mut self.s, "@"));
1720 try!(self.print_pat(&**p));
1725 hir::PatEnum(ref path, ref args_) => {
1726 try!(self.print_path(path, true, 0));
1728 None => try!(word(&mut self.s, "(..)")),
1730 if !args.is_empty() {
1732 try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&**p)));
1733 try!(self.pclose());
1738 hir::PatQPath(ref qself, ref path) => {
1739 try!(self.print_qpath(path, qself, false));
1741 hir::PatStruct(ref path, ref fields, etc) => {
1742 try!(self.print_path(path, true, 0));
1744 try!(self.word_space("{"));
1745 try!(self.commasep_cmnt(Consistent,
1748 try!(s.cbox(indent_unit));
1749 if !f.node.is_shorthand {
1750 try!(s.print_name(f.node.name));
1751 try!(s.word_nbsp(":"));
1753 try!(s.print_pat(&*f.node.pat));
1756 |f| f.node.pat.span));
1758 if !fields.is_empty() {
1759 try!(self.word_space(","));
1761 try!(word(&mut self.s, ".."));
1763 try!(space(&mut self.s));
1764 try!(word(&mut self.s, "}"));
1766 hir::PatTup(ref elts) => {
1768 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&**p)));
1769 if elts.len() == 1 {
1770 try!(word(&mut self.s, ","));
1772 try!(self.pclose());
1774 hir::PatBox(ref inner) => {
1775 try!(word(&mut self.s, "box "));
1776 try!(self.print_pat(&**inner));
1778 hir::PatRegion(ref inner, mutbl) => {
1779 try!(word(&mut self.s, "&"));
1780 if mutbl == hir::MutMutable {
1781 try!(word(&mut self.s, "mut "));
1783 try!(self.print_pat(&**inner));
1785 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1786 hir::PatRange(ref begin, ref end) => {
1787 try!(self.print_expr(&**begin));
1788 try!(space(&mut self.s));
1789 try!(word(&mut self.s, "..."));
1790 try!(self.print_expr(&**end));
1792 hir::PatVec(ref before, ref slice, ref after) => {
1793 try!(word(&mut self.s, "["));
1794 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&**p)));
1795 if let Some(ref p) = *slice {
1796 if !before.is_empty() {
1797 try!(self.word_space(","));
1799 if p.node != hir::PatWild {
1800 try!(self.print_pat(&**p));
1802 try!(word(&mut self.s, ".."));
1803 if !after.is_empty() {
1804 try!(self.word_space(","));
1807 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&**p)));
1808 try!(word(&mut self.s, "]"));
1811 self.ann.post(self, NodePat(pat))
1814 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1815 // I have no idea why this check is necessary, but here it
1817 if arm.attrs.is_empty() {
1818 try!(space(&mut self.s));
1820 try!(self.cbox(indent_unit));
1822 try!(self.print_outer_attributes(&arm.attrs));
1823 let mut first = true;
1824 for p in &arm.pats {
1828 try!(space(&mut self.s));
1829 try!(self.word_space("|"));
1831 try!(self.print_pat(&**p));
1833 try!(space(&mut self.s));
1834 if let Some(ref e) = arm.guard {
1835 try!(self.word_space("if"));
1836 try!(self.print_expr(&**e));
1837 try!(space(&mut self.s));
1839 try!(self.word_space("=>"));
1841 match arm.body.node {
1842 hir::ExprBlock(ref blk) => {
1843 // the block will close the pattern's ibox
1844 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1846 // If it is a user-provided unsafe block, print a comma after it
1847 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1848 try!(word(&mut self.s, ","));
1852 try!(self.end()); // close the ibox for the pattern
1853 try!(self.print_expr(&*arm.body));
1854 try!(word(&mut self.s, ","));
1857 self.end() // close enclosing cbox
1860 // Returns whether it printed anything
1861 fn print_explicit_self(&mut self,
1862 explicit_self: &hir::ExplicitSelf_,
1863 mutbl: hir::Mutability)
1864 -> io::Result<bool> {
1865 try!(self.print_mutability(mutbl));
1866 match *explicit_self {
1867 hir::SelfStatic => {
1870 hir::SelfValue(_) => {
1871 try!(word(&mut self.s, "self"));
1873 hir::SelfRegion(ref lt, m, _) => {
1874 try!(word(&mut self.s, "&"));
1875 try!(self.print_opt_lifetime(lt));
1876 try!(self.print_mutability(m));
1877 try!(word(&mut self.s, "self"));
1879 hir::SelfExplicit(ref typ, _) => {
1880 try!(word(&mut self.s, "self"));
1881 try!(self.word_space(":"));
1882 try!(self.print_type(&**typ));
1888 pub fn print_fn(&mut self,
1890 unsafety: hir::Unsafety,
1891 constness: hir::Constness,
1893 name: Option<ast::Name>,
1894 generics: &hir::Generics,
1895 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1896 vis: hir::Visibility)
1898 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1900 if let Some(name) = name {
1902 try!(self.print_name(name));
1904 try!(self.print_generics(generics));
1905 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1906 self.print_where_clause(&generics.where_clause)
1909 pub fn print_fn_args(&mut self,
1911 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1913 // It is unfortunate to duplicate the commasep logic, but we want the
1914 // self type and the args all in the same box.
1915 try!(self.rbox(0, Inconsistent));
1916 let mut first = true;
1917 if let Some(explicit_self) = opt_explicit_self {
1918 let m = match explicit_self {
1919 &hir::SelfStatic => hir::MutImmutable,
1920 _ => match decl.inputs[0].pat.node {
1921 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1922 _ => hir::MutImmutable,
1925 first = !try!(self.print_explicit_self(explicit_self, m));
1928 // HACK(eddyb) ignore the separately printed self argument.
1929 let args = if first {
1939 try!(self.word_space(","));
1941 try!(self.print_arg(arg));
1947 pub fn print_fn_args_and_ret(&mut self,
1949 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1952 try!(self.print_fn_args(decl, opt_explicit_self));
1954 try!(word(&mut self.s, ", ..."));
1956 try!(self.pclose());
1958 self.print_fn_output(decl)
1961 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1962 try!(word(&mut self.s, "|"));
1963 try!(self.print_fn_args(decl, None));
1964 try!(word(&mut self.s, "|"));
1966 if let hir::DefaultReturn(..) = decl.output {
1970 try!(self.space_if_not_bol());
1971 try!(self.word_space("->"));
1973 hir::Return(ref ty) => {
1974 try!(self.print_type(&**ty));
1975 self.maybe_print_comment(ty.span.lo)
1977 hir::DefaultReturn(..) => unreachable!(),
1978 hir::NoReturn(span) => {
1979 try!(self.word_nbsp("!"));
1980 self.maybe_print_comment(span.lo)
1985 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1986 match capture_clause {
1987 hir::CaptureByValue => self.word_space("move"),
1988 hir::CaptureByRef => Ok(()),
1992 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1993 if !bounds.is_empty() {
1994 try!(word(&mut self.s, prefix));
1995 let mut first = true;
1996 for bound in bounds {
2001 try!(self.word_space("+"));
2005 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2006 self.print_poly_trait_ref(tref)
2008 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2009 try!(word(&mut self.s, "?"));
2010 self.print_poly_trait_ref(tref)
2012 RegionTyParamBound(ref lt) => {
2013 self.print_lifetime(lt)
2023 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2024 self.print_name(lifetime.name)
2027 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2028 try!(self.print_lifetime(&lifetime.lifetime));
2030 for v in &lifetime.bounds {
2031 try!(word(&mut self.s, sep));
2032 try!(self.print_lifetime(v));
2038 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2039 let total = generics.lifetimes.len() + generics.ty_params.len();
2044 try!(word(&mut self.s, "<"));
2046 let mut ints = Vec::new();
2051 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2052 if idx < generics.lifetimes.len() {
2053 let lifetime = &generics.lifetimes[idx];
2054 s.print_lifetime_def(lifetime)
2056 let idx = idx - generics.lifetimes.len();
2057 let param = &generics.ty_params[idx];
2058 s.print_ty_param(param)
2062 try!(word(&mut self.s, ">"));
2066 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2067 try!(self.print_name(param.name));
2068 try!(self.print_bounds(":", ¶m.bounds));
2069 match param.default {
2070 Some(ref default) => {
2071 try!(space(&mut self.s));
2072 try!(self.word_space("="));
2073 self.print_type(&**default)
2079 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2080 if where_clause.predicates.is_empty() {
2084 try!(space(&mut self.s));
2085 try!(self.word_space("where"));
2087 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2089 try!(self.word_space(","));
2093 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2097 try!(self.print_formal_lifetime_list(bound_lifetimes));
2098 try!(self.print_type(&**bounded_ty));
2099 try!(self.print_bounds(":", bounds));
2101 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2104 try!(self.print_lifetime(lifetime));
2105 try!(word(&mut self.s, ":"));
2107 for (i, bound) in bounds.iter().enumerate() {
2108 try!(self.print_lifetime(bound));
2111 try!(word(&mut self.s, ":"));
2115 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2116 try!(self.print_path(path, false, 0));
2117 try!(space(&mut self.s));
2118 try!(self.word_space("="));
2119 try!(self.print_type(&**ty));
2127 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2129 hir::ViewPathSimple(name, ref path) => {
2130 try!(self.print_path(path, false, 0));
2132 if path.segments.last().unwrap().identifier.name != name {
2133 try!(space(&mut self.s));
2134 try!(self.word_space("as"));
2135 try!(self.print_name(name));
2141 hir::ViewPathGlob(ref path) => {
2142 try!(self.print_path(path, false, 0));
2143 word(&mut self.s, "::*")
2146 hir::ViewPathList(ref path, ref segments) => {
2147 if path.segments.is_empty() {
2148 try!(word(&mut self.s, "{"));
2150 try!(self.print_path(path, false, 0));
2151 try!(word(&mut self.s, "::{"));
2153 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2155 hir::PathListIdent { name, .. } => {
2158 hir::PathListMod { .. } => {
2159 word(&mut s.s, "self")
2163 word(&mut self.s, "}")
2168 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2170 hir::MutMutable => self.word_nbsp("mut"),
2171 hir::MutImmutable => Ok(()),
2175 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2176 try!(self.print_mutability(mt.mutbl));
2177 self.print_type(&*mt.ty)
2180 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2181 try!(self.ibox(indent_unit));
2182 match input.ty.node {
2183 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2185 match input.pat.node {
2186 hir::PatIdent(_, ref path1, _) if
2188 parse::token::special_idents::invalid.name => {
2192 try!(self.print_pat(&*input.pat));
2193 try!(word(&mut self.s, ":"));
2194 try!(space(&mut self.s));
2197 try!(self.print_type(&*input.ty));
2203 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2204 if let hir::DefaultReturn(..) = decl.output {
2208 try!(self.space_if_not_bol());
2209 try!(self.ibox(indent_unit));
2210 try!(self.word_space("->"));
2212 hir::NoReturn(_) => try!(self.word_nbsp("!")),
2213 hir::DefaultReturn(..) => unreachable!(),
2214 hir::Return(ref ty) => try!(self.print_type(&**ty)),
2219 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2224 pub fn print_ty_fn(&mut self,
2226 unsafety: hir::Unsafety,
2228 name: Option<ast::Name>,
2229 generics: &hir::Generics,
2230 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2232 try!(self.ibox(indent_unit));
2233 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2234 try!(word(&mut self.s, "for"));
2235 try!(self.print_generics(generics));
2237 let generics = hir::Generics {
2238 lifetimes: Vec::new(),
2239 ty_params: OwnedSlice::empty(),
2240 where_clause: hir::WhereClause {
2241 id: ast::DUMMY_NODE_ID,
2242 predicates: Vec::new(),
2245 try!(self.print_fn(decl,
2247 hir::Constness::NotConst,
2256 pub fn maybe_print_trailing_comment(&mut self,
2257 span: codemap::Span,
2258 next_pos: Option<BytePos>)
2260 let cm = match self.cm {
2264 match self.next_comment() {
2266 if (*cmnt).style != comments::Trailing {
2269 let span_line = cm.lookup_char_pos(span.hi);
2270 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2271 let mut next = (*cmnt).pos + BytePos(1);
2274 Some(p) => next = p,
2276 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2277 span_line.line == comment_line.line {
2278 try!(self.print_comment(cmnt));
2279 self.cur_cmnt_and_lit.cur_cmnt += 1;
2287 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2288 // If there aren't any remaining comments, then we need to manually
2289 // make sure there is a line break at the end.
2290 if self.next_comment().is_none() {
2291 try!(hardbreak(&mut self.s));
2294 match self.next_comment() {
2296 try!(self.print_comment(cmnt));
2297 self.cur_cmnt_and_lit.cur_cmnt += 1;
2305 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2306 opt_abi: Option<abi::Abi>)
2309 Some(abi::Rust) => Ok(()),
2311 try!(self.word_nbsp("extern"));
2312 self.word_nbsp(&abi.to_string())
2318 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<abi::Abi>) -> io::Result<()> {
2321 try!(self.word_nbsp("extern"));
2322 self.word_nbsp(&abi.to_string())
2328 pub fn print_fn_header_info(&mut self,
2329 unsafety: hir::Unsafety,
2330 constness: hir::Constness,
2332 vis: hir::Visibility)
2334 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2335 try!(self.print_unsafety(unsafety));
2338 hir::Constness::NotConst => {}
2339 hir::Constness::Const => try!(self.word_nbsp("const")),
2342 if abi != abi::Rust {
2343 try!(self.word_nbsp("extern"));
2344 try!(self.word_nbsp(&abi.to_string()));
2347 word(&mut self.s, "fn")
2350 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2352 hir::Unsafety::Normal => Ok(()),
2353 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2358 // Dup'ed from parse::classify, but adapted for the HIR.
2359 /// Does this expression require a semicolon to be treated
2360 /// as a statement? The negation of this: 'can this expression
2361 /// be used as a statement without a semicolon' -- is used
2362 /// as an early-bail-out in the parser so that, for instance,
2363 /// if true {...} else {...}
2365 /// isn't parsed as (if true {...} else {...} | x) | 5
2366 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2369 hir::ExprMatch(..) |
2371 hir::ExprWhile(..) |
2372 hir::ExprLoop(..) => false,
2377 /// this statement requires a semicolon after it.
2378 /// note that in one case (stmt_semi), we've already
2379 /// seen the semicolon, and thus don't need another.
2380 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2382 hir::StmtDecl(ref d, _) => {
2384 hir::DeclLocal(_) => true,
2385 hir::DeclItem(_) => false,
2388 hir::StmtExpr(ref e, _) => {
2389 expr_requires_semi_to_be_stmt(&**e)
2391 hir::StmtSemi(..) => {