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::{Crate, 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 krate: Option<&'a Crate>,
58 pub s: pp::Printer<'a>,
59 cm: Option<&'a CodeMap>,
60 comments: Option<Vec<comments::Comment>>,
61 literals: Option<Vec<comments::Literal>>,
62 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
63 boxes: Vec<pp::Breaks>,
64 ann: &'a (PpAnn + 'a),
67 impl<'a> PrintState<'a> for State<'a> {
68 fn writer(&mut self) -> &mut pp::Printer<'a> {
72 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
76 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
80 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
81 &mut self.cur_cmnt_and_lit
84 fn literals(&self) -> &Option<Vec<comments::Literal>> {
89 pub fn rust_printer<'a>(writer: Box<Write + 'a>, krate: Option<&'a Crate>) -> State<'a> {
90 static NO_ANN: NoAnn = NoAnn;
91 rust_printer_annotated(writer, &NO_ANN, krate)
94 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>, ann: &'a PpAnn, krate: Option<&'a Crate>) -> State<'a> {
97 s: pp::mk_printer(writer, default_columns),
101 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
110 #[allow(non_upper_case_globals)]
111 pub const indent_unit: usize = 4;
113 #[allow(non_upper_case_globals)]
114 pub const default_columns: usize = 78;
117 /// Requires you to pass an input filename and reader so that
118 /// it can scan the input text for comments and literals to
120 pub fn print_crate<'a>(cm: &'a CodeMap,
121 span_diagnostic: &diagnostic::SpanHandler,
125 out: Box<Write + 'a>,
129 let mut s = State::new_from_input(cm, span_diagnostic, filename, input, out, ann, is_expanded, Some(krate));
131 // When printing the AST, we sometimes need to inject `#[no_std]` here.
132 // Since you can't compile the HIR, it's not necessary.
134 try!(s.print_mod(&krate.module, &krate.attrs));
135 try!(s.print_remaining_comments());
140 pub fn new_from_input(cm: &'a CodeMap,
141 span_diagnostic: &diagnostic::SpanHandler,
144 out: Box<Write + 'a>,
147 krate: Option<&'a Crate>)
149 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
157 // If the code is post expansion, don't use the table of
158 // literals, since it doesn't correspond with the literals
159 // in the AST anymore.
168 pub fn new(cm: &'a CodeMap,
169 out: Box<Write + 'a>,
171 comments: Option<Vec<comments::Comment>>,
172 literals: Option<Vec<comments::Literal>>,
173 krate: Option<&'a Crate>)
177 s: pp::mk_printer(out, default_columns),
179 comments: comments.clone(),
180 literals: literals.clone(),
181 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
191 pub fn to_string<F>(f: F) -> String
192 where F: FnOnce(&mut State) -> io::Result<()>
194 let mut wr = Vec::new();
196 let mut printer = rust_printer(Box::new(&mut wr), None);
197 f(&mut printer).unwrap();
198 eof(&mut printer.s).unwrap();
200 String::from_utf8(wr).unwrap()
203 pub fn binop_to_string(op: BinOpToken) -> &'static str {
209 token::Percent => "%",
218 pub fn ty_to_string(ty: &hir::Ty) -> String {
219 to_string(|s| s.print_type(ty))
222 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
223 to_string(|s| s.print_bounds("", bounds))
226 pub fn pat_to_string(pat: &hir::Pat) -> String {
227 to_string(|s| s.print_pat(pat))
230 pub fn arm_to_string(arm: &hir::Arm) -> String {
231 to_string(|s| s.print_arm(arm))
234 pub fn expr_to_string(e: &hir::Expr) -> String {
235 to_string(|s| s.print_expr(e))
238 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
239 to_string(|s| s.print_lifetime(e))
242 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
243 to_string(|s| s.print_stmt(stmt))
246 pub fn item_to_string(i: &hir::Item) -> String {
247 to_string(|s| s.print_item(i))
250 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
251 to_string(|s| s.print_impl_item(i))
254 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
255 to_string(|s| s.print_trait_item(i))
258 pub fn generics_to_string(generics: &hir::Generics) -> String {
259 to_string(|s| s.print_generics(generics))
262 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
263 to_string(|s| s.print_where_clause(i))
266 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
267 to_string(|s| s.print_fn_block_args(p))
270 pub fn path_to_string(p: &hir::Path) -> String {
271 to_string(|s| s.print_path(p, false, 0))
274 pub fn name_to_string(name: ast::Name) -> String {
275 to_string(|s| s.print_name(name))
278 pub fn fun_to_string(decl: &hir::FnDecl,
279 unsafety: hir::Unsafety,
280 constness: hir::Constness,
282 opt_explicit_self: Option<&hir::ExplicitSelf_>,
283 generics: &hir::Generics)
287 try!(s.print_fn(decl,
295 try!(s.end()); // Close the head box
296 s.end() // Close the outer box
300 pub fn block_to_string(blk: &hir::Block) -> String {
302 // containing cbox, will be closed by print-block at }
303 try!(s.cbox(indent_unit));
304 // head-ibox, will be closed by print-block after {
310 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
311 to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
314 pub fn variant_to_string(var: &hir::Variant) -> String {
315 to_string(|s| s.print_variant(var))
318 pub fn arg_to_string(arg: &hir::Arg) -> String {
319 to_string(|s| s.print_arg(arg))
322 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
324 hir::Public => format!("pub {}", s),
325 hir::Inherited => s.to_string(),
329 fn needs_parentheses(expr: &hir::Expr) -> bool {
331 hir::ExprAssign(..) |
332 hir::ExprBinary(..) |
333 hir::ExprClosure(..) |
334 hir::ExprAssignOp(..) |
335 hir::ExprCast(..) => true,
341 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
342 self.boxes.push(pp::Breaks::Consistent);
343 pp::cbox(&mut self.s, u)
346 pub fn nbsp(&mut self) -> io::Result<()> {
347 word(&mut self.s, " ")
350 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
351 try!(word(&mut self.s, w));
355 pub fn head(&mut self, w: &str) -> io::Result<()> {
356 // outer-box is consistent
357 try!(self.cbox(indent_unit));
358 // head-box is inconsistent
359 try!(self.ibox(w.len() + 1));
360 // keyword that starts the head
362 try!(self.word_nbsp(w));
367 pub fn bopen(&mut self) -> io::Result<()> {
368 try!(word(&mut self.s, "{"));
369 self.end() // close the head-box
372 pub fn bclose_(&mut self, span: codemap::Span, indented: usize) -> io::Result<()> {
373 self.bclose_maybe_open(span, indented, true)
375 pub fn bclose_maybe_open(&mut self,
380 try!(self.maybe_print_comment(span.hi));
381 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
382 try!(word(&mut self.s, "}"));
384 try!(self.end()); // close the outer-box
388 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
389 self.bclose_(span, indent_unit)
392 pub fn in_cbox(&self) -> bool {
393 match self.boxes.last() {
394 Some(&last_box) => last_box == pp::Breaks::Consistent,
398 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
400 try!(space(&mut self.s));
404 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
406 break_offset(&mut self.s, n, off)
408 if off != 0 && self.s.last_token().is_hardbreak_tok() {
409 // We do something pretty sketchy here: tuck the nonzero
410 // offset-adjustment we were going to deposit along with the
411 // break into the previous hardbreak.
412 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
418 // Synthesizes a comment that was not textually present in the original source
420 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
421 try!(word(&mut self.s, "/*"));
422 try!(space(&mut self.s));
423 try!(word(&mut self.s, &text[..]));
424 try!(space(&mut self.s));
425 word(&mut self.s, "*/")
429 pub fn commasep_cmnt<T, F, G>(&mut self,
435 where F: FnMut(&mut State, &T) -> io::Result<()>,
436 G: FnMut(&T) -> codemap::Span
438 try!(self.rbox(0, b));
439 let len = elts.len();
442 try!(self.maybe_print_comment(get_span(elt).hi));
446 try!(word(&mut self.s, ","));
447 try!(self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi)));
448 try!(self.space_if_not_bol());
454 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<hir::Expr>]) -> io::Result<()> {
455 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
458 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
459 try!(self.print_inner_attributes(attrs));
460 for item_id in &_mod.item_ids {
461 try!(self.print_item_id(item_id));
466 pub fn print_foreign_mod(&mut self,
467 nmod: &hir::ForeignMod,
468 attrs: &[ast::Attribute])
470 try!(self.print_inner_attributes(attrs));
471 for item in &nmod.items {
472 try!(self.print_foreign_item(&**item));
477 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
478 if let Some(l) = *lifetime {
479 try!(self.print_lifetime(&l));
485 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
486 try!(self.maybe_print_comment(ty.span.lo));
489 hir::TyVec(ref ty) => {
490 try!(word(&mut self.s, "["));
491 try!(self.print_type(&**ty));
492 try!(word(&mut self.s, "]"));
494 hir::TyPtr(ref mt) => {
495 try!(word(&mut self.s, "*"));
497 hir::MutMutable => try!(self.word_nbsp("mut")),
498 hir::MutImmutable => try!(self.word_nbsp("const")),
500 try!(self.print_type(&*mt.ty));
502 hir::TyRptr(ref lifetime, ref mt) => {
503 try!(word(&mut self.s, "&"));
504 try!(self.print_opt_lifetime(lifetime));
505 try!(self.print_mt(mt));
507 hir::TyTup(ref elts) => {
509 try!(self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&**ty)));
511 try!(word(&mut self.s, ","));
515 hir::TyBareFn(ref f) => {
516 let generics = hir::Generics {
517 lifetimes: f.lifetimes.clone(),
518 ty_params: OwnedSlice::empty(),
519 where_clause: hir::WhereClause {
520 id: ast::DUMMY_NODE_ID,
521 predicates: Vec::new(),
524 try!(self.print_ty_fn(f.abi, f.unsafety, &*f.decl, None, &generics, None));
526 hir::TyPath(None, ref path) => {
527 try!(self.print_path(path, false, 0));
529 hir::TyPath(Some(ref qself), ref path) => {
530 try!(self.print_qpath(path, qself, false))
532 hir::TyObjectSum(ref ty, ref bounds) => {
533 try!(self.print_type(&**ty));
534 try!(self.print_bounds("+", &bounds[..]));
536 hir::TyPolyTraitRef(ref bounds) => {
537 try!(self.print_bounds("", &bounds[..]));
539 hir::TyFixedLengthVec(ref ty, ref v) => {
540 try!(word(&mut self.s, "["));
541 try!(self.print_type(&**ty));
542 try!(word(&mut self.s, "; "));
543 try!(self.print_expr(&**v));
544 try!(word(&mut self.s, "]"));
546 hir::TyTypeof(ref e) => {
547 try!(word(&mut self.s, "typeof("));
548 try!(self.print_expr(&**e));
549 try!(word(&mut self.s, ")"));
552 try!(word(&mut self.s, "_"));
558 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
559 try!(self.hardbreak_if_not_bol());
560 try!(self.maybe_print_comment(item.span.lo));
561 try!(self.print_outer_attributes(&item.attrs));
563 hir::ForeignItemFn(ref decl, ref generics) => {
565 try!(self.print_fn(decl,
566 hir::Unsafety::Normal,
567 hir::Constness::NotConst,
573 try!(self.end()); // end head-ibox
574 try!(word(&mut self.s, ";"));
575 self.end() // end the outer fn box
577 hir::ForeignItemStatic(ref t, m) => {
578 try!(self.head(&visibility_qualified(item.vis, "static")));
580 try!(self.word_space("mut"));
582 try!(self.print_name(item.name));
583 try!(self.word_space(":"));
584 try!(self.print_type(&**t));
585 try!(word(&mut self.s, ";"));
586 try!(self.end()); // end the head-ibox
587 self.end() // end the outer cbox
592 fn print_associated_const(&mut self,
595 default: Option<&hir::Expr>,
596 vis: hir::Visibility)
598 try!(word(&mut self.s, &visibility_qualified(vis, "")));
599 try!(self.word_space("const"));
600 try!(self.print_name(name));
601 try!(self.word_space(":"));
602 try!(self.print_type(ty));
603 if let Some(expr) = default {
604 try!(space(&mut self.s));
605 try!(self.word_space("="));
606 try!(self.print_expr(expr));
608 word(&mut self.s, ";")
611 fn print_associated_type(&mut self,
613 bounds: Option<&hir::TyParamBounds>,
614 ty: Option<&hir::Ty>)
616 try!(self.word_space("type"));
617 try!(self.print_name(name));
618 if let Some(bounds) = bounds {
619 try!(self.print_bounds(":", bounds));
621 if let Some(ty) = ty {
622 try!(space(&mut self.s));
623 try!(self.word_space("="));
624 try!(self.print_type(ty));
626 word(&mut self.s, ";")
629 pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
630 if let Some(krate) = self.krate {
631 // skip nested items if krate context was not provided
632 let item = &krate.items[&item_id.id];
633 self.print_item(item)
639 /// Pretty-print an item
640 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
641 try!(self.hardbreak_if_not_bol());
642 try!(self.maybe_print_comment(item.span.lo));
643 try!(self.print_outer_attributes(&item.attrs));
644 try!(self.ann.pre(self, NodeItem(item)));
646 hir::ItemExternCrate(ref optional_path) => {
647 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
648 if let Some(p) = *optional_path {
649 let val = p.as_str();
650 if val.contains("-") {
651 try!(self.print_string(&val, ast::CookedStr));
653 try!(self.print_name(p));
655 try!(space(&mut self.s));
656 try!(word(&mut self.s, "as"));
657 try!(space(&mut self.s));
659 try!(self.print_name(item.name));
660 try!(word(&mut self.s, ";"));
661 try!(self.end()); // end inner head-block
662 try!(self.end()); // end outer head-block
664 hir::ItemUse(ref vp) => {
665 try!(self.head(&visibility_qualified(item.vis, "use")));
666 try!(self.print_view_path(&**vp));
667 try!(word(&mut self.s, ";"));
668 try!(self.end()); // end inner head-block
669 try!(self.end()); // end outer head-block
671 hir::ItemStatic(ref ty, m, ref expr) => {
672 try!(self.head(&visibility_qualified(item.vis, "static")));
673 if m == hir::MutMutable {
674 try!(self.word_space("mut"));
676 try!(self.print_name(item.name));
677 try!(self.word_space(":"));
678 try!(self.print_type(&**ty));
679 try!(space(&mut self.s));
680 try!(self.end()); // end the head-ibox
682 try!(self.word_space("="));
683 try!(self.print_expr(&**expr));
684 try!(word(&mut self.s, ";"));
685 try!(self.end()); // end the outer cbox
687 hir::ItemConst(ref ty, ref expr) => {
688 try!(self.head(&visibility_qualified(item.vis, "const")));
689 try!(self.print_name(item.name));
690 try!(self.word_space(":"));
691 try!(self.print_type(&**ty));
692 try!(space(&mut self.s));
693 try!(self.end()); // end the head-ibox
695 try!(self.word_space("="));
696 try!(self.print_expr(&**expr));
697 try!(word(&mut self.s, ";"));
698 try!(self.end()); // end the outer cbox
700 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
702 try!(self.print_fn(decl,
710 try!(word(&mut self.s, " "));
711 try!(self.print_block_with_attrs(&**body, &item.attrs));
713 hir::ItemMod(ref _mod) => {
714 try!(self.head(&visibility_qualified(item.vis, "mod")));
715 try!(self.print_name(item.name));
718 try!(self.print_mod(_mod, &item.attrs));
719 try!(self.bclose(item.span));
721 hir::ItemForeignMod(ref nmod) => {
722 try!(self.head("extern"));
723 try!(self.word_nbsp(&nmod.abi.to_string()));
725 try!(self.print_foreign_mod(nmod, &item.attrs));
726 try!(self.bclose(item.span));
728 hir::ItemTy(ref ty, ref params) => {
729 try!(self.ibox(indent_unit));
731 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
732 try!(self.print_name(item.name));
733 try!(self.print_generics(params));
734 try!(self.end()); // end the inner ibox
736 try!(self.print_where_clause(¶ms.where_clause));
737 try!(space(&mut self.s));
738 try!(self.word_space("="));
739 try!(self.print_type(&**ty));
740 try!(word(&mut self.s, ";"));
741 try!(self.end()); // end the outer ibox
743 hir::ItemEnum(ref enum_definition, ref params) => {
744 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
746 hir::ItemStruct(ref struct_def, ref generics) => {
747 try!(self.head(&visibility_qualified(item.vis, "struct")));
748 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
751 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
753 try!(self.print_visibility(item.vis));
754 try!(self.print_unsafety(unsafety));
755 try!(self.word_nbsp("impl"));
756 try!(self.print_trait_ref(trait_ref));
757 try!(space(&mut self.s));
758 try!(self.word_space("for"));
759 try!(self.word_space(".."));
761 try!(self.bclose(item.span));
763 hir::ItemImpl(unsafety,
770 try!(self.print_visibility(item.vis));
771 try!(self.print_unsafety(unsafety));
772 try!(self.word_nbsp("impl"));
774 if generics.is_parameterized() {
775 try!(self.print_generics(generics));
776 try!(space(&mut self.s));
780 hir::ImplPolarity::Negative => {
781 try!(word(&mut self.s, "!"));
788 try!(self.print_trait_ref(t));
789 try!(space(&mut self.s));
790 try!(self.word_space("for"));
795 try!(self.print_type(&**ty));
796 try!(self.print_where_clause(&generics.where_clause));
798 try!(space(&mut self.s));
800 try!(self.print_inner_attributes(&item.attrs));
801 for impl_item in impl_items {
802 try!(self.print_impl_item(impl_item));
804 try!(self.bclose(item.span));
806 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
808 try!(self.print_visibility(item.vis));
809 try!(self.print_unsafety(unsafety));
810 try!(self.word_nbsp("trait"));
811 try!(self.print_name(item.name));
812 try!(self.print_generics(generics));
813 let mut real_bounds = Vec::with_capacity(bounds.len());
814 for b in bounds.iter() {
815 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
816 try!(space(&mut self.s));
817 try!(self.word_space("for ?"));
818 try!(self.print_trait_ref(&ptr.trait_ref));
820 real_bounds.push(b.clone());
823 try!(self.print_bounds(":", &real_bounds[..]));
824 try!(self.print_where_clause(&generics.where_clause));
825 try!(word(&mut self.s, " "));
827 for trait_item in trait_items {
828 try!(self.print_trait_item(trait_item));
830 try!(self.bclose(item.span));
833 self.ann.post(self, NodeItem(item))
836 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
837 self.print_path(&t.path, false, 0)
840 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
841 if !lifetimes.is_empty() {
842 try!(word(&mut self.s, "for<"));
843 let mut comma = false;
844 for lifetime_def in lifetimes {
846 try!(self.word_space(","))
848 try!(self.print_lifetime_def(lifetime_def));
851 try!(word(&mut self.s, ">"));
856 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
857 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
858 self.print_trait_ref(&t.trait_ref)
861 pub fn print_enum_def(&mut self,
862 enum_definition: &hir::EnumDef,
863 generics: &hir::Generics,
866 visibility: hir::Visibility)
868 try!(self.head(&visibility_qualified(visibility, "enum")));
869 try!(self.print_name(name));
870 try!(self.print_generics(generics));
871 try!(self.print_where_clause(&generics.where_clause));
872 try!(space(&mut self.s));
873 self.print_variants(&enum_definition.variants, span)
876 pub fn print_variants(&mut self,
877 variants: &[P<hir::Variant>],
882 try!(self.space_if_not_bol());
883 try!(self.maybe_print_comment(v.span.lo));
884 try!(self.print_outer_attributes(&v.node.attrs));
885 try!(self.ibox(indent_unit));
886 try!(self.print_variant(&**v));
887 try!(word(&mut self.s, ","));
889 try!(self.maybe_print_trailing_comment(v.span, None));
894 pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
896 hir::Public => self.word_nbsp("pub"),
897 hir::Inherited => Ok(()),
901 pub fn print_struct(&mut self,
902 struct_def: &hir::VariantData,
903 generics: &hir::Generics,
906 print_finalizer: bool)
908 try!(self.print_name(name));
909 try!(self.print_generics(generics));
910 if !struct_def.is_struct() {
911 if struct_def.is_tuple() {
913 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
914 match field.node.kind {
915 hir::NamedField(..) => panic!("unexpected named field"),
916 hir::UnnamedField(vis) => {
917 try!(s.print_visibility(vis));
918 try!(s.maybe_print_comment(field.span.lo));
919 s.print_type(&*field.node.ty)
925 try!(self.print_where_clause(&generics.where_clause));
927 try!(word(&mut self.s, ";"));
930 self.end() // close the outer-box
932 try!(self.print_where_clause(&generics.where_clause));
935 try!(self.hardbreak_if_not_bol());
937 for field in struct_def.fields() {
938 match field.node.kind {
939 hir::UnnamedField(..) => panic!("unexpected unnamed field"),
940 hir::NamedField(name, visibility) => {
941 try!(self.hardbreak_if_not_bol());
942 try!(self.maybe_print_comment(field.span.lo));
943 try!(self.print_outer_attributes(&field.node.attrs));
944 try!(self.print_visibility(visibility));
945 try!(self.print_name(name));
946 try!(self.word_nbsp(":"));
947 try!(self.print_type(&*field.node.ty));
948 try!(word(&mut self.s, ","));
957 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
959 let generics = ::util::empty_generics();
960 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
961 match v.node.disr_expr {
963 try!(space(&mut self.s));
964 try!(self.word_space("="));
965 self.print_expr(&**d)
971 pub fn print_method_sig(&mut self,
974 vis: hir::Visibility)
976 self.print_fn(&m.decl,
982 Some(&m.explicit_self.node),
986 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
987 try!(self.ann.pre(self, NodeSubItem(ti.id)));
988 try!(self.hardbreak_if_not_bol());
989 try!(self.maybe_print_comment(ti.span.lo));
990 try!(self.print_outer_attributes(&ti.attrs));
992 hir::ConstTraitItem(ref ty, ref default) => {
993 try!(self.print_associated_const(ti.name,
995 default.as_ref().map(|expr| &**expr),
998 hir::MethodTraitItem(ref sig, ref body) => {
1000 try!(self.head(""));
1002 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
1003 if let Some(ref body) = *body {
1005 try!(self.print_block_with_attrs(body, &ti.attrs));
1007 try!(word(&mut self.s, ";"));
1010 hir::TypeTraitItem(ref bounds, ref default) => {
1011 try!(self.print_associated_type(ti.name,
1013 default.as_ref().map(|ty| &**ty)));
1016 self.ann.post(self, NodeSubItem(ti.id))
1019 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1020 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1021 try!(self.hardbreak_if_not_bol());
1022 try!(self.maybe_print_comment(ii.span.lo));
1023 try!(self.print_outer_attributes(&ii.attrs));
1025 hir::ImplItemKind::Const(ref ty, ref expr) => {
1026 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1028 hir::ImplItemKind::Method(ref sig, ref body) => {
1029 try!(self.head(""));
1030 try!(self.print_method_sig(ii.name, sig, ii.vis));
1032 try!(self.print_block_with_attrs(body, &ii.attrs));
1034 hir::ImplItemKind::Type(ref ty) => {
1035 try!(self.print_associated_type(ii.name, None, Some(ty)));
1038 self.ann.post(self, NodeSubItem(ii.id))
1041 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1042 try!(self.maybe_print_comment(st.span.lo));
1044 hir::StmtDecl(ref decl, _) => {
1045 try!(self.print_decl(&**decl));
1047 hir::StmtExpr(ref expr, _) => {
1048 try!(self.space_if_not_bol());
1049 try!(self.print_expr(&**expr));
1051 hir::StmtSemi(ref expr, _) => {
1052 try!(self.space_if_not_bol());
1053 try!(self.print_expr(&**expr));
1054 try!(word(&mut self.s, ";"));
1057 if stmt_ends_with_semi(&st.node) {
1058 try!(word(&mut self.s, ";"));
1060 self.maybe_print_trailing_comment(st.span, None)
1063 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1064 self.print_block_with_attrs(blk, &[])
1067 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1068 self.print_block_unclosed_indent(blk, indent_unit)
1071 pub fn print_block_unclosed_indent(&mut self,
1075 self.print_block_maybe_unclosed(blk, indented, &[], false)
1078 pub fn print_block_with_attrs(&mut self,
1080 attrs: &[ast::Attribute])
1082 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1085 pub fn print_block_maybe_unclosed(&mut self,
1088 attrs: &[ast::Attribute],
1092 hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1093 hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1094 hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1095 hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1096 hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1097 hir::DefaultBlock => (),
1099 try!(self.maybe_print_comment(blk.span.lo));
1100 try!(self.ann.pre(self, NodeBlock(blk)));
1103 try!(self.print_inner_attributes(attrs));
1105 for st in &blk.stmts {
1106 try!(self.print_stmt(&**st));
1110 try!(self.space_if_not_bol());
1111 try!(self.print_expr(&**expr));
1112 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1116 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1117 self.ann.post(self, NodeBlock(blk))
1120 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1124 // "another else-if"
1125 hir::ExprIf(ref i, ref then, ref e) => {
1126 try!(self.cbox(indent_unit - 1));
1128 try!(word(&mut self.s, " else if "));
1129 try!(self.print_expr(&**i));
1130 try!(space(&mut self.s));
1131 try!(self.print_block(&**then));
1132 self.print_else(e.as_ref().map(|e| &**e))
1135 hir::ExprBlock(ref b) => {
1136 try!(self.cbox(indent_unit - 1));
1138 try!(word(&mut self.s, " else "));
1139 self.print_block(&**b)
1141 // BLEAH, constraints would be great here
1143 panic!("print_if saw if with weird alternative");
1151 pub fn print_if(&mut self,
1154 elseopt: Option<&hir::Expr>)
1156 try!(self.head("if"));
1157 try!(self.print_expr(test));
1158 try!(space(&mut self.s));
1159 try!(self.print_block(blk));
1160 self.print_else(elseopt)
1163 pub fn print_if_let(&mut self,
1167 elseopt: Option<&hir::Expr>)
1169 try!(self.head("if let"));
1170 try!(self.print_pat(pat));
1171 try!(space(&mut self.s));
1172 try!(self.word_space("="));
1173 try!(self.print_expr(expr));
1174 try!(space(&mut self.s));
1175 try!(self.print_block(blk));
1176 self.print_else(elseopt)
1180 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1182 try!(self.commasep_exprs(Inconsistent, args));
1186 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1187 let needs_par = needs_parentheses(expr);
1191 try!(self.print_expr(expr));
1193 try!(self.pclose());
1198 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1199 try!(self.ibox(indent_unit));
1200 try!(word(&mut self.s, "["));
1201 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1202 try!(word(&mut self.s, "]"));
1206 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1207 try!(self.ibox(indent_unit));
1208 try!(word(&mut self.s, "["));
1209 try!(self.print_expr(element));
1210 try!(self.word_space(";"));
1211 try!(self.print_expr(count));
1212 try!(word(&mut self.s, "]"));
1216 fn print_expr_struct(&mut self,
1218 fields: &[hir::Field],
1219 wth: &Option<P<hir::Expr>>)
1221 try!(self.print_path(path, true, 0));
1222 try!(word(&mut self.s, "{"));
1223 try!(self.commasep_cmnt(Consistent,
1226 try!(s.ibox(indent_unit));
1227 try!(s.print_name(field.name.node));
1228 try!(s.word_space(":"));
1229 try!(s.print_expr(&*field.expr));
1235 try!(self.ibox(indent_unit));
1236 if !fields.is_empty() {
1237 try!(word(&mut self.s, ","));
1238 try!(space(&mut self.s));
1240 try!(word(&mut self.s, ".."));
1241 try!(self.print_expr(&**expr));
1244 _ => if !fields.is_empty() {
1245 try!(word(&mut self.s, ","))
1248 try!(word(&mut self.s, "}"));
1252 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1254 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1255 if exprs.len() == 1 {
1256 try!(word(&mut self.s, ","));
1261 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1262 try!(self.print_expr_maybe_paren(func));
1263 self.print_call_post(args)
1266 fn print_expr_method_call(&mut self,
1267 name: Spanned<ast::Name>,
1269 args: &[P<hir::Expr>])
1271 let base_args = &args[1..];
1272 try!(self.print_expr(&*args[0]));
1273 try!(word(&mut self.s, "."));
1274 try!(self.print_name(name.node));
1275 if !tys.is_empty() {
1276 try!(word(&mut self.s, "::<"));
1277 try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty)));
1278 try!(word(&mut self.s, ">"));
1280 self.print_call_post(base_args)
1283 fn print_expr_binary(&mut self,
1288 try!(self.print_expr(lhs));
1289 try!(space(&mut self.s));
1290 try!(self.word_space(::util::binop_to_string(op.node)));
1291 self.print_expr(rhs)
1294 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1295 try!(word(&mut self.s, ::util::unop_to_string(op)));
1296 self.print_expr_maybe_paren(expr)
1299 fn print_expr_addr_of(&mut self,
1300 mutability: hir::Mutability,
1303 try!(word(&mut self.s, "&"));
1304 try!(self.print_mutability(mutability));
1305 self.print_expr_maybe_paren(expr)
1308 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1309 try!(self.maybe_print_comment(expr.span.lo));
1310 try!(self.ibox(indent_unit));
1311 try!(self.ann.pre(self, NodeExpr(expr)));
1313 hir::ExprBox(ref expr) => {
1314 try!(self.word_space("box"));
1315 try!(self.print_expr(expr));
1317 hir::ExprVec(ref exprs) => {
1318 try!(self.print_expr_vec(&exprs[..]));
1320 hir::ExprRepeat(ref element, ref count) => {
1321 try!(self.print_expr_repeat(&**element, &**count));
1323 hir::ExprStruct(ref path, ref fields, ref wth) => {
1324 try!(self.print_expr_struct(path, &fields[..], wth));
1326 hir::ExprTup(ref exprs) => {
1327 try!(self.print_expr_tup(&exprs[..]));
1329 hir::ExprCall(ref func, ref args) => {
1330 try!(self.print_expr_call(&**func, &args[..]));
1332 hir::ExprMethodCall(name, ref tys, ref args) => {
1333 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1335 hir::ExprBinary(op, ref lhs, ref rhs) => {
1336 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1338 hir::ExprUnary(op, ref expr) => {
1339 try!(self.print_expr_unary(op, &**expr));
1341 hir::ExprAddrOf(m, ref expr) => {
1342 try!(self.print_expr_addr_of(m, &**expr));
1344 hir::ExprLit(ref lit) => {
1345 try!(self.print_literal(&**lit));
1347 hir::ExprCast(ref expr, ref ty) => {
1348 try!(self.print_expr(&**expr));
1349 try!(space(&mut self.s));
1350 try!(self.word_space("as"));
1351 try!(self.print_type(&**ty));
1353 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1354 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1356 hir::ExprWhile(ref test, ref blk, opt_ident) => {
1357 if let Some(ident) = opt_ident {
1358 try!(self.print_name(ident.name));
1359 try!(self.word_space(":"));
1361 try!(self.head("while"));
1362 try!(self.print_expr(&**test));
1363 try!(space(&mut self.s));
1364 try!(self.print_block(&**blk));
1366 hir::ExprLoop(ref blk, opt_ident) => {
1367 if let Some(ident) = opt_ident {
1368 try!(self.print_name(ident.name));
1369 try!(self.word_space(":"));
1371 try!(self.head("loop"));
1372 try!(space(&mut self.s));
1373 try!(self.print_block(&**blk));
1375 hir::ExprMatch(ref expr, ref arms, _) => {
1376 try!(self.cbox(indent_unit));
1378 try!(self.word_nbsp("match"));
1379 try!(self.print_expr(&**expr));
1380 try!(space(&mut self.s));
1383 try!(self.print_arm(arm));
1385 try!(self.bclose_(expr.span, indent_unit));
1387 hir::ExprClosure(capture_clause, ref decl, ref body) => {
1388 try!(self.print_capture_clause(capture_clause));
1390 try!(self.print_fn_block_args(&**decl));
1391 try!(space(&mut self.s));
1393 let default_return = match decl.output {
1394 hir::DefaultReturn(..) => true,
1398 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1399 try!(self.print_block_unclosed(&**body));
1401 // we extract the block, so as not to create another set of boxes
1402 match body.expr.as_ref().unwrap().node {
1403 hir::ExprBlock(ref blk) => {
1404 try!(self.print_block_unclosed(&**blk));
1407 // this is a bare expression
1408 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1409 try!(self.end()); // need to close a box
1413 // a box will be closed by print_expr, but we didn't want an overall
1414 // wrapper so we closed the corresponding opening. so create an
1415 // empty box to satisfy the close.
1418 hir::ExprBlock(ref blk) => {
1419 // containing cbox, will be closed by print-block at }
1420 try!(self.cbox(indent_unit));
1421 // head-box, will be closed by print-block after {
1423 try!(self.print_block(&**blk));
1425 hir::ExprAssign(ref lhs, ref rhs) => {
1426 try!(self.print_expr(&**lhs));
1427 try!(space(&mut self.s));
1428 try!(self.word_space("="));
1429 try!(self.print_expr(&**rhs));
1431 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1432 try!(self.print_expr(&**lhs));
1433 try!(space(&mut self.s));
1434 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1435 try!(self.word_space("="));
1436 try!(self.print_expr(&**rhs));
1438 hir::ExprField(ref expr, name) => {
1439 try!(self.print_expr(&**expr));
1440 try!(word(&mut self.s, "."));
1441 try!(self.print_name(name.node));
1443 hir::ExprTupField(ref expr, id) => {
1444 try!(self.print_expr(&**expr));
1445 try!(word(&mut self.s, "."));
1446 try!(self.print_usize(id.node));
1448 hir::ExprIndex(ref expr, ref index) => {
1449 try!(self.print_expr(&**expr));
1450 try!(word(&mut self.s, "["));
1451 try!(self.print_expr(&**index));
1452 try!(word(&mut self.s, "]"));
1454 hir::ExprRange(ref start, ref end) => {
1455 if let &Some(ref e) = start {
1456 try!(self.print_expr(&**e));
1458 try!(word(&mut self.s, ".."));
1459 if let &Some(ref e) = end {
1460 try!(self.print_expr(&**e));
1463 hir::ExprPath(None, ref path) => {
1464 try!(self.print_path(path, true, 0))
1466 hir::ExprPath(Some(ref qself), ref path) => {
1467 try!(self.print_qpath(path, qself, true))
1469 hir::ExprBreak(opt_ident) => {
1470 try!(word(&mut self.s, "break"));
1471 try!(space(&mut self.s));
1472 if let Some(ident) = opt_ident {
1473 try!(self.print_name(ident.node.name));
1474 try!(space(&mut self.s));
1477 hir::ExprAgain(opt_ident) => {
1478 try!(word(&mut self.s, "continue"));
1479 try!(space(&mut self.s));
1480 if let Some(ident) = opt_ident {
1481 try!(self.print_name(ident.node.name));
1482 try!(space(&mut self.s))
1485 hir::ExprRet(ref result) => {
1486 try!(word(&mut self.s, "return"));
1489 try!(word(&mut self.s, " "));
1490 try!(self.print_expr(&**expr));
1495 hir::ExprInlineAsm(ref a) => {
1496 try!(word(&mut self.s, "asm!"));
1498 try!(self.print_string(&a.asm, a.asm_str_style));
1499 try!(self.word_space(":"));
1501 try!(self.commasep(Inconsistent, &a.outputs, |s, &(ref co, ref o, is_rw)| {
1502 match co.slice_shift_char() {
1503 Some(('=', operand)) if is_rw => {
1504 try!(s.print_string(&format!("+{}", operand), ast::CookedStr))
1506 _ => try!(s.print_string(&co, ast::CookedStr)),
1509 try!(s.print_expr(&**o));
1513 try!(space(&mut self.s));
1514 try!(self.word_space(":"));
1516 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1517 try!(s.print_string(&co, ast::CookedStr));
1519 try!(s.print_expr(&**o));
1523 try!(space(&mut self.s));
1524 try!(self.word_space(":"));
1526 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1527 try!(s.print_string(&co, ast::CookedStr));
1531 let mut options = vec![];
1533 options.push("volatile");
1536 options.push("alignstack");
1538 if a.dialect == ast::AsmDialect::Intel {
1539 options.push("intel");
1542 if !options.is_empty() {
1543 try!(space(&mut self.s));
1544 try!(self.word_space(":"));
1545 try!(self.commasep(Inconsistent, &*options, |s, &co| {
1546 try!(s.print_string(co, ast::CookedStr));
1551 try!(self.pclose());
1554 try!(self.ann.post(self, NodeExpr(expr)));
1558 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1559 try!(self.print_pat(&*loc.pat));
1560 if let Some(ref ty) = loc.ty {
1561 try!(self.word_space(":"));
1562 try!(self.print_type(&**ty));
1567 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1568 try!(self.maybe_print_comment(decl.span.lo));
1570 hir::DeclLocal(ref loc) => {
1571 try!(self.space_if_not_bol());
1572 try!(self.ibox(indent_unit));
1573 try!(self.word_nbsp("let"));
1575 try!(self.ibox(indent_unit));
1576 try!(self.print_local_decl(&**loc));
1578 if let Some(ref init) = loc.init {
1580 try!(self.word_space("="));
1581 try!(self.print_expr(&**init));
1585 hir::DeclItem(ref item) => {
1586 self.print_item_id(item)
1591 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1592 word(&mut self.s, &i.to_string())
1595 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1596 try!(word(&mut self.s, &name.as_str()));
1597 self.ann.post(self, NodeName(&name))
1600 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1601 try!(self.print_local_decl(loc));
1602 try!(space(&mut self.s));
1603 try!(self.word_space("in"));
1604 self.print_expr(coll)
1607 fn print_path(&mut self,
1609 colons_before_params: bool,
1612 try!(self.maybe_print_comment(path.span.lo));
1614 let mut first = !path.global;
1615 for segment in &path.segments[..path.segments.len() - depth] {
1619 try!(word(&mut self.s, "::"))
1622 try!(self.print_name(segment.identifier.name));
1624 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1630 fn print_qpath(&mut self,
1633 colons_before_params: bool)
1635 try!(word(&mut self.s, "<"));
1636 try!(self.print_type(&qself.ty));
1637 if qself.position > 0 {
1638 try!(space(&mut self.s));
1639 try!(self.word_space("as"));
1640 let depth = path.segments.len() - qself.position;
1641 try!(self.print_path(&path, false, depth));
1643 try!(word(&mut self.s, ">"));
1644 try!(word(&mut self.s, "::"));
1645 let item_segment = path.segments.last().unwrap();
1646 try!(self.print_name(item_segment.identifier.name));
1647 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1650 fn print_path_parameters(&mut self,
1651 parameters: &hir::PathParameters,
1652 colons_before_params: bool)
1654 if parameters.is_empty() {
1658 if colons_before_params {
1659 try!(word(&mut self.s, "::"))
1663 hir::AngleBracketedParameters(ref data) => {
1664 try!(word(&mut self.s, "<"));
1666 let mut comma = false;
1667 for lifetime in &data.lifetimes {
1669 try!(self.word_space(","))
1671 try!(self.print_lifetime(lifetime));
1675 if !data.types.is_empty() {
1677 try!(self.word_space(","))
1679 try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&**ty)));
1683 for binding in data.bindings.iter() {
1685 try!(self.word_space(","))
1687 try!(self.print_name(binding.name));
1688 try!(space(&mut self.s));
1689 try!(self.word_space("="));
1690 try!(self.print_type(&*binding.ty));
1694 try!(word(&mut self.s, ">"))
1697 hir::ParenthesizedParameters(ref data) => {
1698 try!(word(&mut self.s, "("));
1699 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&**ty)));
1700 try!(word(&mut self.s, ")"));
1705 try!(self.space_if_not_bol());
1706 try!(self.word_space("->"));
1707 try!(self.print_type(&**ty));
1716 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1717 try!(self.maybe_print_comment(pat.span.lo));
1718 try!(self.ann.pre(self, NodePat(pat)));
1719 // Pat isn't normalized, but the beauty of it
1720 // is that it doesn't matter
1722 hir::PatWild => try!(word(&mut self.s, "_")),
1723 hir::PatIdent(binding_mode, ref path1, ref sub) => {
1724 match binding_mode {
1725 hir::BindByRef(mutbl) => {
1726 try!(self.word_nbsp("ref"));
1727 try!(self.print_mutability(mutbl));
1729 hir::BindByValue(hir::MutImmutable) => {}
1730 hir::BindByValue(hir::MutMutable) => {
1731 try!(self.word_nbsp("mut"));
1734 try!(self.print_name(path1.node.name));
1737 try!(word(&mut self.s, "@"));
1738 try!(self.print_pat(&**p));
1743 hir::PatEnum(ref path, ref args_) => {
1744 try!(self.print_path(path, true, 0));
1746 None => try!(word(&mut self.s, "(..)")),
1748 if !args.is_empty() {
1750 try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&**p)));
1751 try!(self.pclose());
1756 hir::PatQPath(ref qself, ref path) => {
1757 try!(self.print_qpath(path, qself, false));
1759 hir::PatStruct(ref path, ref fields, etc) => {
1760 try!(self.print_path(path, true, 0));
1762 try!(self.word_space("{"));
1763 try!(self.commasep_cmnt(Consistent,
1766 try!(s.cbox(indent_unit));
1767 if !f.node.is_shorthand {
1768 try!(s.print_name(f.node.name));
1769 try!(s.word_nbsp(":"));
1771 try!(s.print_pat(&*f.node.pat));
1774 |f| f.node.pat.span));
1776 if !fields.is_empty() {
1777 try!(self.word_space(","));
1779 try!(word(&mut self.s, ".."));
1781 try!(space(&mut self.s));
1782 try!(word(&mut self.s, "}"));
1784 hir::PatTup(ref elts) => {
1786 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&**p)));
1787 if elts.len() == 1 {
1788 try!(word(&mut self.s, ","));
1790 try!(self.pclose());
1792 hir::PatBox(ref inner) => {
1793 try!(word(&mut self.s, "box "));
1794 try!(self.print_pat(&**inner));
1796 hir::PatRegion(ref inner, mutbl) => {
1797 try!(word(&mut self.s, "&"));
1798 if mutbl == hir::MutMutable {
1799 try!(word(&mut self.s, "mut "));
1801 try!(self.print_pat(&**inner));
1803 hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1804 hir::PatRange(ref begin, ref end) => {
1805 try!(self.print_expr(&**begin));
1806 try!(space(&mut self.s));
1807 try!(word(&mut self.s, "..."));
1808 try!(self.print_expr(&**end));
1810 hir::PatVec(ref before, ref slice, ref after) => {
1811 try!(word(&mut self.s, "["));
1812 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&**p)));
1813 if let Some(ref p) = *slice {
1814 if !before.is_empty() {
1815 try!(self.word_space(","));
1817 if p.node != hir::PatWild {
1818 try!(self.print_pat(&**p));
1820 try!(word(&mut self.s, ".."));
1821 if !after.is_empty() {
1822 try!(self.word_space(","));
1825 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&**p)));
1826 try!(word(&mut self.s, "]"));
1829 self.ann.post(self, NodePat(pat))
1832 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1833 // I have no idea why this check is necessary, but here it
1835 if arm.attrs.is_empty() {
1836 try!(space(&mut self.s));
1838 try!(self.cbox(indent_unit));
1840 try!(self.print_outer_attributes(&arm.attrs));
1841 let mut first = true;
1842 for p in &arm.pats {
1846 try!(space(&mut self.s));
1847 try!(self.word_space("|"));
1849 try!(self.print_pat(&**p));
1851 try!(space(&mut self.s));
1852 if let Some(ref e) = arm.guard {
1853 try!(self.word_space("if"));
1854 try!(self.print_expr(&**e));
1855 try!(space(&mut self.s));
1857 try!(self.word_space("=>"));
1859 match arm.body.node {
1860 hir::ExprBlock(ref blk) => {
1861 // the block will close the pattern's ibox
1862 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1864 // If it is a user-provided unsafe block, print a comma after it
1865 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1866 try!(word(&mut self.s, ","));
1870 try!(self.end()); // close the ibox for the pattern
1871 try!(self.print_expr(&*arm.body));
1872 try!(word(&mut self.s, ","));
1875 self.end() // close enclosing cbox
1878 // Returns whether it printed anything
1879 fn print_explicit_self(&mut self,
1880 explicit_self: &hir::ExplicitSelf_,
1881 mutbl: hir::Mutability)
1882 -> io::Result<bool> {
1883 try!(self.print_mutability(mutbl));
1884 match *explicit_self {
1885 hir::SelfStatic => {
1888 hir::SelfValue(_) => {
1889 try!(word(&mut self.s, "self"));
1891 hir::SelfRegion(ref lt, m, _) => {
1892 try!(word(&mut self.s, "&"));
1893 try!(self.print_opt_lifetime(lt));
1894 try!(self.print_mutability(m));
1895 try!(word(&mut self.s, "self"));
1897 hir::SelfExplicit(ref typ, _) => {
1898 try!(word(&mut self.s, "self"));
1899 try!(self.word_space(":"));
1900 try!(self.print_type(&**typ));
1906 pub fn print_fn(&mut self,
1908 unsafety: hir::Unsafety,
1909 constness: hir::Constness,
1911 name: Option<ast::Name>,
1912 generics: &hir::Generics,
1913 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1914 vis: hir::Visibility)
1916 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1918 if let Some(name) = name {
1920 try!(self.print_name(name));
1922 try!(self.print_generics(generics));
1923 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1924 self.print_where_clause(&generics.where_clause)
1927 pub fn print_fn_args(&mut self,
1929 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1931 // It is unfortunate to duplicate the commasep logic, but we want the
1932 // self type and the args all in the same box.
1933 try!(self.rbox(0, Inconsistent));
1934 let mut first = true;
1935 if let Some(explicit_self) = opt_explicit_self {
1936 let m = match explicit_self {
1937 &hir::SelfStatic => hir::MutImmutable,
1938 _ => match decl.inputs[0].pat.node {
1939 hir::PatIdent(hir::BindByValue(m), _, _) => m,
1940 _ => hir::MutImmutable,
1943 first = !try!(self.print_explicit_self(explicit_self, m));
1946 // HACK(eddyb) ignore the separately printed self argument.
1947 let args = if first {
1957 try!(self.word_space(","));
1959 try!(self.print_arg(arg));
1965 pub fn print_fn_args_and_ret(&mut self,
1967 opt_explicit_self: Option<&hir::ExplicitSelf_>)
1970 try!(self.print_fn_args(decl, opt_explicit_self));
1972 try!(word(&mut self.s, ", ..."));
1974 try!(self.pclose());
1976 self.print_fn_output(decl)
1979 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1980 try!(word(&mut self.s, "|"));
1981 try!(self.print_fn_args(decl, None));
1982 try!(word(&mut self.s, "|"));
1984 if let hir::DefaultReturn(..) = decl.output {
1988 try!(self.space_if_not_bol());
1989 try!(self.word_space("->"));
1991 hir::Return(ref ty) => {
1992 try!(self.print_type(&**ty));
1993 self.maybe_print_comment(ty.span.lo)
1995 hir::DefaultReturn(..) => unreachable!(),
1996 hir::NoReturn(span) => {
1997 try!(self.word_nbsp("!"));
1998 self.maybe_print_comment(span.lo)
2003 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2004 match capture_clause {
2005 hir::CaptureByValue => self.word_space("move"),
2006 hir::CaptureByRef => Ok(()),
2010 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
2011 if !bounds.is_empty() {
2012 try!(word(&mut self.s, prefix));
2013 let mut first = true;
2014 for bound in bounds {
2019 try!(self.word_space("+"));
2023 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2024 self.print_poly_trait_ref(tref)
2026 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2027 try!(word(&mut self.s, "?"));
2028 self.print_poly_trait_ref(tref)
2030 RegionTyParamBound(ref lt) => {
2031 self.print_lifetime(lt)
2041 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2042 self.print_name(lifetime.name)
2045 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2046 try!(self.print_lifetime(&lifetime.lifetime));
2048 for v in &lifetime.bounds {
2049 try!(word(&mut self.s, sep));
2050 try!(self.print_lifetime(v));
2056 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2057 let total = generics.lifetimes.len() + generics.ty_params.len();
2062 try!(word(&mut self.s, "<"));
2064 let mut ints = Vec::new();
2069 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2070 if idx < generics.lifetimes.len() {
2071 let lifetime = &generics.lifetimes[idx];
2072 s.print_lifetime_def(lifetime)
2074 let idx = idx - generics.lifetimes.len();
2075 let param = &generics.ty_params[idx];
2076 s.print_ty_param(param)
2080 try!(word(&mut self.s, ">"));
2084 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2085 try!(self.print_name(param.name));
2086 try!(self.print_bounds(":", ¶m.bounds));
2087 match param.default {
2088 Some(ref default) => {
2089 try!(space(&mut self.s));
2090 try!(self.word_space("="));
2091 self.print_type(&**default)
2097 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2098 if where_clause.predicates.is_empty() {
2102 try!(space(&mut self.s));
2103 try!(self.word_space("where"));
2105 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2107 try!(self.word_space(","));
2111 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2115 try!(self.print_formal_lifetime_list(bound_lifetimes));
2116 try!(self.print_type(&**bounded_ty));
2117 try!(self.print_bounds(":", bounds));
2119 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2122 try!(self.print_lifetime(lifetime));
2123 try!(word(&mut self.s, ":"));
2125 for (i, bound) in bounds.iter().enumerate() {
2126 try!(self.print_lifetime(bound));
2129 try!(word(&mut self.s, ":"));
2133 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2134 try!(self.print_path(path, false, 0));
2135 try!(space(&mut self.s));
2136 try!(self.word_space("="));
2137 try!(self.print_type(&**ty));
2145 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2147 hir::ViewPathSimple(name, ref path) => {
2148 try!(self.print_path(path, false, 0));
2150 if path.segments.last().unwrap().identifier.name != name {
2151 try!(space(&mut self.s));
2152 try!(self.word_space("as"));
2153 try!(self.print_name(name));
2159 hir::ViewPathGlob(ref path) => {
2160 try!(self.print_path(path, false, 0));
2161 word(&mut self.s, "::*")
2164 hir::ViewPathList(ref path, ref segments) => {
2165 if path.segments.is_empty() {
2166 try!(word(&mut self.s, "{"));
2168 try!(self.print_path(path, false, 0));
2169 try!(word(&mut self.s, "::{"));
2171 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2173 hir::PathListIdent { name, .. } => {
2176 hir::PathListMod { .. } => {
2177 word(&mut s.s, "self")
2181 word(&mut self.s, "}")
2186 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2188 hir::MutMutable => self.word_nbsp("mut"),
2189 hir::MutImmutable => Ok(()),
2193 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2194 try!(self.print_mutability(mt.mutbl));
2195 self.print_type(&*mt.ty)
2198 pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2199 try!(self.ibox(indent_unit));
2200 match input.ty.node {
2201 hir::TyInfer => try!(self.print_pat(&*input.pat)),
2203 match input.pat.node {
2204 hir::PatIdent(_, ref path1, _) if
2206 parse::token::special_idents::invalid.name => {
2210 try!(self.print_pat(&*input.pat));
2211 try!(word(&mut self.s, ":"));
2212 try!(space(&mut self.s));
2215 try!(self.print_type(&*input.ty));
2221 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2222 if let hir::DefaultReturn(..) = decl.output {
2226 try!(self.space_if_not_bol());
2227 try!(self.ibox(indent_unit));
2228 try!(self.word_space("->"));
2230 hir::NoReturn(_) => try!(self.word_nbsp("!")),
2231 hir::DefaultReturn(..) => unreachable!(),
2232 hir::Return(ref ty) => try!(self.print_type(&**ty)),
2237 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2242 pub fn print_ty_fn(&mut self,
2244 unsafety: hir::Unsafety,
2246 name: Option<ast::Name>,
2247 generics: &hir::Generics,
2248 opt_explicit_self: Option<&hir::ExplicitSelf_>)
2250 try!(self.ibox(indent_unit));
2251 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2252 try!(word(&mut self.s, "for"));
2253 try!(self.print_generics(generics));
2255 let generics = hir::Generics {
2256 lifetimes: Vec::new(),
2257 ty_params: OwnedSlice::empty(),
2258 where_clause: hir::WhereClause {
2259 id: ast::DUMMY_NODE_ID,
2260 predicates: Vec::new(),
2263 try!(self.print_fn(decl,
2265 hir::Constness::NotConst,
2274 pub fn maybe_print_trailing_comment(&mut self,
2275 span: codemap::Span,
2276 next_pos: Option<BytePos>)
2278 let cm = match self.cm {
2282 match self.next_comment() {
2284 if (*cmnt).style != comments::Trailing {
2287 let span_line = cm.lookup_char_pos(span.hi);
2288 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2289 let mut next = (*cmnt).pos + BytePos(1);
2292 Some(p) => next = p,
2294 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2295 span_line.line == comment_line.line {
2296 try!(self.print_comment(cmnt));
2297 self.cur_cmnt_and_lit.cur_cmnt += 1;
2305 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2306 // If there aren't any remaining comments, then we need to manually
2307 // make sure there is a line break at the end.
2308 if self.next_comment().is_none() {
2309 try!(hardbreak(&mut self.s));
2312 match self.next_comment() {
2314 try!(self.print_comment(cmnt));
2315 self.cur_cmnt_and_lit.cur_cmnt += 1;
2323 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2324 opt_abi: Option<abi::Abi>)
2327 Some(abi::Rust) => Ok(()),
2329 try!(self.word_nbsp("extern"));
2330 self.word_nbsp(&abi.to_string())
2336 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<abi::Abi>) -> io::Result<()> {
2339 try!(self.word_nbsp("extern"));
2340 self.word_nbsp(&abi.to_string())
2346 pub fn print_fn_header_info(&mut self,
2347 unsafety: hir::Unsafety,
2348 constness: hir::Constness,
2350 vis: hir::Visibility)
2352 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2353 try!(self.print_unsafety(unsafety));
2356 hir::Constness::NotConst => {}
2357 hir::Constness::Const => try!(self.word_nbsp("const")),
2360 if abi != abi::Rust {
2361 try!(self.word_nbsp("extern"));
2362 try!(self.word_nbsp(&abi.to_string()));
2365 word(&mut self.s, "fn")
2368 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2370 hir::Unsafety::Normal => Ok(()),
2371 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2376 // Dup'ed from parse::classify, but adapted for the HIR.
2377 /// Does this expression require a semicolon to be treated
2378 /// as a statement? The negation of this: 'can this expression
2379 /// be used as a statement without a semicolon' -- is used
2380 /// as an early-bail-out in the parser so that, for instance,
2381 /// if true {...} else {...}
2383 /// isn't parsed as (if true {...} else {...} | x) | 5
2384 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2387 hir::ExprMatch(..) |
2389 hir::ExprWhile(..) |
2390 hir::ExprLoop(..) => false,
2395 /// this statement requires a semicolon after it.
2396 /// note that in one case (stmt_semi), we've already
2397 /// seen the semicolon, and thus don't need another.
2398 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2400 hir::StmtDecl(ref d, _) => {
2402 hir::DeclLocal(_) => true,
2403 hir::DeclItem(_) => false,
2406 hir::StmtExpr(ref e, _) => {
2407 expr_requires_semi_to_be_stmt(&**e)
2409 hir::StmtSemi(..) => {