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::TyParen(ref typ) => {
511 try!(self.print_type(&**typ));
514 hir::TyBareFn(ref f) => {
515 let generics = hir::Generics {
516 lifetimes: f.lifetimes.clone(),
517 ty_params: OwnedSlice::empty(),
518 where_clause: hir::WhereClause {
519 id: ast::DUMMY_NODE_ID,
520 predicates: Vec::new(),
523 try!(self.print_ty_fn(f.abi, f.unsafety, &*f.decl, None, &generics, None));
525 hir::TyPath(None, ref path) => {
526 try!(self.print_path(path, false, 0));
528 hir::TyPath(Some(ref qself), ref path) => {
529 try!(self.print_qpath(path, qself, false))
531 hir::TyObjectSum(ref ty, ref bounds) => {
532 try!(self.print_type(&**ty));
533 try!(self.print_bounds("+", &bounds[..]));
535 hir::TyPolyTraitRef(ref bounds) => {
536 try!(self.print_bounds("", &bounds[..]));
538 hir::TyFixedLengthVec(ref ty, ref v) => {
539 try!(word(&mut self.s, "["));
540 try!(self.print_type(&**ty));
541 try!(word(&mut self.s, "; "));
542 try!(self.print_expr(&**v));
543 try!(word(&mut self.s, "]"));
545 hir::TyTypeof(ref e) => {
546 try!(word(&mut self.s, "typeof("));
547 try!(self.print_expr(&**e));
548 try!(word(&mut self.s, ")"));
551 try!(word(&mut self.s, "_"));
557 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
558 try!(self.hardbreak_if_not_bol());
559 try!(self.maybe_print_comment(item.span.lo));
560 try!(self.print_outer_attributes(&item.attrs));
562 hir::ForeignItemFn(ref decl, ref generics) => {
564 try!(self.print_fn(decl,
565 hir::Unsafety::Normal,
566 hir::Constness::NotConst,
572 try!(self.end()); // end head-ibox
573 try!(word(&mut self.s, ";"));
574 self.end() // end the outer fn box
576 hir::ForeignItemStatic(ref t, m) => {
577 try!(self.head(&visibility_qualified(item.vis, "static")));
579 try!(self.word_space("mut"));
581 try!(self.print_name(item.name));
582 try!(self.word_space(":"));
583 try!(self.print_type(&**t));
584 try!(word(&mut self.s, ";"));
585 try!(self.end()); // end the head-ibox
586 self.end() // end the outer cbox
591 fn print_associated_const(&mut self,
594 default: Option<&hir::Expr>,
595 vis: hir::Visibility)
597 try!(word(&mut self.s, &visibility_qualified(vis, "")));
598 try!(self.word_space("const"));
599 try!(self.print_name(name));
600 try!(self.word_space(":"));
601 try!(self.print_type(ty));
602 if let Some(expr) = default {
603 try!(space(&mut self.s));
604 try!(self.word_space("="));
605 try!(self.print_expr(expr));
607 word(&mut self.s, ";")
610 fn print_associated_type(&mut self,
612 bounds: Option<&hir::TyParamBounds>,
613 ty: Option<&hir::Ty>)
615 try!(self.word_space("type"));
616 try!(self.print_name(name));
617 if let Some(bounds) = bounds {
618 try!(self.print_bounds(":", bounds));
620 if let Some(ty) = ty {
621 try!(space(&mut self.s));
622 try!(self.word_space("="));
623 try!(self.print_type(ty));
625 word(&mut self.s, ";")
628 /// Pretty-print an item
629 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
630 try!(self.hardbreak_if_not_bol());
631 try!(self.maybe_print_comment(item.span.lo));
632 try!(self.print_outer_attributes(&item.attrs));
633 try!(self.ann.pre(self, NodeItem(item)));
635 hir::ItemExternCrate(ref optional_path) => {
636 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
637 if let Some(p) = *optional_path {
638 let val = p.as_str();
639 if val.contains("-") {
640 try!(self.print_string(&val, ast::CookedStr));
642 try!(self.print_name(p));
644 try!(space(&mut self.s));
645 try!(word(&mut self.s, "as"));
646 try!(space(&mut self.s));
648 try!(self.print_name(item.name));
649 try!(word(&mut self.s, ";"));
650 try!(self.end()); // end inner head-block
651 try!(self.end()); // end outer head-block
653 hir::ItemUse(ref vp) => {
654 try!(self.head(&visibility_qualified(item.vis, "use")));
655 try!(self.print_view_path(&**vp));
656 try!(word(&mut self.s, ";"));
657 try!(self.end()); // end inner head-block
658 try!(self.end()); // end outer head-block
660 hir::ItemStatic(ref ty, m, ref expr) => {
661 try!(self.head(&visibility_qualified(item.vis, "static")));
662 if m == hir::MutMutable {
663 try!(self.word_space("mut"));
665 try!(self.print_name(item.name));
666 try!(self.word_space(":"));
667 try!(self.print_type(&**ty));
668 try!(space(&mut self.s));
669 try!(self.end()); // end the head-ibox
671 try!(self.word_space("="));
672 try!(self.print_expr(&**expr));
673 try!(word(&mut self.s, ";"));
674 try!(self.end()); // end the outer cbox
676 hir::ItemConst(ref ty, ref expr) => {
677 try!(self.head(&visibility_qualified(item.vis, "const")));
678 try!(self.print_name(item.name));
679 try!(self.word_space(":"));
680 try!(self.print_type(&**ty));
681 try!(space(&mut self.s));
682 try!(self.end()); // end the head-ibox
684 try!(self.word_space("="));
685 try!(self.print_expr(&**expr));
686 try!(word(&mut self.s, ";"));
687 try!(self.end()); // end the outer cbox
689 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
691 try!(self.print_fn(decl,
699 try!(word(&mut self.s, " "));
700 try!(self.print_block_with_attrs(&**body, &item.attrs));
702 hir::ItemMod(ref _mod) => {
703 try!(self.head(&visibility_qualified(item.vis, "mod")));
704 try!(self.print_name(item.name));
707 try!(self.print_mod(_mod, &item.attrs));
708 try!(self.bclose(item.span));
710 hir::ItemForeignMod(ref nmod) => {
711 try!(self.head("extern"));
712 try!(self.word_nbsp(&nmod.abi.to_string()));
714 try!(self.print_foreign_mod(nmod, &item.attrs));
715 try!(self.bclose(item.span));
717 hir::ItemTy(ref ty, ref params) => {
718 try!(self.ibox(indent_unit));
720 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
721 try!(self.print_name(item.name));
722 try!(self.print_generics(params));
723 try!(self.end()); // end the inner ibox
725 try!(self.print_where_clause(¶ms.where_clause));
726 try!(space(&mut self.s));
727 try!(self.word_space("="));
728 try!(self.print_type(&**ty));
729 try!(word(&mut self.s, ";"));
730 try!(self.end()); // end the outer ibox
732 hir::ItemEnum(ref enum_definition, ref params) => {
733 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
735 hir::ItemStruct(ref struct_def, ref generics) => {
736 try!(self.head(&visibility_qualified(item.vis, "struct")));
737 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
740 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
742 try!(self.print_visibility(item.vis));
743 try!(self.print_unsafety(unsafety));
744 try!(self.word_nbsp("impl"));
745 try!(self.print_trait_ref(trait_ref));
746 try!(space(&mut self.s));
747 try!(self.word_space("for"));
748 try!(self.word_space(".."));
750 try!(self.bclose(item.span));
752 hir::ItemImpl(unsafety,
759 try!(self.print_visibility(item.vis));
760 try!(self.print_unsafety(unsafety));
761 try!(self.word_nbsp("impl"));
763 if generics.is_parameterized() {
764 try!(self.print_generics(generics));
765 try!(space(&mut self.s));
769 hir::ImplPolarity::Negative => {
770 try!(word(&mut self.s, "!"));
777 try!(self.print_trait_ref(t));
778 try!(space(&mut self.s));
779 try!(self.word_space("for"));
784 try!(self.print_type(&**ty));
785 try!(self.print_where_clause(&generics.where_clause));
787 try!(space(&mut self.s));
789 try!(self.print_inner_attributes(&item.attrs));
790 for impl_item in impl_items {
791 try!(self.print_impl_item(impl_item));
793 try!(self.bclose(item.span));
795 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
797 try!(self.print_visibility(item.vis));
798 try!(self.print_unsafety(unsafety));
799 try!(self.word_nbsp("trait"));
800 try!(self.print_name(item.name));
801 try!(self.print_generics(generics));
802 let mut real_bounds = Vec::with_capacity(bounds.len());
803 for b in bounds.iter() {
804 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
805 try!(space(&mut self.s));
806 try!(self.word_space("for ?"));
807 try!(self.print_trait_ref(&ptr.trait_ref));
809 real_bounds.push(b.clone());
812 try!(self.print_bounds(":", &real_bounds[..]));
813 try!(self.print_where_clause(&generics.where_clause));
814 try!(word(&mut self.s, " "));
816 for trait_item in trait_items {
817 try!(self.print_trait_item(trait_item));
819 try!(self.bclose(item.span));
822 self.ann.post(self, NodeItem(item))
825 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
826 self.print_path(&t.path, false, 0)
829 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
830 if !lifetimes.is_empty() {
831 try!(word(&mut self.s, "for<"));
832 let mut comma = false;
833 for lifetime_def in lifetimes {
835 try!(self.word_space(","))
837 try!(self.print_lifetime_def(lifetime_def));
840 try!(word(&mut self.s, ">"));
845 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
846 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
847 self.print_trait_ref(&t.trait_ref)
850 pub fn print_enum_def(&mut self,
851 enum_definition: &hir::EnumDef,
852 generics: &hir::Generics,
855 visibility: hir::Visibility)
857 try!(self.head(&visibility_qualified(visibility, "enum")));
858 try!(self.print_name(name));
859 try!(self.print_generics(generics));
860 try!(self.print_where_clause(&generics.where_clause));
861 try!(space(&mut self.s));
862 self.print_variants(&enum_definition.variants, span)
865 pub fn print_variants(&mut self,
866 variants: &[P<hir::Variant>],
871 try!(self.space_if_not_bol());
872 try!(self.maybe_print_comment(v.span.lo));
873 try!(self.print_outer_attributes(&v.node.attrs));
874 try!(self.ibox(indent_unit));
875 try!(self.print_variant(&**v));
876 try!(word(&mut self.s, ","));
878 try!(self.maybe_print_trailing_comment(v.span, None));
883 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
885 hir::Public => self.word_nbsp("pub"),
886 hir::Inherited => Ok(()),
890 pub fn print_struct(&mut self,
891 struct_def: &hir::VariantData,
892 generics: &hir::Generics,
895 print_finalizer: bool)
897 try!(self.print_name(name));
898 try!(self.print_generics(generics));
899 if !struct_def.is_struct() {
900 if struct_def.is_tuple() {
902 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
903 match field.node.kind {
904 hir::NamedField(..) => panic!("unexpected named field"),
905 hir::UnnamedField(vis) => {
906 try!(s.print_visibility(vis));
907 try!(s.maybe_print_comment(field.span.lo));
908 s.print_type(&*field.node.ty)
914 try!(self.print_where_clause(&generics.where_clause));
916 try!(word(&mut self.s, ";"));
919 self.end() // close the outer-box
921 try!(self.print_where_clause(&generics.where_clause));
924 try!(self.hardbreak_if_not_bol());
926 for field in struct_def.fields() {
927 match field.node.kind {
928 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
929 hir::NamedField(name, visibility) => {
930 try!(self.hardbreak_if_not_bol());
931 try!(self.maybe_print_comment(field.span.lo));
932 try!(self.print_outer_attributes(&field.node.attrs));
933 try!(self.print_visibility(visibility));
934 try!(self.print_name(name));
935 try!(self.word_nbsp(":"));
936 try!(self.print_type(&*field.node.ty));
937 try!(word(&mut self.s, ","));
946 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
948 let generics = ::util::empty_generics();
949 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
950 match v.node.disr_expr {
952 try!(space(&mut self.s));
953 try!(self.word_space("="));
954 self.print_expr(&**d)
960 pub fn print_method_sig(&mut self,
963 vis: hir::Visibility)
965 self.print_fn(&m.decl,
971 Some(&m.explicit_self.node),
975 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
976 try!(self.ann.pre(self, NodeSubItem(ti.id)));
977 try!(self.hardbreak_if_not_bol());
978 try!(self.maybe_print_comment(ti.span.lo));
979 try!(self.print_outer_attributes(&ti.attrs));
981 hir::ConstTraitItem(ref ty, ref default) => {
982 try!(self.print_associated_const(ti.name,
984 default.as_ref().map(|expr| &**expr),
987 hir::MethodTraitItem(ref sig, ref body) => {
991 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
992 if let Some(ref body) = *body {
994 try!(self.print_block_with_attrs(body, &ti.attrs));
996 try!(word(&mut self.s, ";"));
999 hir::TypeTraitItem(ref bounds, ref default) => {
1000 try!(self.print_associated_type(ti.name,
1002 default.as_ref().map(|ty| &**ty)));
1005 self.ann.post(self, NodeSubItem(ti.id))
1008 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1009 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1010 try!(self.hardbreak_if_not_bol());
1011 try!(self.maybe_print_comment(ii.span.lo));
1012 try!(self.print_outer_attributes(&ii.attrs));
1014 hir::ImplItem_::Const(ref ty, ref expr) => {
1015 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1017 hir::ImplItem_::Method(ref sig, ref body) => {
1018 try!(self.head(""));
1019 try!(self.print_method_sig(ii.name, sig, ii.vis));
1021 try!(self.print_block_with_attrs(body, &ii.attrs));
1023 hir::ImplItem_::Type(ref ty) => {
1024 try!(self.print_associated_type(ii.name, None, Some(ty)));
1027 self.ann.post(self, NodeSubItem(ii.id))
1030 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1031 try!(self.maybe_print_comment(st.span.lo));
1033 hir::StmtDecl(ref decl, _) => {
1034 try!(self.print_decl(&**decl));
1036 hir::StmtExpr(ref expr, _) => {
1037 try!(self.space_if_not_bol());
1038 try!(self.print_expr(&**expr));
1040 hir::StmtSemi(ref expr, _) => {
1041 try!(self.space_if_not_bol());
1042 try!(self.print_expr(&**expr));
1043 try!(word(&mut self.s, ";"));
1046 if stmt_ends_with_semi(&st.node) {
1047 try!(word(&mut self.s, ";"));
1049 self.maybe_print_trailing_comment(st.span, None)
1052 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1053 self.print_block_with_attrs(blk, &[])
1056 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1057 self.print_block_unclosed_indent(blk, indent_unit)
1060 pub fn print_block_unclosed_indent(&mut self,
1064 self.print_block_maybe_unclosed(blk, indented, &[], false)
1067 pub fn print_block_with_attrs(&mut self,
1069 attrs: &[ast::Attribute])
1071 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1074 pub fn print_block_maybe_unclosed(&mut self,
1077 attrs: &[ast::Attribute],
1081 hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1082 hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1083 hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1084 hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1085 hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1086 hir::DefaultBlock => (),
1088 try!(self.maybe_print_comment(blk.span.lo));
1089 try!(self.ann.pre(self, NodeBlock(blk)));
1092 try!(self.print_inner_attributes(attrs));
1094 for st in &blk.stmts {
1095 try!(self.print_stmt(&**st));
1099 try!(self.space_if_not_bol());
1100 try!(self.print_expr(&**expr));
1101 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1105 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1106 self.ann.post(self, NodeBlock(blk))
1109 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1113 // "another else-if"
1114 hir::ExprIf(ref i, ref then, ref e) => {
1115 try!(self.cbox(indent_unit - 1));
1117 try!(word(&mut self.s, " else if "));
1118 try!(self.print_expr(&**i));
1119 try!(space(&mut self.s));
1120 try!(self.print_block(&**then));
1121 self.print_else(e.as_ref().map(|e| &**e))
1124 hir::ExprBlock(ref b) => {
1125 try!(self.cbox(indent_unit - 1));
1127 try!(word(&mut self.s, " else "));
1128 self.print_block(&**b)
1130 // BLEAH, constraints would be great here
1132 panic!("print_if saw if with weird alternative");
1140 pub fn print_if(&mut self,
1143 elseopt: Option<&hir::Expr>)
1145 try!(self.head("if"));
1146 try!(self.print_expr(test));
1147 try!(space(&mut self.s));
1148 try!(self.print_block(blk));
1149 self.print_else(elseopt)
1152 pub fn print_if_let(&mut self,
1156 elseopt: Option<&hir::Expr>)
1158 try!(self.head("if let"));
1159 try!(self.print_pat(pat));
1160 try!(space(&mut self.s));
1161 try!(self.word_space("="));
1162 try!(self.print_expr(expr));
1163 try!(space(&mut self.s));
1164 try!(self.print_block(blk));
1165 self.print_else(elseopt)
1169 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1171 try!(self.commasep_exprs(Inconsistent, args));
1175 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1176 let needs_par = needs_parentheses(expr);
1180 try!(self.print_expr(expr));
1182 try!(self.pclose());
1187 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1188 try!(self.ibox(indent_unit));
1189 try!(word(&mut self.s, "["));
1190 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1191 try!(word(&mut self.s, "]"));
1195 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1196 try!(self.ibox(indent_unit));
1197 try!(word(&mut self.s, "["));
1198 try!(self.print_expr(element));
1199 try!(self.word_space(";"));
1200 try!(self.print_expr(count));
1201 try!(word(&mut self.s, "]"));
1205 fn print_expr_struct(&mut self,
1207 fields: &[hir::Field],
1208 wth: &Option<P<hir::Expr>>)
1210 try!(self.print_path(path, true, 0));
1211 try!(word(&mut self.s, "{"));
1212 try!(self.commasep_cmnt(Consistent,
1215 try!(s.ibox(indent_unit));
1216 try!(s.print_name(field.name.node));
1217 try!(s.word_space(":"));
1218 try!(s.print_expr(&*field.expr));
1224 try!(self.ibox(indent_unit));
1225 if !fields.is_empty() {
1226 try!(word(&mut self.s, ","));
1227 try!(space(&mut self.s));
1229 try!(word(&mut self.s, ".."));
1230 try!(self.print_expr(&**expr));
1233 _ => if !fields.is_empty() {
1234 try!(word(&mut self.s, ","))
1237 try!(word(&mut self.s, "}"));
1241 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1243 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1244 if exprs.len() == 1 {
1245 try!(word(&mut self.s, ","));
1250 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1251 try!(self.print_expr_maybe_paren(func));
1252 self.print_call_post(args)
1255 fn print_expr_method_call(&mut self,
1256 name: Spanned<ast::Name>,
1258 args: &[P<hir::Expr>])
1260 let base_args = &args[1..];
1261 try!(self.print_expr(&*args[0]));
1262 try!(word(&mut self.s, "."));
1263 try!(self.print_name(name.node));
1264 if !tys.is_empty() {
1265 try!(word(&mut self.s, "::<"));
1266 try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty)));
1267 try!(word(&mut self.s, ">"));
1269 self.print_call_post(base_args)
1272 fn print_expr_binary(&mut self,
1277 try!(self.print_expr(lhs));
1278 try!(space(&mut self.s));
1279 try!(self.word_space(::util::binop_to_string(op.node)));
1280 self.print_expr(rhs)
1283 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1284 try!(word(&mut self.s, ::util::unop_to_string(op)));
1285 self.print_expr_maybe_paren(expr)
1288 fn print_expr_addr_of(&mut self,
1289 mutability: hir::Mutability,
1292 try!(word(&mut self.s, "&"));
1293 try!(self.print_mutability(mutability));
1294 self.print_expr_maybe_paren(expr)
1297 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1298 try!(self.maybe_print_comment(expr.span.lo));
1299 try!(self.ibox(indent_unit));
1300 try!(self.ann.pre(self, NodeExpr(expr)));
1302 hir::ExprBox(ref expr) => {
1303 try!(self.word_space("box"));
1304 try!(self.print_expr(expr));
1306 hir::ExprVec(ref exprs) => {
1307 try!(self.print_expr_vec(&exprs[..]));
1309 hir::ExprRepeat(ref element, ref count) => {
1310 try!(self.print_expr_repeat(&**element, &**count));
1312 hir::ExprStruct(ref path, ref fields, ref wth) => {
1313 try!(self.print_expr_struct(path, &fields[..], wth));
1315 hir::ExprTup(ref exprs) => {
1316 try!(self.print_expr_tup(&exprs[..]));
1318 hir::ExprCall(ref func, ref args) => {
1319 try!(self.print_expr_call(&**func, &args[..]));
1321 hir::ExprMethodCall(name, ref tys, ref args) => {
1322 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1324 hir::ExprBinary(op, ref lhs, ref rhs) => {
1325 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1327 hir::ExprUnary(op, ref expr) => {
1328 try!(self.print_expr_unary(op, &**expr));
1330 hir::ExprAddrOf(m, ref expr) => {
1331 try!(self.print_expr_addr_of(m, &**expr));
1333 hir::ExprLit(ref lit) => {
1334 try!(self.print_literal(&**lit));
1336 hir::ExprCast(ref expr, ref ty) => {
1337 try!(self.print_expr(&**expr));
1338 try!(space(&mut self.s));
1339 try!(self.word_space("as"));
1340 try!(self.print_type(&**ty));
1342 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1343 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1345 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1346 if let Some(ident) = opt_ident {
1347 try!(self.print_name(ident.name));
1348 try!(self.word_space(":"));
1350 try!(self.head("while"));
1351 try!(self.print_expr(&**test));
1352 try!(space(&mut self.s));
1353 try!(self.print_block(&**blk));
1355 hir::ExprLoop(ref blk, opt_ident) => {
1356 if let Some(ident) = opt_ident {
1357 try!(self.print_name(ident.name));
1358 try!(self.word_space(":"));
1360 try!(self.head("loop"));
1361 try!(space(&mut self.s));
1362 try!(self.print_block(&**blk));
1364 hir::ExprMatch(ref expr, ref arms, _) => {
1365 try!(self.cbox(indent_unit));
1367 try!(self.word_nbsp("match"));
1368 try!(self.print_expr(&**expr));
1369 try!(space(&mut self.s));
1372 try!(self.print_arm(arm));
1374 try!(self.bclose_(expr.span, indent_unit));
1376 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1377 try!(self.print_capture_clause(capture_clause));
1379 try!(self.print_fn_block_args(&**decl));
1380 try!(space(&mut self.s));
1382 let default_return = match decl.output {
1383 hir::DefaultReturn(..) => true,
1387 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1388 try!(self.print_block_unclosed(&**body));
1390 // we extract the block, so as not to create another set of boxes
1391 match body.expr.as_ref().unwrap().node {
1392 hir::ExprBlock(ref blk) => {
1393 try!(self.print_block_unclosed(&**blk));
1396 // this is a bare expression
1397 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1398 try!(self.end()); // need to close a box
1402 // a box will be closed by print_expr, but we didn't want an overall
1403 // wrapper so we closed the corresponding opening. so create an
1404 // empty box to satisfy the close.
1407 hir::ExprBlock(ref blk) => {
1408 // containing cbox, will be closed by print-block at }
1409 try!(self.cbox(indent_unit));
1410 // head-box, will be closed by print-block after {
1412 try!(self.print_block(&**blk));
1414 hir::ExprAssign(ref lhs, ref rhs) => {
1415 try!(self.print_expr(&**lhs));
1416 try!(space(&mut self.s));
1417 try!(self.word_space("="));
1418 try!(self.print_expr(&**rhs));
1420 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1421 try!(self.print_expr(&**lhs));
1422 try!(space(&mut self.s));
1423 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1424 try!(self.word_space("="));
1425 try!(self.print_expr(&**rhs));
1427 hir::ExprField(ref expr, name) => {
1428 try!(self.print_expr(&**expr));
1429 try!(word(&mut self.s, "."));
1430 try!(self.print_name(name.node));
1432 hir::ExprTupField(ref expr, id) => {
1433 try!(self.print_expr(&**expr));
1434 try!(word(&mut self.s, "."));
1435 try!(self.print_usize(id.node));
1437 hir::ExprIndex(ref expr, ref index) => {
1438 try!(self.print_expr(&**expr));
1439 try!(word(&mut self.s, "["));
1440 try!(self.print_expr(&**index));
1441 try!(word(&mut self.s, "]"));
1443 hir::ExprRange(ref start, ref end) => {
1444 if let &Some(ref e) = start {
1445 try!(self.print_expr(&**e));
1447 try!(word(&mut self.s, ".."));
1448 if let &Some(ref e) = end {
1449 try!(self.print_expr(&**e));
1452 hir::ExprPath(None, ref path) => {
1453 try!(self.print_path(path, true, 0))
1455 hir::ExprPath(Some(ref qself), ref path) => {
1456 try!(self.print_qpath(path, qself, true))
1458 hir::ExprBreak(opt_ident) => {
1459 try!(word(&mut self.s, "break"));
1460 try!(space(&mut self.s));
1461 if let Some(ident) = opt_ident {
1462 try!(self.print_name(ident.node.name));
1463 try!(space(&mut self.s));
1466 hir::ExprAgain(opt_ident) => {
1467 try!(word(&mut self.s, "continue"));
1468 try!(space(&mut self.s));
1469 if let Some(ident) = opt_ident {
1470 try!(self.print_name(ident.node.name));
1471 try!(space(&mut self.s))
1474 hir::ExprRet(ref result) => {
1475 try!(word(&mut self.s, "return"));
1478 try!(word(&mut self.s, " "));
1479 try!(self.print_expr(&**expr));
1484 hir::ExprInlineAsm(ref a) => {
1485 try!(word(&mut self.s, "asm!"));
1487 try!(self.print_string(&a.asm, a.asm_str_style));
1488 try!(self.word_space(":"));
1490 try!(self.commasep(Inconsistent, &a.outputs, |s, &(ref co, ref o, is_rw)| {
1491 match co.slice_shift_char() {
1492 Some(('=', operand)) if is_rw => {
1493 try!(s.print_string(&format!("+{}", operand), ast::CookedStr))
1495 _ => try!(s.print_string(&co, ast::CookedStr)),
1498 try!(s.print_expr(&**o));
1502 try!(space(&mut self.s));
1503 try!(self.word_space(":"));
1505 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1506 try!(s.print_string(&co, ast::CookedStr));
1508 try!(s.print_expr(&**o));
1512 try!(space(&mut self.s));
1513 try!(self.word_space(":"));
1515 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1516 try!(s.print_string(&co, ast::CookedStr));
1520 let mut options = vec![];
1522 options.push("volatile");
1525 options.push("alignstack");
1527 if a.dialect == ast::AsmDialect::Intel {
1528 options.push("intel");
1531 if !options.is_empty() {
1532 try!(space(&mut self.s));
1533 try!(self.word_space(":"));
1534 try!(self.commasep(Inconsistent, &*options, |s, &co| {
1535 try!(s.print_string(co, ast::CookedStr));
1540 try!(self.pclose());
1543 try!(self.ann.post(self, NodeExpr(expr)));
1547 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1548 try!(self.print_pat(&*loc.pat));
1549 if let Some(ref ty) = loc.ty {
1550 try!(self.word_space(":"));
1551 try!(self.print_type(&**ty));
1556 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1557 try!(self.maybe_print_comment(decl.span.lo));
1559 hir::DeclLocal(ref loc) => {
1560 try!(self.space_if_not_bol());
1561 try!(self.ibox(indent_unit));
1562 try!(self.word_nbsp("let"));
1564 try!(self.ibox(indent_unit));
1565 try!(self.print_local_decl(&**loc));
1567 if let Some(ref init) = loc.init {
1569 try!(self.word_space("="));
1570 try!(self.print_expr(&**init));
1574 hir::DeclItem(ref item) => self.print_item(&**item),
1578 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1579 word(&mut self.s, &i.to_string())
1582 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1583 try!(word(&mut self.s, &name.as_str()));
1584 self.ann.post(self, NodeName(&name))
1587 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1588 try!(self.print_local_decl(loc));
1589 try!(space(&mut self.s));
1590 try!(self.word_space("in"));
1591 self.print_expr(coll)
1594 fn print_path(&mut self,
1596 colons_before_params: bool,
1599 try!(self.maybe_print_comment(path.span.lo));
1601 let mut first = !path.global;
1602 for segment in &path.segments[..path.segments.len() - depth] {
1606 try!(word(&mut self.s, "::"))
1609 try!(self.print_name(segment.identifier.name));
1611 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1617 fn print_qpath(&mut self,
1620 colons_before_params: bool)
1622 try!(word(&mut self.s, "<"));
1623 try!(self.print_type(&qself.ty));
1624 if qself.position > 0 {
1625 try!(space(&mut self.s));
1626 try!(self.word_space("as"));
1627 let depth = path.segments.len() - qself.position;
1628 try!(self.print_path(&path, false, depth));
1630 try!(word(&mut self.s, ">"));
1631 try!(word(&mut self.s, "::"));
1632 let item_segment = path.segments.last().unwrap();
1633 try!(self.print_name(item_segment.identifier.name));
1634 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1637 fn print_path_parameters(&mut self,
1638 parameters: &hir::PathParameters,
1639 colons_before_params: bool)
1641 if parameters.is_empty() {
1645 if colons_before_params {
1646 try!(word(&mut self.s, "::"))
1650 hir::AngleBracketedParameters(ref data) => {
1651 try!(word(&mut self.s, "<"));
1653 let mut comma = false;
1654 for lifetime in &data.lifetimes {
1656 try!(self.word_space(","))
1658 try!(self.print_lifetime(lifetime));
1662 if !data.types.is_empty() {
1664 try!(self.word_space(","))
1666 try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&**ty)));
1670 for binding in data.bindings.iter() {
1672 try!(self.word_space(","))
1674 try!(self.print_name(binding.name));
1675 try!(space(&mut self.s));
1676 try!(self.word_space("="));
1677 try!(self.print_type(&*binding.ty));
1681 try!(word(&mut self.s, ">"))
1684 hir::ParenthesizedParameters(ref data) => {
1685 try!(word(&mut self.s, "("));
1686 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&**ty)));
1687 try!(word(&mut self.s, ")"));
1692 try!(self.space_if_not_bol());
1693 try!(self.word_space("->"));
1694 try!(self.print_type(&**ty));
1703 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1704 try!(self.maybe_print_comment(pat.span.lo));
1705 try!(self.ann.pre(self, NodePat(pat)));
1706 // Pat isn't normalized, but the beauty of it
1707 // is that it doesn't matter
1709 hir::PatWild => try!(word(&mut self.s, "_")),
1710 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1711 match binding_mode {
1712 hir::BindByRef(mutbl) => {
1713 try!(self.word_nbsp("ref"));
1714 try!(self.print_mutability(mutbl));
1716 hir::BindByValue(hir::MutImmutable) => {}
1717 hir::BindByValue(hir::MutMutable) => {
1718 try!(self.word_nbsp("mut"));
1721 try!(self.print_name(path1.node.name));
1724 try!(word(&mut self.s, "@"));
1725 try!(self.print_pat(&**p));
1730 hir::PatEnum(ref path, ref args_) => {
1731 try!(self.print_path(path, true, 0));
1733 None => try!(word(&mut self.s, "(..)")),
1735 if !args.is_empty() {
1737 try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&**p)));
1738 try!(self.pclose());
1743 hir::PatQPath(ref qself, ref path) => {
1744 try!(self.print_qpath(path, qself, false));
1746 hir::PatStruct(ref path, ref fields, etc) => {
1747 try!(self.print_path(path, true, 0));
1749 try!(self.word_space("{"));
1750 try!(self.commasep_cmnt(Consistent,
1753 try!(s.cbox(indent_unit));
1754 if !f.node.is_shorthand {
1755 try!(s.print_name(f.node.name));
1756 try!(s.word_nbsp(":"));
1758 try!(s.print_pat(&*f.node.pat));
1761 |f| f.node.pat.span));
1763 if !fields.is_empty() {
1764 try!(self.word_space(","));
1766 try!(word(&mut self.s, ".."));
1768 try!(space(&mut self.s));
1769 try!(word(&mut self.s, "}"));
1771 hir::PatTup(ref elts) => {
1773 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&**p)));
1774 if elts.len() == 1 {
1775 try!(word(&mut self.s, ","));
1777 try!(self.pclose());
1779 hir::PatBox(ref inner) => {
1780 try!(word(&mut self.s, "box "));
1781 try!(self.print_pat(&**inner));
1783 hir::PatRegion(ref inner, mutbl) => {
1784 try!(word(&mut self.s, "&"));
1785 if mutbl == hir::MutMutable {
1786 try!(word(&mut self.s, "mut "));
1788 try!(self.print_pat(&**inner));
1790 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1791 hir::PatRange(ref begin, ref end) => {
1792 try!(self.print_expr(&**begin));
1793 try!(space(&mut self.s));
1794 try!(word(&mut self.s, "..."));
1795 try!(self.print_expr(&**end));
1797 hir::PatVec(ref before, ref slice, ref after) => {
1798 try!(word(&mut self.s, "["));
1799 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&**p)));
1800 if let Some(ref p) = *slice {
1801 if !before.is_empty() {
1802 try!(self.word_space(","));
1804 if p.node != hir::PatWild {
1805 try!(self.print_pat(&**p));
1807 try!(word(&mut self.s, ".."));
1808 if !after.is_empty() {
1809 try!(self.word_space(","));
1812 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&**p)));
1813 try!(word(&mut self.s, "]"));
1816 self.ann.post(self, NodePat(pat))
1819 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1820 // I have no idea why this check is necessary, but here it
1822 if arm.attrs.is_empty() {
1823 try!(space(&mut self.s));
1825 try!(self.cbox(indent_unit));
1827 try!(self.print_outer_attributes(&arm.attrs));
1828 let mut first = true;
1829 for p in &arm.pats {
1833 try!(space(&mut self.s));
1834 try!(self.word_space("|"));
1836 try!(self.print_pat(&**p));
1838 try!(space(&mut self.s));
1839 if let Some(ref e) = arm.guard {
1840 try!(self.word_space("if"));
1841 try!(self.print_expr(&**e));
1842 try!(space(&mut self.s));
1844 try!(self.word_space("=>"));
1846 match arm.body.node {
1847 hir::ExprBlock(ref blk) => {
1848 // the block will close the pattern's ibox
1849 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1851 // If it is a user-provided unsafe block, print a comma after it
1852 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1853 try!(word(&mut self.s, ","));
1857 try!(self.end()); // close the ibox for the pattern
1858 try!(self.print_expr(&*arm.body));
1859 try!(word(&mut self.s, ","));
1862 self.end() // close enclosing cbox
1865 // Returns whether it printed anything
1866 fn print_explicit_self(&mut self,
1867 explicit_self: &hir::ExplicitSelf_,
1868 mutbl: hir::Mutability)
1869 -> io::Result<bool> {
1870 try!(self.print_mutability(mutbl));
1871 match *explicit_self {
1872 hir::SelfStatic => {
1875 hir::SelfValue(_) => {
1876 try!(word(&mut self.s, "self"));
1878 hir::SelfRegion(ref lt, m, _) => {
1879 try!(word(&mut self.s, "&"));
1880 try!(self.print_opt_lifetime(lt));
1881 try!(self.print_mutability(m));
1882 try!(word(&mut self.s, "self"));
1884 hir::SelfExplicit(ref typ, _) => {
1885 try!(word(&mut self.s, "self"));
1886 try!(self.word_space(":"));
1887 try!(self.print_type(&**typ));
1893 pub fn print_fn(&mut self,
1895 unsafety: hir::Unsafety,
1896 constness: hir::Constness,
1898 name: Option<ast::Name>,
1899 generics: &hir::Generics,
1900 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1901 vis: hir::Visibility)
1903 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1905 if let Some(name) = name {
1907 try!(self.print_name(name));
1909 try!(self.print_generics(generics));
1910 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1911 self.print_where_clause(&generics.where_clause)
1914 pub fn print_fn_args(&mut self,
1916 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1918 // It is unfortunate to duplicate the commasep logic, but we want the
1919 // self type and the args all in the same box.
1920 try!(self.rbox(0, Inconsistent));
1921 let mut first = true;
1922 if let Some(explicit_self) = opt_explicit_self {
1923 let m = match explicit_self {
1924 &hir::SelfStatic => hir::MutImmutable,
1925 _ => match decl.inputs[0].pat.node {
1926 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1927 _ => hir::MutImmutable,
1930 first = !try!(self.print_explicit_self(explicit_self, m));
1933 // HACK(eddyb) ignore the separately printed self argument.
1934 let args = if first {
1944 try!(self.word_space(","));
1946 try!(self.print_arg(arg));
1952 pub fn print_fn_args_and_ret(&mut self,
1954 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1957 try!(self.print_fn_args(decl, opt_explicit_self));
1959 try!(word(&mut self.s, ", ..."));
1961 try!(self.pclose());
1963 self.print_fn_output(decl)
1966 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1967 try!(word(&mut self.s, "|"));
1968 try!(self.print_fn_args(decl, None));
1969 try!(word(&mut self.s, "|"));
1971 if let hir::DefaultReturn(..) = decl.output {
1975 try!(self.space_if_not_bol());
1976 try!(self.word_space("->"));
1978 hir::Return(ref ty) => {
1979 try!(self.print_type(&**ty));
1980 self.maybe_print_comment(ty.span.lo)
1982 hir::DefaultReturn(..) => unreachable!(),
1983 hir::NoReturn(span) => {
1984 try!(self.word_nbsp("!"));
1985 self.maybe_print_comment(span.lo)
1990 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1991 match capture_clause {
1992 hir::CaptureByValue => self.word_space("move"),
1993 hir::CaptureByRef => Ok(()),
1997 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1998 if !bounds.is_empty() {
1999 try!(word(&mut self.s, prefix));
2000 let mut first = true;
2001 for bound in bounds {
2006 try!(self.word_space("+"));
2010 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2011 self.print_poly_trait_ref(tref)
2013 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2014 try!(word(&mut self.s, "?"));
2015 self.print_poly_trait_ref(tref)
2017 RegionTyParamBound(ref lt) => {
2018 self.print_lifetime(lt)
2028 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2029 self.print_name(lifetime.name)
2032 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2033 try!(self.print_lifetime(&lifetime.lifetime));
2035 for v in &lifetime.bounds {
2036 try!(word(&mut self.s, sep));
2037 try!(self.print_lifetime(v));
2043 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2044 let total = generics.lifetimes.len() + generics.ty_params.len();
2049 try!(word(&mut self.s, "<"));
2051 let mut ints = Vec::new();
2056 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2057 if idx < generics.lifetimes.len() {
2058 let lifetime = &generics.lifetimes[idx];
2059 s.print_lifetime_def(lifetime)
2061 let idx = idx - generics.lifetimes.len();
2062 let param = &generics.ty_params[idx];
2063 s.print_ty_param(param)
2067 try!(word(&mut self.s, ">"));
2071 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2072 try!(self.print_name(param.name));
2073 try!(self.print_bounds(":", ¶m.bounds));
2074 match param.default {
2075 Some(ref default) => {
2076 try!(space(&mut self.s));
2077 try!(self.word_space("="));
2078 self.print_type(&**default)
2084 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2085 if where_clause.predicates.is_empty() {
2089 try!(space(&mut self.s));
2090 try!(self.word_space("where"));
2092 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2094 try!(self.word_space(","));
2098 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2102 try!(self.print_formal_lifetime_list(bound_lifetimes));
2103 try!(self.print_type(&**bounded_ty));
2104 try!(self.print_bounds(":", bounds));
2106 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2109 try!(self.print_lifetime(lifetime));
2110 try!(word(&mut self.s, ":"));
2112 for (i, bound) in bounds.iter().enumerate() {
2113 try!(self.print_lifetime(bound));
2116 try!(word(&mut self.s, ":"));
2120 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2121 try!(self.print_path(path, false, 0));
2122 try!(space(&mut self.s));
2123 try!(self.word_space("="));
2124 try!(self.print_type(&**ty));
2132 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2134 hir::ViewPathSimple(name, ref path) => {
2135 try!(self.print_path(path, false, 0));
2137 if path.segments.last().unwrap().identifier.name != name {
2138 try!(space(&mut self.s));
2139 try!(self.word_space("as"));
2140 try!(self.print_name(name));
2146 hir::ViewPathGlob(ref path) => {
2147 try!(self.print_path(path, false, 0));
2148 word(&mut self.s, "::*")
2151 hir::ViewPathList(ref path, ref segments) => {
2152 if path.segments.is_empty() {
2153 try!(word(&mut self.s, "{"));
2155 try!(self.print_path(path, false, 0));
2156 try!(word(&mut self.s, "::{"));
2158 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2160 hir::PathListIdent { name, .. } => {
2163 hir::PathListMod { .. } => {
2164 word(&mut s.s, "self")
2168 word(&mut self.s, "}")
2173 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2175 hir::MutMutable => self.word_nbsp("mut"),
2176 hir::MutImmutable => Ok(()),
2180 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2181 try!(self.print_mutability(mt.mutbl));
2182 self.print_type(&*mt.ty)
2185 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2186 try!(self.ibox(indent_unit));
2187 match input.ty.node {
2188 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2190 match input.pat.node {
2191 hir::PatIdent(_, ref path1, _) if
2193 parse::token::special_idents::invalid.name => {
2197 try!(self.print_pat(&*input.pat));
2198 try!(word(&mut self.s, ":"));
2199 try!(space(&mut self.s));
2202 try!(self.print_type(&*input.ty));
2208 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2209 if let hir::DefaultReturn(..) = decl.output {
2213 try!(self.space_if_not_bol());
2214 try!(self.ibox(indent_unit));
2215 try!(self.word_space("->"));
2217 hir::NoReturn(_) => try!(self.word_nbsp("!")),
2218 hir::DefaultReturn(..) => unreachable!(),
2219 hir::Return(ref ty) => try!(self.print_type(&**ty)),
2224 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2229 pub fn print_ty_fn(&mut self,
2231 unsafety: hir::Unsafety,
2233 name: Option<ast::Name>,
2234 generics: &hir::Generics,
2235 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2237 try!(self.ibox(indent_unit));
2238 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2239 try!(word(&mut self.s, "for"));
2240 try!(self.print_generics(generics));
2242 let generics = hir::Generics {
2243 lifetimes: Vec::new(),
2244 ty_params: OwnedSlice::empty(),
2245 where_clause: hir::WhereClause {
2246 id: ast::DUMMY_NODE_ID,
2247 predicates: Vec::new(),
2250 try!(self.print_fn(decl,
2252 hir::Constness::NotConst,
2261 pub fn maybe_print_trailing_comment(&mut self,
2262 span: codemap::Span,
2263 next_pos: Option<BytePos>)
2265 let cm = match self.cm {
2269 match self.next_comment() {
2271 if (*cmnt).style != comments::Trailing {
2274 let span_line = cm.lookup_char_pos(span.hi);
2275 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2276 let mut next = (*cmnt).pos + BytePos(1);
2279 Some(p) => next = p,
2281 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2282 span_line.line == comment_line.line {
2283 try!(self.print_comment(cmnt));
2284 self.cur_cmnt_and_lit.cur_cmnt += 1;
2292 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2293 // If there aren't any remaining comments, then we need to manually
2294 // make sure there is a line break at the end.
2295 if self.next_comment().is_none() {
2296 try!(hardbreak(&mut self.s));
2299 match self.next_comment() {
2301 try!(self.print_comment(cmnt));
2302 self.cur_cmnt_and_lit.cur_cmnt += 1;
2310 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2311 opt_abi: Option<abi::Abi>)
2314 Some(abi::Rust) => Ok(()),
2316 try!(self.word_nbsp("extern"));
2317 self.word_nbsp(&abi.to_string())
2323 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<abi::Abi>) -> io::Result<()> {
2326 try!(self.word_nbsp("extern"));
2327 self.word_nbsp(&abi.to_string())
2333 pub fn print_fn_header_info(&mut self,
2334 unsafety: hir::Unsafety,
2335 constness: hir::Constness,
2337 vis: hir::Visibility)
2339 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2340 try!(self.print_unsafety(unsafety));
2343 hir::Constness::NotConst => {}
2344 hir::Constness::Const => try!(self.word_nbsp("const")),
2347 if abi != abi::Rust {
2348 try!(self.word_nbsp("extern"));
2349 try!(self.word_nbsp(&abi.to_string()));
2352 word(&mut self.s, "fn")
2355 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2357 hir::Unsafety::Normal => Ok(()),
2358 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2363 // Dup'ed from parse::classify, but adapted for the HIR.
2364 /// Does this expression require a semicolon to be treated
2365 /// as a statement? The negation of this: 'can this expression
2366 /// be used as a statement without a semicolon' -- is used
2367 /// as an early-bail-out in the parser so that, for instance,
2368 /// if true {...} else {...}
2370 /// isn't parsed as (if true {...} else {...} | x) | 5
2371 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2374 hir::ExprMatch(..) |
2376 hir::ExprWhile(..) |
2377 hir::ExprLoop(..) => false,
2382 /// this statement requires a semicolon after it.
2383 /// note that in one case (stmt_semi), we've already
2384 /// seen the semicolon, and thus don't need another.
2385 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2387 hir::StmtDecl(ref d, _) => {
2389 hir::DeclLocal(_) => true,
2390 hir::DeclItem(_) => false,
2393 hir::StmtExpr(ref e, _) => {
2394 expr_requires_semi_to_be_stmt(&**e)
2396 hir::StmtSemi(..) => {