1 // Copyright 2012-2014 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 ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
18 use owned_slice::OwnedSlice;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{self, CodeMap, BytePos};
22 use parse::token::{self, BinOpToken, Token, InternedString};
23 use parse::lexer::comments;
25 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, eof};
27 use print::pp::Breaks::{Consistent, Inconsistent};
31 use std::{ascii, mem};
32 use std::io::{self, Write, Read};
35 pub enum AnnNode<'a> {
36 NodeIdent(&'a ast::Ident),
37 NodeName(&'a ast::Name),
38 NodeBlock(&'a ast::Block),
39 NodeItem(&'a ast::Item),
40 NodeExpr(&'a ast::Expr),
41 NodePat(&'a ast::Pat),
45 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
46 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
52 impl PpAnn for NoAnn {}
55 pub struct CurrentCommentAndLiteral {
60 pub struct State<'a> {
61 pub s: pp::Printer<'a>,
62 cm: Option<&'a CodeMap>,
63 comments: Option<Vec<comments::Comment> >,
64 literals: Option<Vec<comments::Literal> >,
65 cur_cmnt_and_lit: CurrentCommentAndLiteral,
66 boxes: Vec<pp::Breaks>,
68 encode_idents_with_hygiene: bool,
71 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
72 static NO_ANN: NoAnn = NoAnn;
73 rust_printer_annotated(writer, &NO_ANN)
76 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
77 ann: &'a PpAnn) -> State<'a> {
79 s: pp::mk_printer(writer, default_columns),
83 cur_cmnt_and_lit: CurrentCommentAndLiteral {
89 encode_idents_with_hygiene: false,
93 #[allow(non_upper_case_globals)]
94 pub const indent_unit: usize = 4;
96 #[allow(non_upper_case_globals)]
97 pub const default_columns: usize = 78;
99 /// Requires you to pass an input filename and reader so that
100 /// it can scan the input text for comments and literals to
102 pub fn print_crate<'a>(cm: &'a CodeMap,
103 span_diagnostic: &diagnostic::SpanHandler,
109 is_expanded: bool) -> io::Result<()> {
110 let mut s = State::new_from_input(cm,
117 if is_expanded && std_inject::use_std(krate) {
118 // We need to print `#![no_std]` (and its feature gate) so that
119 // compiling pretty-printed source won't inject libstd again.
120 // However we don't want these attributes in the AST because
121 // of the feature gate, so we fake them up here.
123 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
125 // #![feature(no_std)]
126 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
127 attr::mk_list_item(InternedString::new("feature"),
128 vec![no_std_meta.clone()]));
129 try!(s.print_attribute(&fake_attr));
132 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
133 try!(s.print_attribute(&fake_attr));
136 try!(s.print_mod(&krate.module, &krate.attrs));
137 try!(s.print_remaining_comments());
142 pub fn new_from_input(cm: &'a CodeMap,
143 span_diagnostic: &diagnostic::SpanHandler,
148 is_expanded: bool) -> State<'a> {
149 let (cmnts, lits) = comments::gather_comments_and_literals(
159 // If the code is post expansion, don't use the table of
160 // literals, since it doesn't correspond with the literals
161 // in the AST anymore.
162 if is_expanded { None } else { Some(lits) })
165 pub fn new(cm: &'a CodeMap,
168 comments: Option<Vec<comments::Comment>>,
169 literals: Option<Vec<comments::Literal>>) -> State<'a> {
171 s: pp::mk_printer(out, default_columns),
175 cur_cmnt_and_lit: CurrentCommentAndLiteral {
181 encode_idents_with_hygiene: false,
186 pub fn to_string<F>(f: F) -> String where
187 F: FnOnce(&mut State) -> io::Result<()>,
189 use std::raw::TraitObject;
190 let mut s = rust_printer(box Vec::new());
192 eof(&mut s.s).unwrap();
194 // FIXME(pcwalton): A nasty function to extract the string from an `Write`
195 // that we "know" to be a `Vec<u8>` that works around the lack of checked
197 let obj: &TraitObject = mem::transmute(&s.s.out);
198 mem::transmute::<*mut (), &Vec<u8>>(obj.data)
200 String::from_utf8(wr.clone()).unwrap()
203 pub fn binop_to_string(op: BinOpToken) -> &'static str {
209 token::Percent => "%",
218 pub fn token_to_string(tok: &Token) -> String {
220 token::Eq => "=".to_string(),
221 token::Lt => "<".to_string(),
222 token::Le => "<=".to_string(),
223 token::EqEq => "==".to_string(),
224 token::Ne => "!=".to_string(),
225 token::Ge => ">=".to_string(),
226 token::Gt => ">".to_string(),
227 token::Not => "!".to_string(),
228 token::Tilde => "~".to_string(),
229 token::OrOr => "||".to_string(),
230 token::AndAnd => "&&".to_string(),
231 token::BinOp(op) => binop_to_string(op).to_string(),
232 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
234 /* Structural symbols */
235 token::At => "@".to_string(),
236 token::Dot => ".".to_string(),
237 token::DotDot => "..".to_string(),
238 token::DotDotDot => "...".to_string(),
239 token::Comma => ",".to_string(),
240 token::Semi => ";".to_string(),
241 token::Colon => ":".to_string(),
242 token::ModSep => "::".to_string(),
243 token::RArrow => "->".to_string(),
244 token::LArrow => "<-".to_string(),
245 token::FatArrow => "=>".to_string(),
246 token::OpenDelim(token::Paren) => "(".to_string(),
247 token::CloseDelim(token::Paren) => ")".to_string(),
248 token::OpenDelim(token::Bracket) => "[".to_string(),
249 token::CloseDelim(token::Bracket) => "]".to_string(),
250 token::OpenDelim(token::Brace) => "{".to_string(),
251 token::CloseDelim(token::Brace) => "}".to_string(),
252 token::Pound => "#".to_string(),
253 token::Dollar => "$".to_string(),
254 token::Question => "?".to_string(),
257 token::Literal(lit, suf) => {
258 let mut out = match lit {
259 token::Byte(b) => format!("b'{}'", b.as_str()),
260 token::Char(c) => format!("'{}'", c.as_str()),
261 token::Float(c) => c.as_str().to_string(),
262 token::Integer(c) => c.as_str().to_string(),
263 token::Str_(s) => format!("\"{}\"", s.as_str()),
264 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
265 delim=repeat("#", n),
267 token::Binary(v) => format!("b\"{}\"", v.as_str()),
268 token::BinaryRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
269 delim=repeat("#", n),
273 if let Some(s) = suf {
274 out.push_str(s.as_str())
280 /* Name components */
281 token::Ident(s, _) => token::get_ident(s).to_string(),
282 token::Lifetime(s) => format!("{}", token::get_ident(s)),
283 token::Underscore => "_".to_string(),
286 token::DocComment(s) => s.as_str().to_string(),
287 token::SubstNt(s, _) => format!("${}", s),
288 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
289 token::Eof => "<eof>".to_string(),
290 token::Whitespace => " ".to_string(),
291 token::Comment => "/* */".to_string(),
292 token::Shebang(s) => format!("/* shebang: {}*/", s.as_str()),
294 token::SpecialVarNt(var) => format!("${}", var.as_str()),
296 token::Interpolated(ref nt) => match *nt {
297 token::NtExpr(ref e) => expr_to_string(&**e),
298 token::NtMeta(ref e) => meta_item_to_string(&**e),
299 token::NtTy(ref e) => ty_to_string(&**e),
300 token::NtPath(ref e) => path_to_string(&**e),
301 token::NtItem(..) => "an interpolated item".to_string(),
302 token::NtBlock(..) => "an interpolated block".to_string(),
303 token::NtStmt(..) => "an interpolated statement".to_string(),
304 token::NtPat(..) => "an interpolated pattern".to_string(),
305 token::NtIdent(..) => "an interpolated identifier".to_string(),
306 token::NtTT(..) => "an interpolated tt".to_string(),
311 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
312 // after we revise the syntax::ext::quote::ToToken impls to go directly
313 // to token-trees instead of thing -> string -> token-trees.
315 macro_rules! thing_to_string_impls {
316 ($to_string:ident) => {
318 pub fn ty_to_string(ty: &ast::Ty) -> String {
319 $to_string(|s| s.print_type(ty))
322 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
323 $to_string(|s| s.print_bounds("", bounds))
326 pub fn pat_to_string(pat: &ast::Pat) -> String {
327 $to_string(|s| s.print_pat(pat))
330 pub fn arm_to_string(arm: &ast::Arm) -> String {
331 $to_string(|s| s.print_arm(arm))
334 pub fn expr_to_string(e: &ast::Expr) -> String {
335 $to_string(|s| s.print_expr(e))
338 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
339 $to_string(|s| s.print_lifetime(e))
342 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
343 $to_string(|s| s.print_tt(tt))
346 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
347 $to_string(|s| s.print_tts(tts))
350 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
351 $to_string(|s| s.print_stmt(stmt))
354 pub fn item_to_string(i: &ast::Item) -> String {
355 $to_string(|s| s.print_item(i))
358 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
359 $to_string(|s| s.print_impl_item(i))
362 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
363 $to_string(|s| s.print_trait_item(i))
366 pub fn generics_to_string(generics: &ast::Generics) -> String {
367 $to_string(|s| s.print_generics(generics))
370 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
371 $to_string(|s| s.print_where_clause(i))
374 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
375 $to_string(|s| s.print_fn_block_args(p))
378 pub fn path_to_string(p: &ast::Path) -> String {
379 $to_string(|s| s.print_path(p, false, 0))
382 pub fn ident_to_string(id: &ast::Ident) -> String {
383 $to_string(|s| s.print_ident(*id))
386 pub fn fun_to_string(decl: &ast::FnDecl, unsafety: ast::Unsafety, name: ast::Ident,
387 opt_explicit_self: Option<&ast::ExplicitSelf_>,
388 generics: &ast::Generics) -> String {
391 try!(s.print_fn(decl, unsafety, abi::Rust, Some(name),
392 generics, opt_explicit_self, ast::Inherited));
393 try!(s.end()); // Close the head box
394 s.end() // Close the outer box
398 pub fn block_to_string(blk: &ast::Block) -> String {
400 // containing cbox, will be closed by print-block at }
401 try!(s.cbox(indent_unit));
402 // head-ibox, will be closed by print-block after {
408 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
409 $to_string(|s| s.print_meta_item(mi))
412 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
413 $to_string(|s| s.print_attribute(attr))
416 pub fn lit_to_string(l: &ast::Lit) -> String {
417 $to_string(|s| s.print_literal(l))
420 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
421 $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
424 pub fn variant_to_string(var: &ast::Variant) -> String {
425 $to_string(|s| s.print_variant(var))
428 pub fn arg_to_string(arg: &ast::Arg) -> String {
429 $to_string(|s| s.print_arg(arg))
432 pub fn mac_to_string(arg: &ast::Mac) -> String {
433 $to_string(|s| s.print_mac(arg, ::parse::token::Paren))
438 thing_to_string_impls! { to_string }
440 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
441 // after we revise the syntax::ext::quote::ToToken impls to go directly
442 // to token-trees instea of thing -> string -> token-trees.
444 pub mod with_hygiene {
448 use super::indent_unit;
450 // This function is the trick that all the rest of the routines
452 pub fn to_string_hyg<F>(f: F) -> String where
453 F: FnOnce(&mut super::State) -> io::Result<()>,
455 super::to_string(move |s| {
456 s.encode_idents_with_hygiene = true;
461 thing_to_string_impls! { to_string_hyg }
464 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
466 ast::Public => format!("pub {}", s),
467 ast::Inherited => s.to_string()
471 fn needs_parentheses(expr: &ast::Expr) -> bool {
473 ast::ExprAssign(..) | ast::ExprBinary(..) |
474 ast::ExprClosure(..) |
475 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
481 pub fn ibox(&mut self, u: usize) -> io::Result<()> {
482 self.boxes.push(pp::Breaks::Inconsistent);
483 pp::ibox(&mut self.s, u)
486 pub fn end(&mut self) -> io::Result<()> {
487 self.boxes.pop().unwrap();
491 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
492 self.boxes.push(pp::Breaks::Consistent);
493 pp::cbox(&mut self.s, u)
497 pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
499 pp::rbox(&mut self.s, u, b)
502 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
504 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
505 try!(word(&mut self.s, w));
509 pub fn word_space(&mut self, w: &str) -> io::Result<()> {
510 try!(word(&mut self.s, w));
514 pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
516 pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
518 pub fn head(&mut self, w: &str) -> io::Result<()> {
519 // outer-box is consistent
520 try!(self.cbox(indent_unit));
521 // head-box is inconsistent
522 try!(self.ibox(w.len() + 1));
523 // keyword that starts the head
525 try!(self.word_nbsp(w));
530 pub fn bopen(&mut self) -> io::Result<()> {
531 try!(word(&mut self.s, "{"));
532 self.end() // close the head-box
535 pub fn bclose_(&mut self, span: codemap::Span,
536 indented: usize) -> io::Result<()> {
537 self.bclose_maybe_open(span, indented, true)
539 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
540 indented: usize, close_box: bool) -> io::Result<()> {
541 try!(self.maybe_print_comment(span.hi));
542 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
543 try!(word(&mut self.s, "}"));
545 try!(self.end()); // close the outer-box
549 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
550 self.bclose_(span, indent_unit)
553 pub fn is_begin(&mut self) -> bool {
554 match self.s.last_token() {
555 pp::Token::Begin(_) => true,
560 pub fn is_end(&mut self) -> bool {
561 match self.s.last_token() {
562 pp::Token::End => true,
567 // is this the beginning of a line?
568 pub fn is_bol(&mut self) -> bool {
569 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
572 pub fn in_cbox(&self) -> bool {
573 match self.boxes.last() {
574 Some(&last_box) => last_box == pp::Breaks::Consistent,
579 pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
581 try!(hardbreak(&mut self.s))
585 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
586 if !self.is_bol() { try!(space(&mut self.s)); }
589 pub fn break_offset_if_not_bol(&mut self, n: usize,
590 off: isize) -> io::Result<()> {
592 break_offset(&mut self.s, n, off)
594 if off != 0 && self.s.last_token().is_hardbreak_tok() {
595 // We do something pretty sketchy here: tuck the nonzero
596 // offset-adjustment we were going to deposit along with the
597 // break into the previous hardbreak.
598 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
604 // Synthesizes a comment that was not textually present in the original source
606 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
607 try!(word(&mut self.s, "/*"));
608 try!(space(&mut self.s));
609 try!(word(&mut self.s, &text[..]));
610 try!(space(&mut self.s));
611 word(&mut self.s, "*/")
614 pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
615 F: FnMut(&mut State, &T) -> io::Result<()>,
617 try!(self.rbox(0, b));
618 let mut first = true;
620 if first { first = false; } else { try!(self.word_space(",")); }
627 pub fn commasep_cmnt<T, F, G>(&mut self,
631 mut get_span: G) -> io::Result<()> where
632 F: FnMut(&mut State, &T) -> io::Result<()>,
633 G: FnMut(&T) -> codemap::Span,
635 try!(self.rbox(0, b));
636 let len = elts.len();
639 try!(self.maybe_print_comment(get_span(elt).hi));
643 try!(word(&mut self.s, ","));
644 try!(self.maybe_print_trailing_comment(get_span(elt),
645 Some(get_span(&elts[i]).hi)));
646 try!(self.space_if_not_bol());
652 pub fn commasep_exprs(&mut self, b: Breaks,
653 exprs: &[P<ast::Expr>]) -> io::Result<()> {
654 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
657 pub fn print_mod(&mut self, _mod: &ast::Mod,
658 attrs: &[ast::Attribute]) -> io::Result<()> {
659 try!(self.print_inner_attributes(attrs));
660 for item in &_mod.items {
661 try!(self.print_item(&**item));
666 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
667 attrs: &[ast::Attribute]) -> io::Result<()> {
668 try!(self.print_inner_attributes(attrs));
669 for item in &nmod.items {
670 try!(self.print_foreign_item(&**item));
675 pub fn print_opt_lifetime(&mut self,
676 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
677 if let Some(l) = *lifetime {
678 try!(self.print_lifetime(&l));
684 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
685 try!(self.maybe_print_comment(ty.span.lo));
688 ast::TyVec(ref ty) => {
689 try!(word(&mut self.s, "["));
690 try!(self.print_type(&**ty));
691 try!(word(&mut self.s, "]"));
693 ast::TyPtr(ref mt) => {
694 try!(word(&mut self.s, "*"));
696 ast::MutMutable => try!(self.word_nbsp("mut")),
697 ast::MutImmutable => try!(self.word_nbsp("const")),
699 try!(self.print_type(&*mt.ty));
701 ast::TyRptr(ref lifetime, ref mt) => {
702 try!(word(&mut self.s, "&"));
703 try!(self.print_opt_lifetime(lifetime));
704 try!(self.print_mt(mt));
706 ast::TyTup(ref elts) => {
708 try!(self.commasep(Inconsistent, &elts[..],
709 |s, ty| s.print_type(&**ty)));
711 try!(word(&mut self.s, ","));
715 ast::TyParen(ref typ) => {
717 try!(self.print_type(&**typ));
720 ast::TyBareFn(ref f) => {
721 let generics = ast::Generics {
722 lifetimes: f.lifetimes.clone(),
723 ty_params: OwnedSlice::empty(),
724 where_clause: ast::WhereClause {
725 id: ast::DUMMY_NODE_ID,
726 predicates: Vec::new(),
729 try!(self.print_ty_fn(f.abi,
736 ast::TyPath(None, ref path) => {
737 try!(self.print_path(path, false, 0));
739 ast::TyPath(Some(ref qself), ref path) => {
740 try!(self.print_qpath(path, qself, false))
742 ast::TyObjectSum(ref ty, ref bounds) => {
743 try!(self.print_type(&**ty));
744 try!(self.print_bounds("+", &bounds[..]));
746 ast::TyPolyTraitRef(ref bounds) => {
747 try!(self.print_bounds("", &bounds[..]));
749 ast::TyFixedLengthVec(ref ty, ref v) => {
750 try!(word(&mut self.s, "["));
751 try!(self.print_type(&**ty));
752 try!(word(&mut self.s, "; "));
753 try!(self.print_expr(&**v));
754 try!(word(&mut self.s, "]"));
756 ast::TyTypeof(ref e) => {
757 try!(word(&mut self.s, "typeof("));
758 try!(self.print_expr(&**e));
759 try!(word(&mut self.s, ")"));
762 try!(word(&mut self.s, "_"));
768 pub fn print_foreign_item(&mut self,
769 item: &ast::ForeignItem) -> io::Result<()> {
770 try!(self.hardbreak_if_not_bol());
771 try!(self.maybe_print_comment(item.span.lo));
772 try!(self.print_outer_attributes(&item.attrs));
774 ast::ForeignItemFn(ref decl, ref generics) => {
776 try!(self.print_fn(&**decl, ast::Unsafety::Normal,
777 abi::Rust, Some(item.ident),
778 generics, None, item.vis));
779 try!(self.end()); // end head-ibox
780 try!(word(&mut self.s, ";"));
781 self.end() // end the outer fn box
783 ast::ForeignItemStatic(ref t, m) => {
784 try!(self.head(&visibility_qualified(item.vis,
787 try!(self.word_space("mut"));
789 try!(self.print_ident(item.ident));
790 try!(self.word_space(":"));
791 try!(self.print_type(&**t));
792 try!(word(&mut self.s, ";"));
793 try!(self.end()); // end the head-ibox
794 self.end() // end the outer cbox
799 fn print_associated_type(&mut self,
801 bounds: Option<&ast::TyParamBounds>,
802 ty: Option<&ast::Ty>)
804 try!(self.word_space("type"));
805 try!(self.print_ident(ident));
806 if let Some(bounds) = bounds {
807 try!(self.print_bounds(":", bounds));
809 if let Some(ty) = ty {
810 try!(space(&mut self.s));
811 try!(self.word_space("="));
812 try!(self.print_type(ty));
814 word(&mut self.s, ";")
818 /// Pretty-print an item
819 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
820 try!(self.hardbreak_if_not_bol());
821 try!(self.maybe_print_comment(item.span.lo));
822 try!(self.print_outer_attributes(&item.attrs));
823 try!(self.ann.pre(self, NodeItem(item)));
825 ast::ItemExternCrate(ref optional_path) => {
826 try!(self.head(&visibility_qualified(item.vis,
828 if let Some(p) = *optional_path {
829 let val = token::get_name(p);
830 if val.contains("-") {
831 try!(self.print_string(&val, ast::CookedStr));
833 try!(self.print_name(p));
835 try!(space(&mut self.s));
836 try!(word(&mut self.s, "as"));
837 try!(space(&mut self.s));
839 try!(self.print_ident(item.ident));
840 try!(word(&mut self.s, ";"));
841 try!(self.end()); // end inner head-block
842 try!(self.end()); // end outer head-block
844 ast::ItemUse(ref vp) => {
845 try!(self.head(&visibility_qualified(item.vis,
847 try!(self.print_view_path(&**vp));
848 try!(word(&mut self.s, ";"));
849 try!(self.end()); // end inner head-block
850 try!(self.end()); // end outer head-block
852 ast::ItemStatic(ref ty, m, ref expr) => {
853 try!(self.head(&visibility_qualified(item.vis,
855 if m == ast::MutMutable {
856 try!(self.word_space("mut"));
858 try!(self.print_ident(item.ident));
859 try!(self.word_space(":"));
860 try!(self.print_type(&**ty));
861 try!(space(&mut self.s));
862 try!(self.end()); // end the head-ibox
864 try!(self.word_space("="));
865 try!(self.print_expr(&**expr));
866 try!(word(&mut self.s, ";"));
867 try!(self.end()); // end the outer cbox
869 ast::ItemConst(ref ty, ref expr) => {
870 try!(self.head(&visibility_qualified(item.vis,
872 try!(self.print_ident(item.ident));
873 try!(self.word_space(":"));
874 try!(self.print_type(&**ty));
875 try!(space(&mut self.s));
876 try!(self.end()); // end the head-ibox
878 try!(self.word_space("="));
879 try!(self.print_expr(&**expr));
880 try!(word(&mut self.s, ";"));
881 try!(self.end()); // end the outer cbox
883 ast::ItemFn(ref decl, unsafety, abi, ref typarams, ref body) => {
894 try!(word(&mut self.s, " "));
895 try!(self.print_block_with_attrs(&**body, &item.attrs));
897 ast::ItemMod(ref _mod) => {
898 try!(self.head(&visibility_qualified(item.vis,
900 try!(self.print_ident(item.ident));
903 try!(self.print_mod(_mod, &item.attrs));
904 try!(self.bclose(item.span));
906 ast::ItemForeignMod(ref nmod) => {
907 try!(self.head("extern"));
908 try!(self.word_nbsp(&nmod.abi.to_string()));
910 try!(self.print_foreign_mod(nmod, &item.attrs));
911 try!(self.bclose(item.span));
913 ast::ItemTy(ref ty, ref params) => {
914 try!(self.ibox(indent_unit));
916 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
917 try!(self.print_ident(item.ident));
918 try!(self.print_generics(params));
919 try!(self.end()); // end the inner ibox
921 try!(space(&mut self.s));
922 try!(self.word_space("="));
923 try!(self.print_type(&**ty));
924 try!(self.print_where_clause(¶ms.where_clause));
925 try!(word(&mut self.s, ";"));
926 try!(self.end()); // end the outer ibox
928 ast::ItemEnum(ref enum_definition, ref params) => {
929 try!(self.print_enum_def(
937 ast::ItemStruct(ref struct_def, ref generics) => {
938 try!(self.head(&visibility_qualified(item.vis,"struct")));
939 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
942 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
944 try!(self.print_visibility(item.vis));
945 try!(self.print_unsafety(unsafety));
946 try!(self.word_nbsp("impl"));
947 try!(self.print_trait_ref(trait_ref));
948 try!(space(&mut self.s));
949 try!(self.word_space("for"));
950 try!(self.word_space(".."));
952 try!(self.bclose(item.span));
954 ast::ItemImpl(unsafety,
961 try!(self.print_visibility(item.vis));
962 try!(self.print_unsafety(unsafety));
963 try!(self.word_nbsp("impl"));
965 if generics.is_parameterized() {
966 try!(self.print_generics(generics));
967 try!(space(&mut self.s));
971 ast::ImplPolarity::Negative => {
972 try!(word(&mut self.s, "!"));
979 try!(self.print_trait_ref(t));
980 try!(space(&mut self.s));
981 try!(self.word_space("for"));
986 try!(self.print_type(&**ty));
987 try!(self.print_where_clause(&generics.where_clause));
989 try!(space(&mut self.s));
991 try!(self.print_inner_attributes(&item.attrs));
992 for impl_item in impl_items {
993 try!(self.print_impl_item(impl_item));
995 try!(self.bclose(item.span));
997 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
999 try!(self.print_visibility(item.vis));
1000 try!(self.print_unsafety(unsafety));
1001 try!(self.word_nbsp("trait"));
1002 try!(self.print_ident(item.ident));
1003 try!(self.print_generics(generics));
1004 let mut real_bounds = Vec::with_capacity(bounds.len());
1005 for b in bounds.iter() {
1006 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1007 try!(space(&mut self.s));
1008 try!(self.word_space("for ?"));
1009 try!(self.print_trait_ref(&ptr.trait_ref));
1011 real_bounds.push(b.clone());
1014 try!(self.print_bounds(":", &real_bounds[..]));
1015 try!(self.print_where_clause(&generics.where_clause));
1016 try!(word(&mut self.s, " "));
1018 for trait_item in trait_items {
1019 try!(self.print_trait_item(trait_item));
1021 try!(self.bclose(item.span));
1023 // I think it's reasonable to hide the context here:
1024 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1026 try!(self.print_visibility(item.vis));
1027 try!(self.print_path(pth, false, 0));
1028 try!(word(&mut self.s, "! "));
1029 try!(self.print_ident(item.ident));
1030 try!(self.cbox(indent_unit));
1032 try!(self.print_tts(&tts[..]));
1033 try!(self.pclose());
1034 try!(word(&mut self.s, ";"));
1038 self.ann.post(self, NodeItem(item))
1041 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1042 self.print_path(&t.path, false, 0)
1045 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1046 if !lifetimes.is_empty() {
1047 try!(word(&mut self.s, "for<"));
1048 let mut comma = false;
1049 for lifetime_def in lifetimes {
1051 try!(self.word_space(","))
1053 try!(self.print_lifetime_def(lifetime_def));
1056 try!(word(&mut self.s, ">"));
1061 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1062 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1063 self.print_trait_ref(&t.trait_ref)
1066 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1067 generics: &ast::Generics, ident: ast::Ident,
1068 span: codemap::Span,
1069 visibility: ast::Visibility) -> io::Result<()> {
1070 try!(self.head(&visibility_qualified(visibility, "enum")));
1071 try!(self.print_ident(ident));
1072 try!(self.print_generics(generics));
1073 try!(self.print_where_clause(&generics.where_clause));
1074 try!(space(&mut self.s));
1075 self.print_variants(&enum_definition.variants, span)
1078 pub fn print_variants(&mut self,
1079 variants: &[P<ast::Variant>],
1080 span: codemap::Span) -> io::Result<()> {
1083 try!(self.space_if_not_bol());
1084 try!(self.maybe_print_comment(v.span.lo));
1085 try!(self.print_outer_attributes(&v.node.attrs));
1086 try!(self.ibox(indent_unit));
1087 try!(self.print_variant(&**v));
1088 try!(word(&mut self.s, ","));
1090 try!(self.maybe_print_trailing_comment(v.span, None));
1095 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1097 ast::Public => self.word_nbsp("pub"),
1098 ast::Inherited => Ok(())
1102 pub fn print_struct(&mut self,
1103 struct_def: &ast::StructDef,
1104 generics: &ast::Generics,
1106 span: codemap::Span) -> io::Result<()> {
1107 try!(self.print_ident(ident));
1108 try!(self.print_generics(generics));
1109 if ast_util::struct_def_is_tuple_like(struct_def) {
1110 if !struct_def.fields.is_empty() {
1113 Inconsistent, &struct_def.fields,
1115 match field.node.kind {
1116 ast::NamedField(..) => panic!("unexpected named field"),
1117 ast::UnnamedField(vis) => {
1118 try!(s.print_visibility(vis));
1119 try!(s.maybe_print_comment(field.span.lo));
1120 s.print_type(&*field.node.ty)
1125 try!(self.pclose());
1127 try!(self.print_where_clause(&generics.where_clause));
1128 try!(word(&mut self.s, ";"));
1130 self.end() // close the outer-box
1132 try!(self.print_where_clause(&generics.where_clause));
1135 try!(self.hardbreak_if_not_bol());
1137 for field in &struct_def.fields {
1138 match field.node.kind {
1139 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1140 ast::NamedField(ident, visibility) => {
1141 try!(self.hardbreak_if_not_bol());
1142 try!(self.maybe_print_comment(field.span.lo));
1143 try!(self.print_outer_attributes(&field.node.attrs));
1144 try!(self.print_visibility(visibility));
1145 try!(self.print_ident(ident));
1146 try!(self.word_nbsp(":"));
1147 try!(self.print_type(&*field.node.ty));
1148 try!(word(&mut self.s, ","));
1157 /// This doesn't deserve to be called "pretty" printing, but it should be
1158 /// meaning-preserving. A quick hack that might help would be to look at the
1159 /// spans embedded in the TTs to decide where to put spaces and newlines.
1160 /// But it'd be better to parse these according to the grammar of the
1161 /// appropriate macro, transcribe back into the grammar we just parsed from,
1162 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1163 /// expression arguments as expressions). It can be done! I think.
1164 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1166 ast::TtToken(_, ref tk) => {
1167 try!(word(&mut self.s, &token_to_string(tk)));
1169 parse::token::DocComment(..) => {
1170 hardbreak(&mut self.s)
1175 ast::TtDelimited(_, ref delimed) => {
1176 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1177 try!(space(&mut self.s));
1178 try!(self.print_tts(&delimed.tts));
1179 try!(space(&mut self.s));
1180 word(&mut self.s, &token_to_string(&delimed.close_token()))
1182 ast::TtSequence(_, ref seq) => {
1183 try!(word(&mut self.s, "$("));
1184 for tt_elt in &seq.tts {
1185 try!(self.print_tt(tt_elt));
1187 try!(word(&mut self.s, ")"));
1188 match seq.separator {
1190 try!(word(&mut self.s, &token_to_string(tk)));
1195 ast::ZeroOrMore => word(&mut self.s, "*"),
1196 ast::OneOrMore => word(&mut self.s, "+"),
1202 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1204 let mut suppress_space = false;
1205 for (i, tt) in tts.iter().enumerate() {
1206 if i != 0 && !suppress_space {
1207 try!(space(&mut self.s));
1209 try!(self.print_tt(tt));
1210 // There should be no space between the module name and the following `::` in paths,
1211 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1212 suppress_space = match tt {
1213 &ast::TtToken(_, token::Ident(_, token::ModName)) |
1214 &ast::TtToken(_, token::MatchNt(_, _, _, token::ModName)) |
1215 &ast::TtToken(_, token::SubstNt(_, token::ModName)) => true,
1222 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1223 try!(self.print_visibility(v.node.vis));
1225 ast::TupleVariantKind(ref args) => {
1226 try!(self.print_ident(v.node.name));
1227 if !args.is_empty() {
1229 try!(self.commasep(Consistent,
1231 |s, arg| s.print_type(&*arg.ty)));
1232 try!(self.pclose());
1235 ast::StructVariantKind(ref struct_def) => {
1236 try!(self.head(""));
1237 let generics = ast_util::empty_generics();
1238 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1241 match v.node.disr_expr {
1243 try!(space(&mut self.s));
1244 try!(self.word_space("="));
1245 self.print_expr(&**d)
1251 pub fn print_method_sig(&mut self,
1254 vis: ast::Visibility)
1256 self.print_fn(&m.decl,
1261 Some(&m.explicit_self.node),
1265 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1267 try!(self.hardbreak_if_not_bol());
1268 try!(self.maybe_print_comment(ti.span.lo));
1269 try!(self.print_outer_attributes(&ti.attrs));
1271 ast::MethodTraitItem(ref sig, ref body) => {
1273 try!(self.head(""));
1275 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1276 if let Some(ref body) = *body {
1278 self.print_block_with_attrs(body, &ti.attrs)
1280 word(&mut self.s, ";")
1283 ast::TypeTraitItem(ref bounds, ref default) => {
1284 self.print_associated_type(ti.ident, Some(bounds),
1285 default.as_ref().map(|ty| &**ty))
1290 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1291 try!(self.hardbreak_if_not_bol());
1292 try!(self.maybe_print_comment(ii.span.lo));
1293 try!(self.print_outer_attributes(&ii.attrs));
1295 ast::MethodImplItem(ref sig, ref body) => {
1296 try!(self.head(""));
1297 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1299 self.print_block_with_attrs(body, &ii.attrs)
1301 ast::TypeImplItem(ref ty) => {
1302 self.print_associated_type(ii.ident, None, Some(ty))
1304 ast::MacImplItem(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1306 // code copied from ItemMac:
1307 try!(self.print_path(pth, false, 0));
1308 try!(word(&mut self.s, "! "));
1309 try!(self.cbox(indent_unit));
1311 try!(self.print_tts(&tts[..]));
1312 try!(self.pclose());
1313 try!(word(&mut self.s, ";"));
1319 pub fn print_outer_attributes(&mut self,
1320 attrs: &[ast::Attribute]) -> io::Result<()> {
1323 match attr.node.style {
1325 try!(self.print_attribute(attr));
1328 _ => {/* fallthrough */ }
1332 try!(self.hardbreak_if_not_bol());
1337 pub fn print_inner_attributes(&mut self,
1338 attrs: &[ast::Attribute]) -> io::Result<()> {
1341 match attr.node.style {
1343 try!(self.print_attribute(attr));
1346 _ => {/* fallthrough */ }
1350 try!(self.hardbreak_if_not_bol());
1355 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
1356 try!(self.hardbreak_if_not_bol());
1357 try!(self.maybe_print_comment(attr.span.lo));
1358 if attr.node.is_sugared_doc {
1359 word(&mut self.s, &attr.value_str().unwrap())
1361 match attr.node.style {
1362 ast::AttrInner => try!(word(&mut self.s, "#![")),
1363 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1365 try!(self.print_meta_item(&*attr.meta()));
1366 word(&mut self.s, "]")
1371 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1372 try!(self.maybe_print_comment(st.span.lo));
1374 ast::StmtDecl(ref decl, _) => {
1375 try!(self.print_decl(&**decl));
1377 ast::StmtExpr(ref expr, _) => {
1378 try!(self.space_if_not_bol());
1379 try!(self.print_expr(&**expr));
1381 ast::StmtSemi(ref expr, _) => {
1382 try!(self.space_if_not_bol());
1383 try!(self.print_expr(&**expr));
1384 try!(word(&mut self.s, ";"));
1386 ast::StmtMac(ref mac, style) => {
1387 try!(self.space_if_not_bol());
1388 let delim = match style {
1389 ast::MacStmtWithBraces => token::Brace,
1392 try!(self.print_mac(&**mac, delim));
1394 ast::MacStmtWithBraces => {}
1395 _ => try!(word(&mut self.s, ";")),
1399 if parse::classify::stmt_ends_with_semi(&st.node) {
1400 try!(word(&mut self.s, ";"));
1402 self.maybe_print_trailing_comment(st.span, None)
1405 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1406 self.print_block_with_attrs(blk, &[])
1409 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1410 self.print_block_unclosed_indent(blk, indent_unit)
1413 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1414 indented: usize) -> io::Result<()> {
1415 self.print_block_maybe_unclosed(blk, indented, &[], false)
1418 pub fn print_block_with_attrs(&mut self,
1420 attrs: &[ast::Attribute]) -> io::Result<()> {
1421 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1424 pub fn print_block_maybe_unclosed(&mut self,
1427 attrs: &[ast::Attribute],
1428 close_box: bool) -> io::Result<()> {
1430 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1431 ast::DefaultBlock => ()
1433 try!(self.maybe_print_comment(blk.span.lo));
1434 try!(self.ann.pre(self, NodeBlock(blk)));
1437 try!(self.print_inner_attributes(attrs));
1439 for st in &blk.stmts {
1440 try!(self.print_stmt(&**st));
1444 try!(self.space_if_not_bol());
1445 try!(self.print_expr(&**expr));
1446 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1450 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1451 self.ann.post(self, NodeBlock(blk))
1454 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1458 // "another else-if"
1459 ast::ExprIf(ref i, ref then, ref e) => {
1460 try!(self.cbox(indent_unit - 1));
1462 try!(word(&mut self.s, " else if "));
1463 try!(self.print_expr(&**i));
1464 try!(space(&mut self.s));
1465 try!(self.print_block(&**then));
1466 self.print_else(e.as_ref().map(|e| &**e))
1468 // "another else-if-let"
1469 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1470 try!(self.cbox(indent_unit - 1));
1472 try!(word(&mut self.s, " else if let "));
1473 try!(self.print_pat(&**pat));
1474 try!(space(&mut self.s));
1475 try!(self.word_space("="));
1476 try!(self.print_expr(&**expr));
1477 try!(space(&mut self.s));
1478 try!(self.print_block(&**then));
1479 self.print_else(e.as_ref().map(|e| &**e))
1482 ast::ExprBlock(ref b) => {
1483 try!(self.cbox(indent_unit - 1));
1485 try!(word(&mut self.s, " else "));
1486 self.print_block(&**b)
1488 // BLEAH, constraints would be great here
1490 panic!("print_if saw if with weird alternative");
1498 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1499 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1500 try!(self.head("if"));
1501 try!(self.print_expr(test));
1502 try!(space(&mut self.s));
1503 try!(self.print_block(blk));
1504 self.print_else(elseopt)
1507 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1508 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1509 try!(self.head("if let"));
1510 try!(self.print_pat(pat));
1511 try!(space(&mut self.s));
1512 try!(self.word_space("="));
1513 try!(self.print_expr(expr));
1514 try!(space(&mut self.s));
1515 try!(self.print_block(blk));
1516 self.print_else(elseopt)
1519 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1522 // I think it's reasonable to hide the ctxt here:
1523 ast::MacInvocTT(ref pth, ref tts, _) => {
1524 try!(self.print_path(pth, false, 0));
1525 try!(word(&mut self.s, "!"));
1527 token::Paren => try!(self.popen()),
1528 token::Bracket => try!(word(&mut self.s, "[")),
1529 token::Brace => try!(self.bopen()),
1531 try!(self.print_tts(tts));
1533 token::Paren => self.pclose(),
1534 token::Bracket => word(&mut self.s, "]"),
1535 token::Brace => self.bclose(m.span),
1542 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1544 try!(self.commasep_exprs(Inconsistent, args));
1548 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1549 let needs_par = needs_parentheses(expr);
1553 try!(self.print_expr(expr));
1555 try!(self.pclose());
1560 fn print_expr_box(&mut self,
1561 place: &Option<P<ast::Expr>>,
1562 expr: &ast::Expr) -> io::Result<()> {
1563 try!(word(&mut self.s, "box"));
1564 try!(word(&mut self.s, "("));
1565 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1566 try!(self.word_space(")"));
1567 self.print_expr(expr)
1570 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1571 try!(self.ibox(indent_unit));
1572 try!(word(&mut self.s, "["));
1573 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1574 try!(word(&mut self.s, "]"));
1578 fn print_expr_repeat(&mut self,
1579 element: &ast::Expr,
1580 count: &ast::Expr) -> io::Result<()> {
1581 try!(self.ibox(indent_unit));
1582 try!(word(&mut self.s, "["));
1583 try!(self.print_expr(element));
1584 try!(self.word_space(";"));
1585 try!(self.print_expr(count));
1586 try!(word(&mut self.s, "]"));
1590 fn print_expr_struct(&mut self,
1592 fields: &[ast::Field],
1593 wth: &Option<P<ast::Expr>>) -> io::Result<()> {
1594 try!(self.print_path(path, true, 0));
1595 if !(fields.is_empty() && wth.is_none()) {
1596 try!(word(&mut self.s, "{"));
1597 try!(self.commasep_cmnt(
1601 try!(s.ibox(indent_unit));
1602 try!(s.print_ident(field.ident.node));
1603 try!(s.word_space(":"));
1604 try!(s.print_expr(&*field.expr));
1610 try!(self.ibox(indent_unit));
1611 if !fields.is_empty() {
1612 try!(word(&mut self.s, ","));
1613 try!(space(&mut self.s));
1615 try!(word(&mut self.s, ".."));
1616 try!(self.print_expr(&**expr));
1619 _ => try!(word(&mut self.s, ",")),
1621 try!(word(&mut self.s, "}"));
1626 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1628 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1629 if exprs.len() == 1 {
1630 try!(word(&mut self.s, ","));
1635 fn print_expr_call(&mut self,
1637 args: &[P<ast::Expr>]) -> io::Result<()> {
1638 try!(self.print_expr_maybe_paren(func));
1639 self.print_call_post(args)
1642 fn print_expr_method_call(&mut self,
1643 ident: ast::SpannedIdent,
1645 args: &[P<ast::Expr>]) -> io::Result<()> {
1646 let base_args = &args[1..];
1647 try!(self.print_expr(&*args[0]));
1648 try!(word(&mut self.s, "."));
1649 try!(self.print_ident(ident.node));
1651 try!(word(&mut self.s, "::<"));
1652 try!(self.commasep(Inconsistent, tys,
1653 |s, ty| s.print_type(&**ty)));
1654 try!(word(&mut self.s, ">"));
1656 self.print_call_post(base_args)
1659 fn print_expr_binary(&mut self,
1662 rhs: &ast::Expr) -> io::Result<()> {
1663 try!(self.print_expr(lhs));
1664 try!(space(&mut self.s));
1665 try!(self.word_space(ast_util::binop_to_string(op.node)));
1666 self.print_expr(rhs)
1669 fn print_expr_unary(&mut self,
1671 expr: &ast::Expr) -> io::Result<()> {
1672 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1673 self.print_expr_maybe_paren(expr)
1676 fn print_expr_addr_of(&mut self,
1677 mutability: ast::Mutability,
1678 expr: &ast::Expr) -> io::Result<()> {
1679 try!(word(&mut self.s, "&"));
1680 try!(self.print_mutability(mutability));
1681 self.print_expr_maybe_paren(expr)
1684 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1685 try!(self.maybe_print_comment(expr.span.lo));
1686 try!(self.ibox(indent_unit));
1687 try!(self.ann.pre(self, NodeExpr(expr)));
1689 ast::ExprBox(ref place, ref expr) => {
1690 try!(self.print_expr_box(place, &**expr));
1692 ast::ExprVec(ref exprs) => {
1693 try!(self.print_expr_vec(&exprs[..]));
1695 ast::ExprRepeat(ref element, ref count) => {
1696 try!(self.print_expr_repeat(&**element, &**count));
1698 ast::ExprStruct(ref path, ref fields, ref wth) => {
1699 try!(self.print_expr_struct(path, &fields[..], wth));
1701 ast::ExprTup(ref exprs) => {
1702 try!(self.print_expr_tup(&exprs[..]));
1704 ast::ExprCall(ref func, ref args) => {
1705 try!(self.print_expr_call(&**func, &args[..]));
1707 ast::ExprMethodCall(ident, ref tys, ref args) => {
1708 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1710 ast::ExprBinary(op, ref lhs, ref rhs) => {
1711 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1713 ast::ExprUnary(op, ref expr) => {
1714 try!(self.print_expr_unary(op, &**expr));
1716 ast::ExprAddrOf(m, ref expr) => {
1717 try!(self.print_expr_addr_of(m, &**expr));
1719 ast::ExprLit(ref lit) => {
1720 try!(self.print_literal(&**lit));
1722 ast::ExprCast(ref expr, ref ty) => {
1723 try!(self.print_expr(&**expr));
1724 try!(space(&mut self.s));
1725 try!(self.word_space("as"));
1726 try!(self.print_type(&**ty));
1728 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1729 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1731 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1732 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1734 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1735 if let Some(ident) = opt_ident {
1736 try!(self.print_ident(ident));
1737 try!(self.word_space(":"));
1739 try!(self.head("while"));
1740 try!(self.print_expr(&**test));
1741 try!(space(&mut self.s));
1742 try!(self.print_block(&**blk));
1744 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1745 if let Some(ident) = opt_ident {
1746 try!(self.print_ident(ident));
1747 try!(self.word_space(":"));
1749 try!(self.head("while let"));
1750 try!(self.print_pat(&**pat));
1751 try!(space(&mut self.s));
1752 try!(self.word_space("="));
1753 try!(self.print_expr(&**expr));
1754 try!(space(&mut self.s));
1755 try!(self.print_block(&**blk));
1757 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1758 if let Some(ident) = opt_ident {
1759 try!(self.print_ident(ident));
1760 try!(self.word_space(":"));
1762 try!(self.head("for"));
1763 try!(self.print_pat(&**pat));
1764 try!(space(&mut self.s));
1765 try!(self.word_space("in"));
1766 try!(self.print_expr(&**iter));
1767 try!(space(&mut self.s));
1768 try!(self.print_block(&**blk));
1770 ast::ExprLoop(ref blk, opt_ident) => {
1771 if let Some(ident) = opt_ident {
1772 try!(self.print_ident(ident));
1773 try!(self.word_space(":"));
1775 try!(self.head("loop"));
1776 try!(space(&mut self.s));
1777 try!(self.print_block(&**blk));
1779 ast::ExprMatch(ref expr, ref arms, _) => {
1780 try!(self.cbox(indent_unit));
1782 try!(self.word_nbsp("match"));
1783 try!(self.print_expr(&**expr));
1784 try!(space(&mut self.s));
1787 try!(self.print_arm(arm));
1789 try!(self.bclose_(expr.span, indent_unit));
1791 ast::ExprClosure(capture_clause, ref decl, ref body) => {
1792 try!(self.print_capture_clause(capture_clause));
1794 try!(self.print_fn_block_args(&**decl));
1795 try!(space(&mut self.s));
1797 let default_return = match decl.output {
1798 ast::DefaultReturn(..) => true,
1802 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1803 try!(self.print_block_unclosed(&**body));
1805 // we extract the block, so as not to create another set of boxes
1806 match body.expr.as_ref().unwrap().node {
1807 ast::ExprBlock(ref blk) => {
1808 try!(self.print_block_unclosed(&**blk));
1811 // this is a bare expression
1812 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1813 try!(self.end()); // need to close a box
1817 // a box will be closed by print_expr, but we didn't want an overall
1818 // wrapper so we closed the corresponding opening. so create an
1819 // empty box to satisfy the close.
1822 ast::ExprBlock(ref blk) => {
1823 // containing cbox, will be closed by print-block at }
1824 try!(self.cbox(indent_unit));
1825 // head-box, will be closed by print-block after {
1827 try!(self.print_block(&**blk));
1829 ast::ExprAssign(ref lhs, ref rhs) => {
1830 try!(self.print_expr(&**lhs));
1831 try!(space(&mut self.s));
1832 try!(self.word_space("="));
1833 try!(self.print_expr(&**rhs));
1835 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1836 try!(self.print_expr(&**lhs));
1837 try!(space(&mut self.s));
1838 try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
1839 try!(self.word_space("="));
1840 try!(self.print_expr(&**rhs));
1842 ast::ExprField(ref expr, id) => {
1843 try!(self.print_expr(&**expr));
1844 try!(word(&mut self.s, "."));
1845 try!(self.print_ident(id.node));
1847 ast::ExprTupField(ref expr, id) => {
1848 try!(self.print_expr(&**expr));
1849 try!(word(&mut self.s, "."));
1850 try!(self.print_usize(id.node));
1852 ast::ExprIndex(ref expr, ref index) => {
1853 try!(self.print_expr(&**expr));
1854 try!(word(&mut self.s, "["));
1855 try!(self.print_expr(&**index));
1856 try!(word(&mut self.s, "]"));
1858 ast::ExprRange(ref start, ref end) => {
1859 if let &Some(ref e) = start {
1860 try!(self.print_expr(&**e));
1862 try!(word(&mut self.s, ".."));
1863 if let &Some(ref e) = end {
1864 try!(self.print_expr(&**e));
1867 ast::ExprPath(None, ref path) => {
1868 try!(self.print_path(path, true, 0))
1870 ast::ExprPath(Some(ref qself), ref path) => {
1871 try!(self.print_qpath(path, qself, true))
1873 ast::ExprBreak(opt_ident) => {
1874 try!(word(&mut self.s, "break"));
1875 try!(space(&mut self.s));
1876 if let Some(ident) = opt_ident {
1877 try!(self.print_ident(ident));
1878 try!(space(&mut self.s));
1881 ast::ExprAgain(opt_ident) => {
1882 try!(word(&mut self.s, "continue"));
1883 try!(space(&mut self.s));
1884 if let Some(ident) = opt_ident {
1885 try!(self.print_ident(ident));
1886 try!(space(&mut self.s))
1889 ast::ExprRet(ref result) => {
1890 try!(word(&mut self.s, "return"));
1893 try!(word(&mut self.s, " "));
1894 try!(self.print_expr(&**expr));
1899 ast::ExprInlineAsm(ref a) => {
1900 try!(word(&mut self.s, "asm!"));
1902 try!(self.print_string(&a.asm, a.asm_str_style));
1903 try!(self.word_space(":"));
1905 try!(self.commasep(Inconsistent, &a.outputs,
1906 |s, &(ref co, ref o, is_rw)| {
1907 match co.slice_shift_char() {
1908 Some(('=', operand)) if is_rw => {
1909 try!(s.print_string(&format!("+{}", operand),
1912 _ => try!(s.print_string(&co, ast::CookedStr))
1915 try!(s.print_expr(&**o));
1919 try!(space(&mut self.s));
1920 try!(self.word_space(":"));
1922 try!(self.commasep(Inconsistent, &a.inputs,
1923 |s, &(ref co, ref o)| {
1924 try!(s.print_string(&co, ast::CookedStr));
1926 try!(s.print_expr(&**o));
1930 try!(space(&mut self.s));
1931 try!(self.word_space(":"));
1933 try!(self.commasep(Inconsistent, &a.clobbers,
1935 try!(s.print_string(&co, ast::CookedStr));
1939 let mut options = vec!();
1941 options.push("volatile");
1944 options.push("alignstack");
1946 if a.dialect == ast::AsmDialect::AsmIntel {
1947 options.push("intel");
1950 if options.len() > 0 {
1951 try!(space(&mut self.s));
1952 try!(self.word_space(":"));
1953 try!(self.commasep(Inconsistent, &*options,
1955 try!(s.print_string(co, ast::CookedStr));
1960 try!(self.pclose());
1962 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1963 ast::ExprParen(ref e) => {
1965 try!(self.print_expr(&**e));
1966 try!(self.pclose());
1969 try!(self.ann.post(self, NodeExpr(expr)));
1973 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
1974 try!(self.print_pat(&*loc.pat));
1975 if let Some(ref ty) = loc.ty {
1976 try!(self.word_space(":"));
1977 try!(self.print_type(&**ty));
1982 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
1983 try!(self.maybe_print_comment(decl.span.lo));
1985 ast::DeclLocal(ref loc) => {
1986 try!(self.space_if_not_bol());
1987 try!(self.ibox(indent_unit));
1988 try!(self.word_nbsp("let"));
1990 try!(self.ibox(indent_unit));
1991 try!(self.print_local_decl(&**loc));
1993 if let Some(ref init) = loc.init {
1995 try!(self.word_space("="));
1996 try!(self.print_expr(&**init));
2000 ast::DeclItem(ref item) => self.print_item(&**item)
2004 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2005 if self.encode_idents_with_hygiene {
2006 let encoded = ident.encode_with_hygiene();
2007 try!(word(&mut self.s, &encoded[..]))
2009 try!(word(&mut self.s, &token::get_ident(ident)))
2011 self.ann.post(self, NodeIdent(&ident))
2014 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2015 word(&mut self.s, &i.to_string())
2018 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2019 try!(word(&mut self.s, &token::get_name(name)));
2020 self.ann.post(self, NodeName(&name))
2023 pub fn print_for_decl(&mut self, loc: &ast::Local,
2024 coll: &ast::Expr) -> io::Result<()> {
2025 try!(self.print_local_decl(loc));
2026 try!(space(&mut self.s));
2027 try!(self.word_space("in"));
2028 self.print_expr(coll)
2031 fn print_path(&mut self,
2033 colons_before_params: bool,
2037 try!(self.maybe_print_comment(path.span.lo));
2039 let mut first = !path.global;
2040 for segment in &path.segments[..path.segments.len()-depth] {
2044 try!(word(&mut self.s, "::"))
2047 try!(self.print_ident(segment.identifier));
2049 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2055 fn print_qpath(&mut self,
2058 colons_before_params: bool)
2061 try!(word(&mut self.s, "<"));
2062 try!(self.print_type(&qself.ty));
2063 if qself.position > 0 {
2064 try!(space(&mut self.s));
2065 try!(self.word_space("as"));
2066 let depth = path.segments.len() - qself.position;
2067 try!(self.print_path(&path, false, depth));
2069 try!(word(&mut self.s, ">"));
2070 try!(word(&mut self.s, "::"));
2071 let item_segment = path.segments.last().unwrap();
2072 try!(self.print_ident(item_segment.identifier));
2073 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2076 fn print_path_parameters(&mut self,
2077 parameters: &ast::PathParameters,
2078 colons_before_params: bool)
2081 if parameters.is_empty() {
2085 if colons_before_params {
2086 try!(word(&mut self.s, "::"))
2090 ast::AngleBracketedParameters(ref data) => {
2091 try!(word(&mut self.s, "<"));
2093 let mut comma = false;
2094 for lifetime in &data.lifetimes {
2096 try!(self.word_space(","))
2098 try!(self.print_lifetime(lifetime));
2102 if !data.types.is_empty() {
2104 try!(self.word_space(","))
2109 |s, ty| s.print_type(&**ty)));
2113 for binding in &*data.bindings {
2115 try!(self.word_space(","))
2117 try!(self.print_ident(binding.ident));
2118 try!(space(&mut self.s));
2119 try!(self.word_space("="));
2120 try!(self.print_type(&*binding.ty));
2124 try!(word(&mut self.s, ">"))
2127 ast::ParenthesizedParameters(ref data) => {
2128 try!(word(&mut self.s, "("));
2132 |s, ty| s.print_type(&**ty)));
2133 try!(word(&mut self.s, ")"));
2138 try!(self.space_if_not_bol());
2139 try!(self.word_space("->"));
2140 try!(self.print_type(&**ty));
2149 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2150 try!(self.maybe_print_comment(pat.span.lo));
2151 try!(self.ann.pre(self, NodePat(pat)));
2152 /* Pat isn't normalized, but the beauty of it
2153 is that it doesn't matter */
2155 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2156 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2157 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2158 match binding_mode {
2159 ast::BindByRef(mutbl) => {
2160 try!(self.word_nbsp("ref"));
2161 try!(self.print_mutability(mutbl));
2163 ast::BindByValue(ast::MutImmutable) => {}
2164 ast::BindByValue(ast::MutMutable) => {
2165 try!(self.word_nbsp("mut"));
2168 try!(self.print_ident(path1.node));
2171 try!(word(&mut self.s, "@"));
2172 try!(self.print_pat(&**p));
2177 ast::PatEnum(ref path, ref args_) => {
2178 try!(self.print_path(path, true, 0));
2180 None => try!(word(&mut self.s, "(..)")),
2182 if !args.is_empty() {
2184 try!(self.commasep(Inconsistent, &args[..],
2185 |s, p| s.print_pat(&**p)));
2186 try!(self.pclose());
2191 ast::PatStruct(ref path, ref fields, etc) => {
2192 try!(self.print_path(path, true, 0));
2194 try!(self.word_space("{"));
2195 try!(self.commasep_cmnt(
2196 Consistent, &fields[..],
2198 try!(s.cbox(indent_unit));
2199 if !f.node.is_shorthand {
2200 try!(s.print_ident(f.node.ident));
2201 try!(s.word_nbsp(":"));
2203 try!(s.print_pat(&*f.node.pat));
2206 |f| f.node.pat.span));
2208 if fields.len() != 0 { try!(self.word_space(",")); }
2209 try!(word(&mut self.s, ".."));
2211 try!(space(&mut self.s));
2212 try!(word(&mut self.s, "}"));
2214 ast::PatTup(ref elts) => {
2216 try!(self.commasep(Inconsistent,
2218 |s, p| s.print_pat(&**p)));
2219 if elts.len() == 1 {
2220 try!(word(&mut self.s, ","));
2222 try!(self.pclose());
2224 ast::PatBox(ref inner) => {
2225 try!(word(&mut self.s, "box "));
2226 try!(self.print_pat(&**inner));
2228 ast::PatRegion(ref inner, mutbl) => {
2229 try!(word(&mut self.s, "&"));
2230 if mutbl == ast::MutMutable {
2231 try!(word(&mut self.s, "mut "));
2233 try!(self.print_pat(&**inner));
2235 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2236 ast::PatRange(ref begin, ref end) => {
2237 try!(self.print_expr(&**begin));
2238 try!(space(&mut self.s));
2239 try!(word(&mut self.s, "..."));
2240 try!(self.print_expr(&**end));
2242 ast::PatVec(ref before, ref slice, ref after) => {
2243 try!(word(&mut self.s, "["));
2244 try!(self.commasep(Inconsistent,
2246 |s, p| s.print_pat(&**p)));
2247 if let Some(ref p) = *slice {
2248 if !before.is_empty() { try!(self.word_space(",")); }
2249 try!(self.print_pat(&**p));
2251 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2252 // this case is handled by print_pat
2254 _ => try!(word(&mut self.s, "..")),
2256 if !after.is_empty() { try!(self.word_space(",")); }
2258 try!(self.commasep(Inconsistent,
2260 |s, p| s.print_pat(&**p)));
2261 try!(word(&mut self.s, "]"));
2263 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2265 self.ann.post(self, NodePat(pat))
2268 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2269 // I have no idea why this check is necessary, but here it
2271 if arm.attrs.is_empty() {
2272 try!(space(&mut self.s));
2274 try!(self.cbox(indent_unit));
2276 try!(self.print_outer_attributes(&arm.attrs));
2277 let mut first = true;
2278 for p in &arm.pats {
2282 try!(space(&mut self.s));
2283 try!(self.word_space("|"));
2285 try!(self.print_pat(&**p));
2287 try!(space(&mut self.s));
2288 if let Some(ref e) = arm.guard {
2289 try!(self.word_space("if"));
2290 try!(self.print_expr(&**e));
2291 try!(space(&mut self.s));
2293 try!(self.word_space("=>"));
2295 match arm.body.node {
2296 ast::ExprBlock(ref blk) => {
2297 // the block will close the pattern's ibox
2298 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2300 // If it is a user-provided unsafe block, print a comma after it
2301 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2302 try!(word(&mut self.s, ","));
2306 try!(self.end()); // close the ibox for the pattern
2307 try!(self.print_expr(&*arm.body));
2308 try!(word(&mut self.s, ","));
2311 self.end() // close enclosing cbox
2314 // Returns whether it printed anything
2315 fn print_explicit_self(&mut self,
2316 explicit_self: &ast::ExplicitSelf_,
2317 mutbl: ast::Mutability) -> io::Result<bool> {
2318 try!(self.print_mutability(mutbl));
2319 match *explicit_self {
2320 ast::SelfStatic => { return Ok(false); }
2321 ast::SelfValue(_) => {
2322 try!(word(&mut self.s, "self"));
2324 ast::SelfRegion(ref lt, m, _) => {
2325 try!(word(&mut self.s, "&"));
2326 try!(self.print_opt_lifetime(lt));
2327 try!(self.print_mutability(m));
2328 try!(word(&mut self.s, "self"));
2330 ast::SelfExplicit(ref typ, _) => {
2331 try!(word(&mut self.s, "self"));
2332 try!(self.word_space(":"));
2333 try!(self.print_type(&**typ));
2339 pub fn print_fn(&mut self,
2341 unsafety: ast::Unsafety,
2343 name: Option<ast::Ident>,
2344 generics: &ast::Generics,
2345 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2346 vis: ast::Visibility) -> io::Result<()> {
2347 try!(self.print_fn_header_info(unsafety, abi, vis));
2349 if let Some(name) = name {
2351 try!(self.print_ident(name));
2353 try!(self.print_generics(generics));
2354 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2355 self.print_where_clause(&generics.where_clause)
2358 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2359 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2361 // It is unfortunate to duplicate the commasep logic, but we want the
2362 // self type and the args all in the same box.
2363 try!(self.rbox(0, Inconsistent));
2364 let mut first = true;
2365 if let Some(explicit_self) = opt_explicit_self {
2366 let m = match explicit_self {
2367 &ast::SelfStatic => ast::MutImmutable,
2368 _ => match decl.inputs[0].pat.node {
2369 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2370 _ => ast::MutImmutable
2373 first = !try!(self.print_explicit_self(explicit_self, m));
2376 // HACK(eddyb) ignore the separately printed self argument.
2377 let args = if first {
2384 if first { first = false; } else { try!(self.word_space(",")); }
2385 try!(self.print_arg(arg));
2391 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2392 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2395 try!(self.print_fn_args(decl, opt_explicit_self));
2397 try!(word(&mut self.s, ", ..."));
2399 try!(self.pclose());
2401 self.print_fn_output(decl)
2404 pub fn print_fn_block_args(
2408 try!(word(&mut self.s, "|"));
2409 try!(self.print_fn_args(decl, None));
2410 try!(word(&mut self.s, "|"));
2412 if let ast::DefaultReturn(..) = decl.output {
2416 try!(self.space_if_not_bol());
2417 try!(self.word_space("->"));
2419 ast::Return(ref ty) => {
2420 try!(self.print_type(&**ty));
2421 self.maybe_print_comment(ty.span.lo)
2423 ast::DefaultReturn(..) => unreachable!(),
2424 ast::NoReturn(span) => {
2425 try!(self.word_nbsp("!"));
2426 self.maybe_print_comment(span.lo)
2431 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2433 match capture_clause {
2434 ast::CaptureByValue => self.word_space("move"),
2435 ast::CaptureByRef => Ok(()),
2439 pub fn print_bounds(&mut self,
2441 bounds: &[ast::TyParamBound])
2443 if !bounds.is_empty() {
2444 try!(word(&mut self.s, prefix));
2445 let mut first = true;
2446 for bound in bounds {
2451 try!(self.word_space("+"));
2455 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2456 self.print_poly_trait_ref(tref)
2458 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2459 try!(word(&mut self.s, "?"));
2460 self.print_poly_trait_ref(tref)
2462 RegionTyParamBound(ref lt) => {
2463 self.print_lifetime(lt)
2473 pub fn print_lifetime(&mut self,
2474 lifetime: &ast::Lifetime)
2477 self.print_name(lifetime.name)
2480 pub fn print_lifetime_def(&mut self,
2481 lifetime: &ast::LifetimeDef)
2484 try!(self.print_lifetime(&lifetime.lifetime));
2486 for v in &lifetime.bounds {
2487 try!(word(&mut self.s, sep));
2488 try!(self.print_lifetime(v));
2494 pub fn print_generics(&mut self,
2495 generics: &ast::Generics)
2498 let total = generics.lifetimes.len() + generics.ty_params.len();
2503 try!(word(&mut self.s, "<"));
2505 let mut ints = Vec::new();
2510 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2511 if idx < generics.lifetimes.len() {
2512 let lifetime = &generics.lifetimes[idx];
2513 s.print_lifetime_def(lifetime)
2515 let idx = idx - generics.lifetimes.len();
2516 let param = &generics.ty_params[idx];
2517 s.print_ty_param(param)
2521 try!(word(&mut self.s, ">"));
2525 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2526 try!(self.print_ident(param.ident));
2527 try!(self.print_bounds(":", ¶m.bounds));
2528 match param.default {
2529 Some(ref default) => {
2530 try!(space(&mut self.s));
2531 try!(self.word_space("="));
2532 self.print_type(&**default)
2538 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2540 if where_clause.predicates.len() == 0 {
2544 try!(space(&mut self.s));
2545 try!(self.word_space("where"));
2547 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2549 try!(self.word_space(","));
2553 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2557 try!(self.print_formal_lifetime_list(bound_lifetimes));
2558 try!(self.print_type(&**bounded_ty));
2559 try!(self.print_bounds(":", bounds));
2561 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2564 try!(self.print_lifetime(lifetime));
2565 try!(word(&mut self.s, ":"));
2567 for (i, bound) in bounds.iter().enumerate() {
2568 try!(self.print_lifetime(bound));
2571 try!(word(&mut self.s, ":"));
2575 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2576 try!(self.print_path(path, false, 0));
2577 try!(space(&mut self.s));
2578 try!(self.word_space("="));
2579 try!(self.print_type(&**ty));
2587 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
2588 try!(self.ibox(indent_unit));
2590 ast::MetaWord(ref name) => {
2591 try!(word(&mut self.s, &name));
2593 ast::MetaNameValue(ref name, ref value) => {
2594 try!(self.word_space(&name[..]));
2595 try!(self.word_space("="));
2596 try!(self.print_literal(value));
2598 ast::MetaList(ref name, ref items) => {
2599 try!(word(&mut self.s, &name));
2601 try!(self.commasep(Consistent,
2603 |s, i| s.print_meta_item(&**i)));
2604 try!(self.pclose());
2610 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2612 ast::ViewPathSimple(ident, ref path) => {
2613 try!(self.print_path(path, false, 0));
2615 // FIXME(#6993) can't compare identifiers directly here
2616 if path.segments.last().unwrap().identifier.name !=
2618 try!(space(&mut self.s));
2619 try!(self.word_space("as"));
2620 try!(self.print_ident(ident));
2626 ast::ViewPathGlob(ref path) => {
2627 try!(self.print_path(path, false, 0));
2628 word(&mut self.s, "::*")
2631 ast::ViewPathList(ref path, ref idents) => {
2632 if path.segments.is_empty() {
2633 try!(word(&mut self.s, "{"));
2635 try!(self.print_path(path, false, 0));
2636 try!(word(&mut self.s, "::{"));
2638 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2640 ast::PathListIdent { name, .. } => {
2643 ast::PathListMod { .. } => {
2644 word(&mut s.s, "self")
2648 word(&mut self.s, "}")
2653 pub fn print_mutability(&mut self,
2654 mutbl: ast::Mutability) -> io::Result<()> {
2656 ast::MutMutable => self.word_nbsp("mut"),
2657 ast::MutImmutable => Ok(()),
2661 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2662 try!(self.print_mutability(mt.mutbl));
2663 self.print_type(&*mt.ty)
2666 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2667 try!(self.ibox(indent_unit));
2668 match input.ty.node {
2669 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2671 match input.pat.node {
2672 ast::PatIdent(_, ref path1, _) if
2674 parse::token::special_idents::invalid.name => {
2678 try!(self.print_pat(&*input.pat));
2679 try!(word(&mut self.s, ":"));
2680 try!(space(&mut self.s));
2683 try!(self.print_type(&*input.ty));
2689 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2690 if let ast::DefaultReturn(..) = decl.output {
2694 try!(self.space_if_not_bol());
2695 try!(self.ibox(indent_unit));
2696 try!(self.word_space("->"));
2699 try!(self.word_nbsp("!")),
2700 ast::DefaultReturn(..) => unreachable!(),
2701 ast::Return(ref ty) =>
2702 try!(self.print_type(&**ty))
2707 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2712 pub fn print_ty_fn(&mut self,
2714 unsafety: ast::Unsafety,
2716 name: Option<ast::Ident>,
2717 generics: &ast::Generics,
2718 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2720 try!(self.ibox(indent_unit));
2721 if generics.lifetimes.len() > 0 || generics.ty_params.len() > 0 {
2722 try!(word(&mut self.s, "for"));
2723 try!(self.print_generics(generics));
2725 let generics = ast::Generics {
2726 lifetimes: Vec::new(),
2727 ty_params: OwnedSlice::empty(),
2728 where_clause: ast::WhereClause {
2729 id: ast::DUMMY_NODE_ID,
2730 predicates: Vec::new(),
2733 try!(self.print_fn(decl, unsafety, abi, name,
2734 &generics, opt_explicit_self,
2739 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2740 next_pos: Option<BytePos>)
2742 let cm = match self.cm {
2746 match self.next_comment() {
2748 if (*cmnt).style != comments::Trailing { return Ok(()) }
2749 let span_line = cm.lookup_char_pos(span.hi);
2750 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2751 let mut next = (*cmnt).pos + BytePos(1);
2752 match next_pos { None => (), Some(p) => next = p }
2753 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2754 span_line.line == comment_line.line {
2755 try!(self.print_comment(cmnt));
2756 self.cur_cmnt_and_lit.cur_cmnt += 1;
2764 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2765 // If there aren't any remaining comments, then we need to manually
2766 // make sure there is a line break at the end.
2767 if self.next_comment().is_none() {
2768 try!(hardbreak(&mut self.s));
2771 match self.next_comment() {
2773 try!(self.print_comment(cmnt));
2774 self.cur_cmnt_and_lit.cur_cmnt += 1;
2782 pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
2783 try!(self.maybe_print_comment(lit.span.lo));
2784 match self.next_lit(lit.span.lo) {
2786 return word(&mut self.s, &(*ltrl).lit);
2791 ast::LitStr(ref st, style) => self.print_string(&st, style),
2792 ast::LitByte(byte) => {
2793 let mut res = String::from_str("b'");
2794 res.extend(ascii::escape_default(byte).map(|c| c as char));
2796 word(&mut self.s, &res[..])
2798 ast::LitChar(ch) => {
2799 let mut res = String::from_str("'");
2800 res.extend(ch.escape_default());
2802 word(&mut self.s, &res[..])
2804 ast::LitInt(i, t) => {
2806 ast::SignedIntLit(st, ast::Plus) => {
2808 &ast_util::int_ty_to_string(st, Some(i as i64)))
2810 ast::SignedIntLit(st, ast::Minus) => {
2811 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2813 &format!("-{}", istr))
2815 ast::UnsignedIntLit(ut) => {
2816 word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i)))
2818 ast::UnsuffixedIntLit(ast::Plus) => {
2819 word(&mut self.s, &format!("{}", i))
2821 ast::UnsuffixedIntLit(ast::Minus) => {
2822 word(&mut self.s, &format!("-{}", i))
2826 ast::LitFloat(ref f, t) => {
2831 &ast_util::float_ty_to_string(t)))
2833 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]),
2834 ast::LitBool(val) => {
2835 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2837 ast::LitBinary(ref v) => {
2838 let mut escaped: String = String::new();
2840 escaped.extend(ascii::escape_default(ch)
2841 .map(|c| c as char));
2843 word(&mut self.s, &format!("b\"{}\"", escaped))
2848 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2849 match self.literals {
2851 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2852 let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2853 if ltrl.pos > pos { return None; }
2854 self.cur_cmnt_and_lit.cur_lit += 1;
2855 if ltrl.pos == pos { return Some(ltrl); }
2863 pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
2865 match self.next_comment() {
2867 if (*cmnt).pos < pos {
2868 try!(self.print_comment(cmnt));
2869 self.cur_cmnt_and_lit.cur_cmnt += 1;
2878 pub fn print_comment(&mut self,
2879 cmnt: &comments::Comment) -> io::Result<()> {
2881 comments::Mixed => {
2882 assert_eq!(cmnt.lines.len(), 1);
2883 try!(zerobreak(&mut self.s));
2884 try!(word(&mut self.s, &cmnt.lines[0]));
2885 zerobreak(&mut self.s)
2887 comments::Isolated => {
2888 try!(self.hardbreak_if_not_bol());
2889 for line in &cmnt.lines {
2890 // Don't print empty lines because they will end up as trailing
2892 if !line.is_empty() {
2893 try!(word(&mut self.s, &line[..]));
2895 try!(hardbreak(&mut self.s));
2899 comments::Trailing => {
2900 try!(word(&mut self.s, " "));
2901 if cmnt.lines.len() == 1 {
2902 try!(word(&mut self.s, &cmnt.lines[0]));
2903 hardbreak(&mut self.s)
2906 for line in &cmnt.lines {
2907 if !line.is_empty() {
2908 try!(word(&mut self.s, &line[..]));
2910 try!(hardbreak(&mut self.s));
2915 comments::BlankLine => {
2916 // We need to do at least one, possibly two hardbreaks.
2917 let is_semi = match self.s.last_token() {
2918 pp::Token::String(s, _) => ";" == s,
2921 if is_semi || self.is_begin() || self.is_end() {
2922 try!(hardbreak(&mut self.s));
2924 hardbreak(&mut self.s)
2929 pub fn print_string(&mut self, st: &str,
2930 style: ast::StrStyle) -> io::Result<()> {
2931 let st = match style {
2933 (format!("\"{}\"", st.escape_default()))
2936 (format!("r{delim}\"{string}\"{delim}",
2937 delim=repeat("#", n),
2941 word(&mut self.s, &st[..])
2944 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2945 match self.comments {
2946 Some(ref cmnts) => {
2947 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2948 Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2957 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2958 opt_abi: Option<abi::Abi>)
2961 Some(abi::Rust) => Ok(()),
2963 try!(self.word_nbsp("extern"));
2964 self.word_nbsp(&abi.to_string())
2970 pub fn print_extern_opt_abi(&mut self,
2971 opt_abi: Option<abi::Abi>) -> io::Result<()> {
2974 try!(self.word_nbsp("extern"));
2975 self.word_nbsp(&abi.to_string())
2981 pub fn print_fn_header_info(&mut self,
2982 unsafety: ast::Unsafety,
2984 vis: ast::Visibility) -> io::Result<()> {
2985 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2986 try!(self.print_unsafety(unsafety));
2988 if abi != abi::Rust {
2989 try!(self.word_nbsp("extern"));
2990 try!(self.word_nbsp(&abi.to_string()));
2993 word(&mut self.s, "fn")
2996 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
2998 ast::Unsafety::Normal => Ok(()),
2999 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3004 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3016 fn test_fun_to_string() {
3017 let abba_ident = token::str_to_ident("abba");
3019 let decl = ast::FnDecl {
3021 output: ast::DefaultReturn(codemap::DUMMY_SP),
3024 let generics = ast_util::empty_generics();
3025 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3031 fn test_variant_to_string() {
3032 let ident = token::str_to_ident("principal_skinner");
3034 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3037 // making this up as I go.... ?
3038 kind: ast::TupleVariantKind(Vec::new()),
3044 let varstr = variant_to_string(&var);
3045 assert_eq!(varstr, "pub principal_skinner");
3049 fn test_signed_int_to_string() {
3050 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3051 let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3052 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3053 lit_to_string(&codemap::dummy_spanned(neg_int)));