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::*;
14 use ast::{self, TokenTree};
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use attr::ThinAttributesExt;
18 use util::parser::AssocOp;
20 use owned_slice::OwnedSlice;
21 use attr::{AttrMetaMethods, AttributeMethods};
22 use codemap::{self, CodeMap, BytePos};
24 use parse::token::{self, BinOpToken, Token, InternedString};
25 use parse::lexer::comments;
27 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
28 use print::pp::{Breaks, eof};
29 use print::pp::Breaks::{Consistent, Inconsistent};
34 use std::io::{self, Write, Read};
37 pub enum AnnNode<'a> {
38 NodeIdent(&'a ast::Ident),
39 NodeName(&'a ast::Name),
40 NodeBlock(&'a ast::Block),
41 NodeItem(&'a ast::Item),
42 NodeSubItem(ast::NodeId),
43 NodeExpr(&'a ast::Expr),
44 NodePat(&'a ast::Pat),
48 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
49 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
52 #[derive(Copy, Clone)]
55 impl PpAnn for NoAnn {}
57 #[derive(Copy, Clone)]
58 pub struct CurrentCommentAndLiteral {
63 pub struct State<'a> {
64 pub s: pp::Printer<'a>,
65 cm: Option<&'a CodeMap>,
66 comments: Option<Vec<comments::Comment> >,
67 literals: Option<Vec<comments::Literal> >,
68 cur_cmnt_and_lit: CurrentCommentAndLiteral,
69 boxes: Vec<pp::Breaks>,
73 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
74 static NO_ANN: NoAnn = NoAnn;
75 rust_printer_annotated(writer, &NO_ANN)
78 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
79 ann: &'a PpAnn) -> State<'a> {
81 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
85 cur_cmnt_and_lit: CurrentCommentAndLiteral {
94 pub const INDENT_UNIT: usize = 4;
96 pub const DEFAULT_COLUMNS: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
102 span_diagnostic: &diagnostic::SpanHandler,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm,
116 if is_expanded && !std_inject::no_std(krate) {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
122 // #![feature(prelude_import)]
123 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
124 let list = attr::mk_list_item(InternedString::new("feature"),
125 vec![prelude_import_meta]);
126 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
127 try!(s.print_attribute(&fake_attr));
130 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
131 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
132 try!(s.print_attribute(&fake_attr));
135 try!(s.print_mod(&krate.module, &krate.attrs));
136 try!(s.print_remaining_comments());
141 pub fn new_from_input(cm: &'a CodeMap,
142 span_diagnostic: &diagnostic::SpanHandler,
147 is_expanded: bool) -> State<'a> {
148 let (cmnts, lits) = comments::gather_comments_and_literals(
158 // If the code is post expansion, don't use the table of
159 // literals, since it doesn't correspond with the literals
160 // in the AST anymore.
161 if is_expanded { None } else { Some(lits) })
164 pub fn new(cm: &'a CodeMap,
167 comments: Option<Vec<comments::Comment>>,
168 literals: Option<Vec<comments::Literal>>) -> State<'a> {
170 s: pp::mk_printer(out, DEFAULT_COLUMNS),
174 cur_cmnt_and_lit: CurrentCommentAndLiteral {
184 pub fn to_string<F>(f: F) -> String where
185 F: FnOnce(&mut State) -> io::Result<()>,
187 let mut wr = Vec::new();
189 let mut printer = rust_printer(Box::new(&mut wr));
190 f(&mut printer).unwrap();
191 eof(&mut printer.s).unwrap();
193 String::from_utf8(wr).unwrap()
196 pub fn binop_to_string(op: BinOpToken) -> &'static str {
202 token::Percent => "%",
211 pub fn token_to_string(tok: &Token) -> String {
213 token::Eq => "=".to_string(),
214 token::Lt => "<".to_string(),
215 token::Le => "<=".to_string(),
216 token::EqEq => "==".to_string(),
217 token::Ne => "!=".to_string(),
218 token::Ge => ">=".to_string(),
219 token::Gt => ">".to_string(),
220 token::Not => "!".to_string(),
221 token::Tilde => "~".to_string(),
222 token::OrOr => "||".to_string(),
223 token::AndAnd => "&&".to_string(),
224 token::BinOp(op) => binop_to_string(op).to_string(),
225 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
227 /* Structural symbols */
228 token::At => "@".to_string(),
229 token::Dot => ".".to_string(),
230 token::DotDot => "..".to_string(),
231 token::DotDotDot => "...".to_string(),
232 token::Comma => ",".to_string(),
233 token::Semi => ";".to_string(),
234 token::Colon => ":".to_string(),
235 token::ModSep => "::".to_string(),
236 token::RArrow => "->".to_string(),
237 token::LArrow => "<-".to_string(),
238 token::FatArrow => "=>".to_string(),
239 token::OpenDelim(token::Paren) => "(".to_string(),
240 token::CloseDelim(token::Paren) => ")".to_string(),
241 token::OpenDelim(token::Bracket) => "[".to_string(),
242 token::CloseDelim(token::Bracket) => "]".to_string(),
243 token::OpenDelim(token::Brace) => "{".to_string(),
244 token::CloseDelim(token::Brace) => "}".to_string(),
245 token::Pound => "#".to_string(),
246 token::Dollar => "$".to_string(),
247 token::Question => "?".to_string(),
250 token::Literal(lit, suf) => {
251 let mut out = match lit {
252 token::Byte(b) => format!("b'{}'", b),
253 token::Char(c) => format!("'{}'", c),
254 token::Float(c) => c.to_string(),
255 token::Integer(c) => c.to_string(),
256 token::Str_(s) => format!("\"{}\"", s),
257 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
258 delim=repeat("#", n),
260 token::ByteStr(v) => format!("b\"{}\"", v),
261 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
262 delim=repeat("#", n),
266 if let Some(s) = suf {
267 out.push_str(&s.as_str())
273 /* Name components */
274 token::Ident(s, _) => s.to_string(),
275 token::Lifetime(s) => s.to_string(),
276 token::Underscore => "_".to_string(),
279 token::DocComment(s) => s.to_string(),
280 token::SubstNt(s, _) => format!("${}", s),
281 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
282 token::Eof => "<eof>".to_string(),
283 token::Whitespace => " ".to_string(),
284 token::Comment => "/* */".to_string(),
285 token::Shebang(s) => format!("/* shebang: {}*/", s),
287 token::SpecialVarNt(var) => format!("${}", var.as_str()),
289 token::Interpolated(ref nt) => match *nt {
290 token::NtExpr(ref e) => expr_to_string(&**e),
291 token::NtMeta(ref e) => meta_item_to_string(&**e),
292 token::NtTy(ref e) => ty_to_string(&**e),
293 token::NtPath(ref e) => path_to_string(&**e),
294 token::NtItem(ref e) => item_to_string(&**e),
295 token::NtBlock(ref e) => block_to_string(&**e),
296 token::NtStmt(ref e) => stmt_to_string(&**e),
297 token::NtPat(ref e) => pat_to_string(&**e),
298 token::NtIdent(ref e, _) => ident_to_string(e.node),
299 token::NtTT(ref e) => tt_to_string(&**e),
300 token::NtArm(ref e) => arm_to_string(&*e),
301 token::NtImplItem(ref e) => impl_item_to_string(&**e),
302 token::NtTraitItem(ref e) => trait_item_to_string(&**e),
303 token::NtGenerics(ref e) => generics_to_string(&*e),
304 token::NtWhereClause(ref e) => where_clause_to_string(&*e),
305 token::NtArg(ref e) => arg_to_string(&*e),
310 pub fn ty_to_string(ty: &ast::Ty) -> String {
311 to_string(|s| s.print_type(ty))
314 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
315 to_string(|s| s.print_bounds("", bounds))
318 pub fn pat_to_string(pat: &ast::Pat) -> String {
319 to_string(|s| s.print_pat(pat))
322 pub fn arm_to_string(arm: &ast::Arm) -> String {
323 to_string(|s| s.print_arm(arm))
326 pub fn expr_to_string(e: &ast::Expr) -> String {
327 to_string(|s| s.print_expr(e))
330 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
331 to_string(|s| s.print_lifetime(e))
334 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
335 to_string(|s| s.print_tt(tt))
338 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
339 to_string(|s| s.print_tts(tts))
342 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
343 to_string(|s| s.print_stmt(stmt))
346 pub fn attr_to_string(attr: &ast::Attribute) -> String {
347 to_string(|s| s.print_attribute(attr))
350 pub fn item_to_string(i: &ast::Item) -> String {
351 to_string(|s| s.print_item(i))
354 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
355 to_string(|s| s.print_impl_item(i))
358 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
359 to_string(|s| s.print_trait_item(i))
362 pub fn generics_to_string(generics: &ast::Generics) -> String {
363 to_string(|s| s.print_generics(generics))
366 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
367 to_string(|s| s.print_where_clause(i))
370 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
371 to_string(|s| s.print_fn_block_args(p))
374 pub fn path_to_string(p: &ast::Path) -> String {
375 to_string(|s| s.print_path(p, false, 0))
378 pub fn ident_to_string(id: ast::Ident) -> String {
379 to_string(|s| s.print_ident(id))
382 pub fn fun_to_string(decl: &ast::FnDecl,
383 unsafety: ast::Unsafety,
384 constness: ast::Constness,
386 opt_explicit_self: Option<&ast::ExplicitSelf_>,
387 generics: &ast::Generics)
391 try!(s.print_fn(decl, unsafety, constness, 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))
436 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
438 ast::Public => format!("pub {}", s),
439 ast::Inherited => s.to_string()
443 fn needs_parentheses(expr: &ast::Expr) -> bool {
445 ast::ExprAssign(..) | ast::ExprBinary(..) |
446 ast::ExprClosure(..) |
447 ast::ExprAssignOp(..) | ast::ExprCast(..) |
448 ast::ExprInPlace(..) => true,
453 pub trait PrintState<'a> {
454 fn writer(&mut self) -> &mut pp::Printer<'a>;
455 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
456 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
457 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
458 fn literals(&self) -> &Option<Vec<comments::Literal>>;
460 fn word_space(&mut self, w: &str) -> io::Result<()> {
461 try!(word(self.writer(), w));
465 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
467 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
469 fn is_begin(&mut self) -> bool {
470 match self.writer().last_token() {
471 pp::Token::Begin(_) => true,
476 fn is_end(&mut self) -> bool {
477 match self.writer().last_token() {
478 pp::Token::End => true,
483 // is this the beginning of a line?
484 fn is_bol(&mut self) -> bool {
485 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
488 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
490 try!(hardbreak(self.writer()))
496 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
497 self.boxes().push(b);
498 pp::rbox(self.writer(), u, b)
501 fn ibox(&mut self, u: usize) -> io::Result<()> {
502 self.boxes().push(pp::Breaks::Inconsistent);
503 pp::ibox(self.writer(), u)
506 fn end(&mut self) -> io::Result<()> {
507 self.boxes().pop().unwrap();
508 pp::end(self.writer())
511 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
512 where F: FnMut(&mut Self, &T) -> io::Result<()>,
514 try!(self.rbox(0, b));
515 let mut first = true;
517 if first { first = false; } else { try!(self.word_space(",")); }
523 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
524 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
526 let mut result = None;
528 if let &Some(ref lits) = self.literals()
530 while cur_lit < lits.len() {
531 let ltrl = (*lits)[cur_lit].clone();
532 if ltrl.pos > pos { break; }
541 self.cur_cmnt_and_lit().cur_lit = cur_lit;
545 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
547 match self.next_comment() {
549 if (*cmnt).pos < pos {
550 try!(self.print_comment(cmnt));
551 self.cur_cmnt_and_lit().cur_cmnt += 1;
560 fn print_comment(&mut self,
561 cmnt: &comments::Comment) -> io::Result<()> {
564 assert_eq!(cmnt.lines.len(), 1);
565 try!(zerobreak(self.writer()));
566 try!(word(self.writer(), &cmnt.lines[0]));
567 zerobreak(self.writer())
569 comments::Isolated => {
570 try!(self.hardbreak_if_not_bol());
571 for line in &cmnt.lines {
572 // Don't print empty lines because they will end up as trailing
574 if !line.is_empty() {
575 try!(word(self.writer(), &line[..]));
577 try!(hardbreak(self.writer()));
581 comments::Trailing => {
582 try!(word(self.writer(), " "));
583 if cmnt.lines.len() == 1 {
584 try!(word(self.writer(), &cmnt.lines[0]));
585 hardbreak(self.writer())
588 for line in &cmnt.lines {
589 if !line.is_empty() {
590 try!(word(self.writer(), &line[..]));
592 try!(hardbreak(self.writer()));
597 comments::BlankLine => {
598 // We need to do at least one, possibly two hardbreaks.
599 let is_semi = match self.writer().last_token() {
600 pp::Token::String(s, _) => ";" == s,
603 if is_semi || self.is_begin() || self.is_end() {
604 try!(hardbreak(self.writer()));
606 hardbreak(self.writer())
611 fn next_comment(&mut self) -> Option<comments::Comment> {
612 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
613 match *self.comments() {
615 if cur_cmnt < cmnts.len() {
616 Some(cmnts[cur_cmnt].clone())
625 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
626 try!(self.maybe_print_comment(lit.span.lo));
627 match self.next_lit(lit.span.lo) {
629 return word(self.writer(), &(*ltrl).lit);
634 ast::LitStr(ref st, style) => self.print_string(&st, style),
635 ast::LitByte(byte) => {
636 let mut res = String::from("b'");
637 res.extend(ascii::escape_default(byte).map(|c| c as char));
639 word(self.writer(), &res[..])
641 ast::LitChar(ch) => {
642 let mut res = String::from("'");
643 res.extend(ch.escape_default());
645 word(self.writer(), &res[..])
647 ast::LitInt(i, t) => {
649 ast::SignedIntLit(st, ast::Plus) => {
651 &st.val_to_string(i as i64))
653 ast::SignedIntLit(st, ast::Minus) => {
654 let istr = st.val_to_string(-(i as i64));
656 &format!("-{}", istr))
658 ast::UnsignedIntLit(ut) => {
659 word(self.writer(), &ut.val_to_string(i))
661 ast::UnsuffixedIntLit(ast::Plus) => {
662 word(self.writer(), &format!("{}", i))
664 ast::UnsuffixedIntLit(ast::Minus) => {
665 word(self.writer(), &format!("-{}", i))
669 ast::LitFloat(ref f, t) => {
676 ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
677 ast::LitBool(val) => {
678 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
680 ast::LitByteStr(ref v) => {
681 let mut escaped: String = String::new();
682 for &ch in v.iter() {
683 escaped.extend(ascii::escape_default(ch)
684 .map(|c| c as char));
686 word(self.writer(), &format!("b\"{}\"", escaped))
691 fn print_string(&mut self, st: &str,
692 style: ast::StrStyle) -> io::Result<()> {
693 let st = match style {
695 (format!("\"{}\"", st.escape_default()))
698 (format!("r{delim}\"{string}\"{delim}",
699 delim=repeat("#", n),
703 word(self.writer(), &st[..])
706 fn print_inner_attributes(&mut self,
707 attrs: &[ast::Attribute]) -> io::Result<()> {
708 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
711 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
712 attrs: &[ast::Attribute])
714 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
717 fn print_outer_attributes(&mut self,
718 attrs: &[ast::Attribute]) -> io::Result<()> {
719 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
722 fn print_inner_attributes_inline(&mut self,
723 attrs: &[ast::Attribute]) -> io::Result<()> {
724 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
727 fn print_outer_attributes_inline(&mut self,
728 attrs: &[ast::Attribute]) -> io::Result<()> {
729 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
732 fn print_either_attributes(&mut self,
733 attrs: &[ast::Attribute],
734 kind: ast::AttrStyle,
736 trailing_hardbreak: bool) -> io::Result<()> {
739 if attr.node.style == kind {
740 try!(self.print_attribute_inline(attr, is_inline));
747 if count > 0 && trailing_hardbreak && !is_inline {
748 try!(self.hardbreak_if_not_bol());
753 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
754 self.print_attribute_inline(attr, false)
757 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
758 is_inline: bool) -> io::Result<()> {
760 try!(self.hardbreak_if_not_bol());
762 try!(self.maybe_print_comment(attr.span.lo));
763 if attr.node.is_sugared_doc {
764 word(self.writer(), &attr.value_str().unwrap())
766 match attr.node.style {
767 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
768 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
770 try!(self.print_meta_item(&*attr.meta()));
771 word(self.writer(), "]")
775 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
776 try!(self.ibox(INDENT_UNIT));
778 ast::MetaWord(ref name) => {
779 try!(word(self.writer(), &name));
781 ast::MetaNameValue(ref name, ref value) => {
782 try!(self.word_space(&name[..]));
783 try!(self.word_space("="));
784 try!(self.print_literal(value));
786 ast::MetaList(ref name, ref items) => {
787 try!(word(self.writer(), &name));
789 try!(self.commasep(Consistent,
791 |s, i| s.print_meta_item(&**i)));
798 fn space_if_not_bol(&mut self) -> io::Result<()> {
799 if !self.is_bol() { try!(space(self.writer())); }
803 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
806 impl<'a> PrintState<'a> for State<'a> {
807 fn writer(&mut self) -> &mut pp::Printer<'a> {
811 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
815 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
819 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
820 &mut self.cur_cmnt_and_lit
823 fn literals(&self) -> &Option<Vec<comments::Literal>> {
829 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
830 self.boxes.push(pp::Breaks::Consistent);
831 pp::cbox(&mut self.s, u)
834 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
835 try!(word(&mut self.s, w));
839 pub fn head(&mut self, w: &str) -> io::Result<()> {
840 // outer-box is consistent
841 try!(self.cbox(INDENT_UNIT));
842 // head-box is inconsistent
843 try!(self.ibox(w.len() + 1));
844 // keyword that starts the head
846 try!(self.word_nbsp(w));
851 pub fn bopen(&mut self) -> io::Result<()> {
852 try!(word(&mut self.s, "{"));
853 self.end() // close the head-box
856 pub fn bclose_(&mut self, span: codemap::Span,
857 indented: usize) -> io::Result<()> {
858 self.bclose_maybe_open(span, indented, true)
860 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
861 indented: usize, close_box: bool) -> io::Result<()> {
862 try!(self.maybe_print_comment(span.hi));
863 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
864 try!(word(&mut self.s, "}"));
866 try!(self.end()); // close the outer-box
870 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
871 self.bclose_(span, INDENT_UNIT)
874 pub fn in_cbox(&self) -> bool {
875 match self.boxes.last() {
876 Some(&last_box) => last_box == pp::Breaks::Consistent,
881 pub fn break_offset_if_not_bol(&mut self, n: usize,
882 off: isize) -> io::Result<()> {
884 break_offset(&mut self.s, n, off)
886 if off != 0 && self.s.last_token().is_hardbreak_tok() {
887 // We do something pretty sketchy here: tuck the nonzero
888 // offset-adjustment we were going to deposit along with the
889 // break into the previous hardbreak.
890 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
896 // Synthesizes a comment that was not textually present in the original source
898 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
899 try!(word(&mut self.s, "/*"));
900 try!(space(&mut self.s));
901 try!(word(&mut self.s, &text[..]));
902 try!(space(&mut self.s));
903 word(&mut self.s, "*/")
908 pub fn commasep_cmnt<T, F, G>(&mut self,
912 mut get_span: G) -> io::Result<()> where
913 F: FnMut(&mut State, &T) -> io::Result<()>,
914 G: FnMut(&T) -> codemap::Span,
916 try!(self.rbox(0, b));
917 let len = elts.len();
920 try!(self.maybe_print_comment(get_span(elt).hi));
924 try!(word(&mut self.s, ","));
925 try!(self.maybe_print_trailing_comment(get_span(elt),
926 Some(get_span(&elts[i]).hi)));
927 try!(self.space_if_not_bol());
933 pub fn commasep_exprs(&mut self, b: Breaks,
934 exprs: &[P<ast::Expr>]) -> io::Result<()> {
935 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
938 pub fn print_mod(&mut self, _mod: &ast::Mod,
939 attrs: &[ast::Attribute]) -> io::Result<()> {
940 try!(self.print_inner_attributes(attrs));
941 for item in &_mod.items {
942 try!(self.print_item(&**item));
947 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
948 attrs: &[ast::Attribute]) -> io::Result<()> {
949 try!(self.print_inner_attributes(attrs));
950 for item in &nmod.items {
951 try!(self.print_foreign_item(&**item));
956 pub fn print_opt_lifetime(&mut self,
957 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
958 if let Some(l) = *lifetime {
959 try!(self.print_lifetime(&l));
965 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
966 try!(self.maybe_print_comment(ty.span.lo));
969 ast::TyVec(ref ty) => {
970 try!(word(&mut self.s, "["));
971 try!(self.print_type(&**ty));
972 try!(word(&mut self.s, "]"));
974 ast::TyPtr(ref mt) => {
975 try!(word(&mut self.s, "*"));
977 ast::MutMutable => try!(self.word_nbsp("mut")),
978 ast::MutImmutable => try!(self.word_nbsp("const")),
980 try!(self.print_type(&*mt.ty));
982 ast::TyRptr(ref lifetime, ref mt) => {
983 try!(word(&mut self.s, "&"));
984 try!(self.print_opt_lifetime(lifetime));
985 try!(self.print_mt(mt));
987 ast::TyTup(ref elts) => {
989 try!(self.commasep(Inconsistent, &elts[..],
990 |s, ty| s.print_type(&**ty)));
992 try!(word(&mut self.s, ","));
996 ast::TyParen(ref typ) => {
998 try!(self.print_type(&**typ));
1001 ast::TyBareFn(ref f) => {
1002 let generics = ast::Generics {
1003 lifetimes: f.lifetimes.clone(),
1004 ty_params: OwnedSlice::empty(),
1005 where_clause: ast::WhereClause {
1006 id: ast::DUMMY_NODE_ID,
1007 predicates: Vec::new(),
1010 try!(self.print_ty_fn(f.abi,
1017 ast::TyPath(None, ref path) => {
1018 try!(self.print_path(path, false, 0));
1020 ast::TyPath(Some(ref qself), ref path) => {
1021 try!(self.print_qpath(path, qself, false))
1023 ast::TyObjectSum(ref ty, ref bounds) => {
1024 try!(self.print_type(&**ty));
1025 try!(self.print_bounds("+", &bounds[..]));
1027 ast::TyPolyTraitRef(ref bounds) => {
1028 try!(self.print_bounds("", &bounds[..]));
1030 ast::TyFixedLengthVec(ref ty, ref v) => {
1031 try!(word(&mut self.s, "["));
1032 try!(self.print_type(&**ty));
1033 try!(word(&mut self.s, "; "));
1034 try!(self.print_expr(&**v));
1035 try!(word(&mut self.s, "]"));
1037 ast::TyTypeof(ref e) => {
1038 try!(word(&mut self.s, "typeof("));
1039 try!(self.print_expr(&**e));
1040 try!(word(&mut self.s, ")"));
1043 try!(word(&mut self.s, "_"));
1045 ast::TyMac(ref m) => {
1046 try!(self.print_mac(m, token::Paren));
1052 pub fn print_foreign_item(&mut self,
1053 item: &ast::ForeignItem) -> io::Result<()> {
1054 try!(self.hardbreak_if_not_bol());
1055 try!(self.maybe_print_comment(item.span.lo));
1056 try!(self.print_outer_attributes(&item.attrs));
1058 ast::ForeignItemFn(ref decl, ref generics) => {
1059 try!(self.head(""));
1060 try!(self.print_fn(decl, ast::Unsafety::Normal,
1061 ast::Constness::NotConst,
1062 abi::Rust, Some(item.ident),
1063 generics, None, item.vis));
1064 try!(self.end()); // end head-ibox
1065 try!(word(&mut self.s, ";"));
1066 self.end() // end the outer fn box
1068 ast::ForeignItemStatic(ref t, m) => {
1069 try!(self.head(&visibility_qualified(item.vis,
1072 try!(self.word_space("mut"));
1074 try!(self.print_ident(item.ident));
1075 try!(self.word_space(":"));
1076 try!(self.print_type(&**t));
1077 try!(word(&mut self.s, ";"));
1078 try!(self.end()); // end the head-ibox
1079 self.end() // end the outer cbox
1084 fn print_associated_const(&mut self,
1087 default: Option<&ast::Expr>,
1088 vis: ast::Visibility)
1091 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1092 try!(self.word_space("const"));
1093 try!(self.print_ident(ident));
1094 try!(self.word_space(":"));
1095 try!(self.print_type(ty));
1096 if let Some(expr) = default {
1097 try!(space(&mut self.s));
1098 try!(self.word_space("="));
1099 try!(self.print_expr(expr));
1101 word(&mut self.s, ";")
1104 fn print_associated_type(&mut self,
1106 bounds: Option<&ast::TyParamBounds>,
1107 ty: Option<&ast::Ty>)
1109 try!(self.word_space("type"));
1110 try!(self.print_ident(ident));
1111 if let Some(bounds) = bounds {
1112 try!(self.print_bounds(":", bounds));
1114 if let Some(ty) = ty {
1115 try!(space(&mut self.s));
1116 try!(self.word_space("="));
1117 try!(self.print_type(ty));
1119 word(&mut self.s, ";")
1122 /// Pretty-print an item
1123 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1124 try!(self.hardbreak_if_not_bol());
1125 try!(self.maybe_print_comment(item.span.lo));
1126 try!(self.print_outer_attributes(&item.attrs));
1127 try!(self.ann.pre(self, NodeItem(item)));
1129 ast::ItemExternCrate(ref optional_path) => {
1130 try!(self.head(&visibility_qualified(item.vis,
1132 if let Some(p) = *optional_path {
1133 let val = p.as_str();
1134 if val.contains("-") {
1135 try!(self.print_string(&val, ast::CookedStr));
1137 try!(self.print_name(p));
1139 try!(space(&mut self.s));
1140 try!(word(&mut self.s, "as"));
1141 try!(space(&mut self.s));
1143 try!(self.print_ident(item.ident));
1144 try!(word(&mut self.s, ";"));
1145 try!(self.end()); // end inner head-block
1146 try!(self.end()); // end outer head-block
1148 ast::ItemUse(ref vp) => {
1149 try!(self.head(&visibility_qualified(item.vis,
1151 try!(self.print_view_path(&**vp));
1152 try!(word(&mut self.s, ";"));
1153 try!(self.end()); // end inner head-block
1154 try!(self.end()); // end outer head-block
1156 ast::ItemStatic(ref ty, m, ref expr) => {
1157 try!(self.head(&visibility_qualified(item.vis,
1159 if m == ast::MutMutable {
1160 try!(self.word_space("mut"));
1162 try!(self.print_ident(item.ident));
1163 try!(self.word_space(":"));
1164 try!(self.print_type(&**ty));
1165 try!(space(&mut self.s));
1166 try!(self.end()); // end the head-ibox
1168 try!(self.word_space("="));
1169 try!(self.print_expr(&**expr));
1170 try!(word(&mut self.s, ";"));
1171 try!(self.end()); // end the outer cbox
1173 ast::ItemConst(ref ty, ref expr) => {
1174 try!(self.head(&visibility_qualified(item.vis,
1176 try!(self.print_ident(item.ident));
1177 try!(self.word_space(":"));
1178 try!(self.print_type(&**ty));
1179 try!(space(&mut self.s));
1180 try!(self.end()); // end the head-ibox
1182 try!(self.word_space("="));
1183 try!(self.print_expr(&**expr));
1184 try!(word(&mut self.s, ";"));
1185 try!(self.end()); // end the outer cbox
1187 ast::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1188 try!(self.head(""));
1199 try!(word(&mut self.s, " "));
1200 try!(self.print_block_with_attrs(&**body, &item.attrs));
1202 ast::ItemMod(ref _mod) => {
1203 try!(self.head(&visibility_qualified(item.vis,
1205 try!(self.print_ident(item.ident));
1208 try!(self.print_mod(_mod, &item.attrs));
1209 try!(self.bclose(item.span));
1211 ast::ItemForeignMod(ref nmod) => {
1212 try!(self.head("extern"));
1213 try!(self.word_nbsp(&nmod.abi.to_string()));
1215 try!(self.print_foreign_mod(nmod, &item.attrs));
1216 try!(self.bclose(item.span));
1218 ast::ItemTy(ref ty, ref params) => {
1219 try!(self.ibox(INDENT_UNIT));
1221 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
1222 try!(self.print_ident(item.ident));
1223 try!(self.print_generics(params));
1224 try!(self.end()); // end the inner ibox
1226 try!(self.print_where_clause(¶ms.where_clause));
1227 try!(space(&mut self.s));
1228 try!(self.word_space("="));
1229 try!(self.print_type(&**ty));
1230 try!(word(&mut self.s, ";"));
1231 try!(self.end()); // end the outer ibox
1233 ast::ItemEnum(ref enum_definition, ref params) => {
1234 try!(self.print_enum_def(
1242 ast::ItemStruct(ref struct_def, ref generics) => {
1243 try!(self.head(&visibility_qualified(item.vis,"struct")));
1244 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1247 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
1248 try!(self.head(""));
1249 try!(self.print_visibility(item.vis));
1250 try!(self.print_unsafety(unsafety));
1251 try!(self.word_nbsp("impl"));
1252 try!(self.print_trait_ref(trait_ref));
1253 try!(space(&mut self.s));
1254 try!(self.word_space("for"));
1255 try!(self.word_space(".."));
1257 try!(self.bclose(item.span));
1259 ast::ItemImpl(unsafety,
1264 ref impl_items) => {
1265 try!(self.head(""));
1266 try!(self.print_visibility(item.vis));
1267 try!(self.print_unsafety(unsafety));
1268 try!(self.word_nbsp("impl"));
1270 if generics.is_parameterized() {
1271 try!(self.print_generics(generics));
1272 try!(space(&mut self.s));
1276 ast::ImplPolarity::Negative => {
1277 try!(word(&mut self.s, "!"));
1284 try!(self.print_trait_ref(t));
1285 try!(space(&mut self.s));
1286 try!(self.word_space("for"));
1291 try!(self.print_type(&**ty));
1292 try!(self.print_where_clause(&generics.where_clause));
1294 try!(space(&mut self.s));
1296 try!(self.print_inner_attributes(&item.attrs));
1297 for impl_item in impl_items {
1298 try!(self.print_impl_item(impl_item));
1300 try!(self.bclose(item.span));
1302 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
1303 try!(self.head(""));
1304 try!(self.print_visibility(item.vis));
1305 try!(self.print_unsafety(unsafety));
1306 try!(self.word_nbsp("trait"));
1307 try!(self.print_ident(item.ident));
1308 try!(self.print_generics(generics));
1309 let mut real_bounds = Vec::with_capacity(bounds.len());
1310 for b in bounds.iter() {
1311 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1312 try!(space(&mut self.s));
1313 try!(self.word_space("for ?"));
1314 try!(self.print_trait_ref(&ptr.trait_ref));
1316 real_bounds.push(b.clone());
1319 try!(self.print_bounds(":", &real_bounds[..]));
1320 try!(self.print_where_clause(&generics.where_clause));
1321 try!(word(&mut self.s, " "));
1323 for trait_item in trait_items {
1324 try!(self.print_trait_item(trait_item));
1326 try!(self.bclose(item.span));
1328 ast::ItemMac(codemap::Spanned { ref node, .. }) => {
1329 try!(self.print_visibility(item.vis));
1330 try!(self.print_path(&node.path, false, 0));
1331 try!(word(&mut self.s, "! "));
1332 try!(self.print_ident(item.ident));
1333 try!(self.cbox(INDENT_UNIT));
1335 try!(self.print_tts(&node.tts[..]));
1336 try!(self.pclose());
1337 try!(word(&mut self.s, ";"));
1341 self.ann.post(self, NodeItem(item))
1344 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1345 self.print_path(&t.path, false, 0)
1348 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1349 if !lifetimes.is_empty() {
1350 try!(word(&mut self.s, "for<"));
1351 let mut comma = false;
1352 for lifetime_def in lifetimes {
1354 try!(self.word_space(","))
1356 try!(self.print_lifetime_def(lifetime_def));
1359 try!(word(&mut self.s, ">"));
1364 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1365 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1366 self.print_trait_ref(&t.trait_ref)
1369 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1370 generics: &ast::Generics, ident: ast::Ident,
1371 span: codemap::Span,
1372 visibility: ast::Visibility) -> io::Result<()> {
1373 try!(self.head(&visibility_qualified(visibility, "enum")));
1374 try!(self.print_ident(ident));
1375 try!(self.print_generics(generics));
1376 try!(self.print_where_clause(&generics.where_clause));
1377 try!(space(&mut self.s));
1378 self.print_variants(&enum_definition.variants, span)
1381 pub fn print_variants(&mut self,
1382 variants: &[P<ast::Variant>],
1383 span: codemap::Span) -> io::Result<()> {
1386 try!(self.space_if_not_bol());
1387 try!(self.maybe_print_comment(v.span.lo));
1388 try!(self.print_outer_attributes(&v.node.attrs));
1389 try!(self.ibox(INDENT_UNIT));
1390 try!(self.print_variant(&**v));
1391 try!(word(&mut self.s, ","));
1393 try!(self.maybe_print_trailing_comment(v.span, None));
1398 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1400 ast::Public => self.word_nbsp("pub"),
1401 ast::Inherited => Ok(())
1405 pub fn print_struct(&mut self,
1406 struct_def: &ast::VariantData,
1407 generics: &ast::Generics,
1409 span: codemap::Span,
1410 print_finalizer: bool) -> io::Result<()> {
1411 try!(self.print_ident(ident));
1412 try!(self.print_generics(generics));
1413 if !struct_def.is_struct() {
1414 if struct_def.is_tuple() {
1417 Inconsistent, struct_def.fields(),
1419 match field.node.kind {
1420 ast::NamedField(..) => panic!("unexpected named field"),
1421 ast::UnnamedField(vis) => {
1422 try!(s.print_visibility(vis));
1423 try!(s.maybe_print_comment(field.span.lo));
1424 s.print_type(&*field.node.ty)
1429 try!(self.pclose());
1431 try!(self.print_where_clause(&generics.where_clause));
1432 if print_finalizer {
1433 try!(word(&mut self.s, ";"));
1436 self.end() // close the outer-box
1438 try!(self.print_where_clause(&generics.where_clause));
1441 try!(self.hardbreak_if_not_bol());
1443 for field in struct_def.fields() {
1444 match field.node.kind {
1445 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1446 ast::NamedField(ident, visibility) => {
1447 try!(self.hardbreak_if_not_bol());
1448 try!(self.maybe_print_comment(field.span.lo));
1449 try!(self.print_outer_attributes(&field.node.attrs));
1450 try!(self.print_visibility(visibility));
1451 try!(self.print_ident(ident));
1452 try!(self.word_nbsp(":"));
1453 try!(self.print_type(&*field.node.ty));
1454 try!(word(&mut self.s, ","));
1463 /// This doesn't deserve to be called "pretty" printing, but it should be
1464 /// meaning-preserving. A quick hack that might help would be to look at the
1465 /// spans embedded in the TTs to decide where to put spaces and newlines.
1466 /// But it'd be better to parse these according to the grammar of the
1467 /// appropriate macro, transcribe back into the grammar we just parsed from,
1468 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1469 /// expression arguments as expressions). It can be done! I think.
1470 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1472 TokenTree::Token(_, ref tk) => {
1473 try!(word(&mut self.s, &token_to_string(tk)));
1475 parse::token::DocComment(..) => {
1476 hardbreak(&mut self.s)
1481 TokenTree::Delimited(_, ref delimed) => {
1482 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1483 try!(space(&mut self.s));
1484 try!(self.print_tts(&delimed.tts));
1485 try!(space(&mut self.s));
1486 word(&mut self.s, &token_to_string(&delimed.close_token()))
1488 TokenTree::Sequence(_, ref seq) => {
1489 try!(word(&mut self.s, "$("));
1490 for tt_elt in &seq.tts {
1491 try!(self.print_tt(tt_elt));
1493 try!(word(&mut self.s, ")"));
1494 match seq.separator {
1496 try!(word(&mut self.s, &token_to_string(tk)));
1501 ast::ZeroOrMore => word(&mut self.s, "*"),
1502 ast::OneOrMore => word(&mut self.s, "+"),
1508 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1510 let mut suppress_space = false;
1511 for (i, tt) in tts.iter().enumerate() {
1512 if i != 0 && !suppress_space {
1513 try!(space(&mut self.s));
1515 try!(self.print_tt(tt));
1516 // There should be no space between the module name and the following `::` in paths,
1517 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1518 suppress_space = match *tt {
1519 TokenTree::Token(_, token::Ident(_, token::ModName)) |
1520 TokenTree::Token(_, token::MatchNt(_, _, _, token::ModName)) |
1521 TokenTree::Token(_, token::SubstNt(_, token::ModName)) => true,
1528 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1529 try!(self.head(""));
1530 let generics = ast::Generics::default();
1531 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1532 match v.node.disr_expr {
1534 try!(space(&mut self.s));
1535 try!(self.word_space("="));
1536 self.print_expr(&**d)
1542 pub fn print_method_sig(&mut self,
1545 vis: ast::Visibility)
1547 self.print_fn(&m.decl,
1553 Some(&m.explicit_self.node),
1557 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1559 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1560 try!(self.hardbreak_if_not_bol());
1561 try!(self.maybe_print_comment(ti.span.lo));
1562 try!(self.print_outer_attributes(&ti.attrs));
1564 ast::ConstTraitItem(ref ty, ref default) => {
1565 try!(self.print_associated_const(ti.ident, &ty,
1566 default.as_ref().map(|expr| &**expr),
1569 ast::MethodTraitItem(ref sig, ref body) => {
1571 try!(self.head(""));
1573 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1574 if let Some(ref body) = *body {
1576 try!(self.print_block_with_attrs(body, &ti.attrs));
1578 try!(word(&mut self.s, ";"));
1581 ast::TypeTraitItem(ref bounds, ref default) => {
1582 try!(self.print_associated_type(ti.ident, Some(bounds),
1583 default.as_ref().map(|ty| &**ty)));
1586 self.ann.post(self, NodeSubItem(ti.id))
1589 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1590 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1591 try!(self.hardbreak_if_not_bol());
1592 try!(self.maybe_print_comment(ii.span.lo));
1593 try!(self.print_outer_attributes(&ii.attrs));
1595 ast::ImplItemKind::Const(ref ty, ref expr) => {
1596 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1598 ast::ImplItemKind::Method(ref sig, ref body) => {
1599 try!(self.head(""));
1600 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1602 try!(self.print_block_with_attrs(body, &ii.attrs));
1604 ast::ImplItemKind::Type(ref ty) => {
1605 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1607 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1608 // code copied from ItemMac:
1609 try!(self.print_path(&node.path, false, 0));
1610 try!(word(&mut self.s, "! "));
1611 try!(self.cbox(INDENT_UNIT));
1613 try!(self.print_tts(&node.tts[..]));
1614 try!(self.pclose());
1615 try!(word(&mut self.s, ";"));
1619 self.ann.post(self, NodeSubItem(ii.id))
1622 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1623 try!(self.maybe_print_comment(st.span.lo));
1625 ast::StmtDecl(ref decl, _) => {
1626 try!(self.print_decl(&**decl));
1628 ast::StmtExpr(ref expr, _) => {
1629 try!(self.space_if_not_bol());
1630 try!(self.print_expr_outer_attr_style(&**expr, false));
1632 ast::StmtSemi(ref expr, _) => {
1633 try!(self.space_if_not_bol());
1634 try!(self.print_expr_outer_attr_style(&**expr, false));
1635 try!(word(&mut self.s, ";"));
1637 ast::StmtMac(ref mac, style, ref attrs) => {
1638 try!(self.space_if_not_bol());
1639 try!(self.print_outer_attributes(attrs.as_attr_slice()));
1640 let delim = match style {
1641 ast::MacStmtWithBraces => token::Brace,
1644 try!(self.print_mac(&**mac, delim));
1646 ast::MacStmtWithBraces => {}
1647 _ => try!(word(&mut self.s, ";")),
1651 if parse::classify::stmt_ends_with_semi(&st.node) {
1652 try!(word(&mut self.s, ";"));
1654 self.maybe_print_trailing_comment(st.span, None)
1657 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1658 self.print_block_with_attrs(blk, &[])
1661 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1662 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1665 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1666 attrs: &[ast::Attribute])
1668 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1671 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1672 indented: usize) -> io::Result<()> {
1673 self.print_block_maybe_unclosed(blk, indented, &[], false)
1676 pub fn print_block_with_attrs(&mut self,
1678 attrs: &[ast::Attribute]) -> io::Result<()> {
1679 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1682 pub fn print_block_maybe_unclosed(&mut self,
1685 attrs: &[ast::Attribute],
1686 close_box: bool) -> io::Result<()> {
1688 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1689 ast::DefaultBlock => ()
1691 try!(self.maybe_print_comment(blk.span.lo));
1692 try!(self.ann.pre(self, NodeBlock(blk)));
1695 try!(self.print_inner_attributes(attrs));
1697 for st in &blk.stmts {
1698 try!(self.print_stmt(&**st));
1702 try!(self.space_if_not_bol());
1703 try!(self.print_expr_outer_attr_style(&**expr, false));
1704 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1708 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1709 self.ann.post(self, NodeBlock(blk))
1712 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1716 // "another else-if"
1717 ast::ExprIf(ref i, ref then, ref e) => {
1718 try!(self.cbox(INDENT_UNIT - 1));
1720 try!(word(&mut self.s, " else if "));
1721 try!(self.print_expr(&**i));
1722 try!(space(&mut self.s));
1723 try!(self.print_block(&**then));
1724 self.print_else(e.as_ref().map(|e| &**e))
1726 // "another else-if-let"
1727 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1728 try!(self.cbox(INDENT_UNIT - 1));
1730 try!(word(&mut self.s, " else if let "));
1731 try!(self.print_pat(&**pat));
1732 try!(space(&mut self.s));
1733 try!(self.word_space("="));
1734 try!(self.print_expr(&**expr));
1735 try!(space(&mut self.s));
1736 try!(self.print_block(&**then));
1737 self.print_else(e.as_ref().map(|e| &**e))
1740 ast::ExprBlock(ref b) => {
1741 try!(self.cbox(INDENT_UNIT - 1));
1743 try!(word(&mut self.s, " else "));
1744 self.print_block(&**b)
1746 // BLEAH, constraints would be great here
1748 panic!("print_if saw if with weird alternative");
1756 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1757 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1758 try!(self.head("if"));
1759 try!(self.print_expr(test));
1760 try!(space(&mut self.s));
1761 try!(self.print_block(blk));
1762 self.print_else(elseopt)
1765 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1766 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1767 try!(self.head("if let"));
1768 try!(self.print_pat(pat));
1769 try!(space(&mut self.s));
1770 try!(self.word_space("="));
1771 try!(self.print_expr(expr));
1772 try!(space(&mut self.s));
1773 try!(self.print_block(blk));
1774 self.print_else(elseopt)
1777 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1779 try!(self.print_path(&m.node.path, false, 0));
1780 try!(word(&mut self.s, "!"));
1782 token::Paren => try!(self.popen()),
1783 token::Bracket => try!(word(&mut self.s, "[")),
1785 // head-ibox, will be closed by bopen()
1787 // Don't ask me why the regular bopen() does
1788 // more then just opening a brace...
1792 try!(self.print_tts(&m.node.tts));
1794 token::Paren => self.pclose(),
1795 token::Bracket => word(&mut self.s, "]"),
1796 token::Brace => self.bclose(m.span),
1801 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1803 try!(self.commasep_exprs(Inconsistent, args));
1807 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1808 binop: ast::BinOp) -> bool {
1809 match sub_expr.node {
1810 ast::ExprBinary(ref sub_op, _, _) => {
1811 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1812 AssocOp::from_ast_binop(binop.node).precedence() {
1822 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1823 let needs_par = needs_parentheses(expr);
1827 try!(self.print_expr(expr));
1829 try!(self.pclose());
1834 fn print_expr_in_place(&mut self,
1836 expr: &ast::Expr) -> io::Result<()> {
1837 try!(self.print_expr_maybe_paren(place));
1838 try!(space(&mut self.s));
1839 try!(self.word_space("<-"));
1840 self.print_expr_maybe_paren(expr)
1843 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1844 attrs: &[Attribute]) -> io::Result<()> {
1845 try!(self.ibox(INDENT_UNIT));
1846 try!(word(&mut self.s, "["));
1847 try!(self.print_inner_attributes_inline(attrs));
1848 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1849 try!(word(&mut self.s, "]"));
1853 fn print_expr_repeat(&mut self,
1854 element: &ast::Expr,
1856 attrs: &[Attribute]) -> io::Result<()> {
1857 try!(self.ibox(INDENT_UNIT));
1858 try!(word(&mut self.s, "["));
1859 try!(self.print_inner_attributes_inline(attrs));
1860 try!(self.print_expr(element));
1861 try!(self.word_space(";"));
1862 try!(self.print_expr(count));
1863 try!(word(&mut self.s, "]"));
1867 fn print_expr_struct(&mut self,
1869 fields: &[ast::Field],
1870 wth: &Option<P<ast::Expr>>,
1871 attrs: &[Attribute]) -> io::Result<()> {
1872 try!(self.print_path(path, true, 0));
1873 try!(word(&mut self.s, "{"));
1874 try!(self.print_inner_attributes_inline(attrs));
1875 try!(self.commasep_cmnt(
1879 try!(s.ibox(INDENT_UNIT));
1880 try!(s.print_ident(field.ident.node));
1881 try!(s.word_space(":"));
1882 try!(s.print_expr(&*field.expr));
1888 try!(self.ibox(INDENT_UNIT));
1889 if !fields.is_empty() {
1890 try!(word(&mut self.s, ","));
1891 try!(space(&mut self.s));
1893 try!(word(&mut self.s, ".."));
1894 try!(self.print_expr(&**expr));
1897 _ => if !fields.is_empty() {
1898 try!(word(&mut self.s, ","))
1901 try!(word(&mut self.s, "}"));
1905 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1906 attrs: &[Attribute]) -> io::Result<()> {
1908 try!(self.print_inner_attributes_inline(attrs));
1909 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1910 if exprs.len() == 1 {
1911 try!(word(&mut self.s, ","));
1916 fn print_expr_call(&mut self,
1918 args: &[P<ast::Expr>]) -> io::Result<()> {
1919 try!(self.print_expr_maybe_paren(func));
1920 self.print_call_post(args)
1923 fn print_expr_method_call(&mut self,
1924 ident: ast::SpannedIdent,
1926 args: &[P<ast::Expr>]) -> io::Result<()> {
1927 let base_args = &args[1..];
1928 try!(self.print_expr(&*args[0]));
1929 try!(word(&mut self.s, "."));
1930 try!(self.print_ident(ident.node));
1931 if !tys.is_empty() {
1932 try!(word(&mut self.s, "::<"));
1933 try!(self.commasep(Inconsistent, tys,
1934 |s, ty| s.print_type(&**ty)));
1935 try!(word(&mut self.s, ">"));
1937 self.print_call_post(base_args)
1940 fn print_expr_binary(&mut self,
1943 rhs: &ast::Expr) -> io::Result<()> {
1944 if self.check_expr_bin_needs_paren(lhs, op) {
1945 try!(self.print_expr_maybe_paren(lhs));
1947 try!(self.print_expr(lhs));
1949 try!(space(&mut self.s));
1950 try!(self.word_space(op.node.to_string()));
1951 if self.check_expr_bin_needs_paren(rhs, op) {
1952 self.print_expr_maybe_paren(rhs)
1954 self.print_expr(rhs)
1958 fn print_expr_unary(&mut self,
1960 expr: &ast::Expr) -> io::Result<()> {
1961 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1962 self.print_expr_maybe_paren(expr)
1965 fn print_expr_addr_of(&mut self,
1966 mutability: ast::Mutability,
1967 expr: &ast::Expr) -> io::Result<()> {
1968 try!(word(&mut self.s, "&"));
1969 try!(self.print_mutability(mutability));
1970 self.print_expr_maybe_paren(expr)
1973 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1974 self.print_expr_outer_attr_style(expr, true)
1977 fn print_expr_outer_attr_style(&mut self,
1979 is_inline: bool) -> io::Result<()> {
1980 try!(self.maybe_print_comment(expr.span.lo));
1982 let attrs = expr.attrs.as_attr_slice();
1984 try!(self.print_outer_attributes_inline(attrs));
1986 try!(self.print_outer_attributes(attrs));
1989 try!(self.ibox(INDENT_UNIT));
1990 try!(self.ann.pre(self, NodeExpr(expr)));
1992 ast::ExprBox(ref expr) => {
1993 try!(self.word_space("box"));
1994 try!(self.print_expr(expr));
1996 ast::ExprInPlace(ref place, ref expr) => {
1997 try!(self.print_expr_in_place(place, expr));
1999 ast::ExprVec(ref exprs) => {
2000 try!(self.print_expr_vec(&exprs[..], attrs));
2002 ast::ExprRepeat(ref element, ref count) => {
2003 try!(self.print_expr_repeat(&**element, &**count, attrs));
2005 ast::ExprStruct(ref path, ref fields, ref wth) => {
2006 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
2008 ast::ExprTup(ref exprs) => {
2009 try!(self.print_expr_tup(&exprs[..], attrs));
2011 ast::ExprCall(ref func, ref args) => {
2012 try!(self.print_expr_call(&**func, &args[..]));
2014 ast::ExprMethodCall(ident, ref tys, ref args) => {
2015 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
2017 ast::ExprBinary(op, ref lhs, ref rhs) => {
2018 try!(self.print_expr_binary(op, &**lhs, &**rhs));
2020 ast::ExprUnary(op, ref expr) => {
2021 try!(self.print_expr_unary(op, &**expr));
2023 ast::ExprAddrOf(m, ref expr) => {
2024 try!(self.print_expr_addr_of(m, &**expr));
2026 ast::ExprLit(ref lit) => {
2027 try!(self.print_literal(&**lit));
2029 ast::ExprCast(ref expr, ref ty) => {
2030 if let ast::ExprCast(..) = expr.node {
2031 try!(self.print_expr(&**expr));
2033 try!(self.print_expr_maybe_paren(&**expr));
2035 try!(space(&mut self.s));
2036 try!(self.word_space("as"));
2037 try!(self.print_type(&**ty));
2039 ast::ExprIf(ref test, ref blk, ref elseopt) => {
2040 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
2042 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2043 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
2045 ast::ExprWhile(ref test, ref blk, opt_ident) => {
2046 if let Some(ident) = opt_ident {
2047 try!(self.print_ident(ident));
2048 try!(self.word_space(":"));
2050 try!(self.head("while"));
2051 try!(self.print_expr(&**test));
2052 try!(space(&mut self.s));
2053 try!(self.print_block_with_attrs(&**blk, attrs));
2055 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2056 if let Some(ident) = opt_ident {
2057 try!(self.print_ident(ident));
2058 try!(self.word_space(":"));
2060 try!(self.head("while let"));
2061 try!(self.print_pat(&**pat));
2062 try!(space(&mut self.s));
2063 try!(self.word_space("="));
2064 try!(self.print_expr(&**expr));
2065 try!(space(&mut self.s));
2066 try!(self.print_block_with_attrs(&**blk, attrs));
2068 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2069 if let Some(ident) = opt_ident {
2070 try!(self.print_ident(ident));
2071 try!(self.word_space(":"));
2073 try!(self.head("for"));
2074 try!(self.print_pat(&**pat));
2075 try!(space(&mut self.s));
2076 try!(self.word_space("in"));
2077 try!(self.print_expr(&**iter));
2078 try!(space(&mut self.s));
2079 try!(self.print_block_with_attrs(&**blk, attrs));
2081 ast::ExprLoop(ref blk, opt_ident) => {
2082 if let Some(ident) = opt_ident {
2083 try!(self.print_ident(ident));
2084 try!(self.word_space(":"));
2086 try!(self.head("loop"));
2087 try!(space(&mut self.s));
2088 try!(self.print_block_with_attrs(&**blk, attrs));
2090 ast::ExprMatch(ref expr, ref arms) => {
2091 try!(self.cbox(INDENT_UNIT));
2093 try!(self.word_nbsp("match"));
2094 try!(self.print_expr(&**expr));
2095 try!(space(&mut self.s));
2097 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2099 try!(self.print_arm(arm));
2101 try!(self.bclose_(expr.span, INDENT_UNIT));
2103 ast::ExprClosure(capture_clause, ref decl, ref body) => {
2104 try!(self.print_capture_clause(capture_clause));
2106 try!(self.print_fn_block_args(&**decl));
2107 try!(space(&mut self.s));
2109 let default_return = match decl.output {
2110 ast::DefaultReturn(..) => true,
2114 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2115 try!(self.print_block_unclosed(&**body));
2117 // we extract the block, so as not to create another set of boxes
2118 let i_expr = body.expr.as_ref().unwrap();
2120 ast::ExprBlock(ref blk) => {
2121 try!(self.print_block_unclosed_with_attrs(
2123 i_expr.attrs.as_attr_slice()));
2126 // this is a bare expression
2127 try!(self.print_expr(&**i_expr));
2128 try!(self.end()); // need to close a box
2132 // a box will be closed by print_expr, but we didn't want an overall
2133 // wrapper so we closed the corresponding opening. so create an
2134 // empty box to satisfy the close.
2137 ast::ExprBlock(ref blk) => {
2138 // containing cbox, will be closed by print-block at }
2139 try!(self.cbox(INDENT_UNIT));
2140 // head-box, will be closed by print-block after {
2142 try!(self.print_block_with_attrs(&**blk, attrs));
2144 ast::ExprAssign(ref lhs, ref rhs) => {
2145 try!(self.print_expr(&**lhs));
2146 try!(space(&mut self.s));
2147 try!(self.word_space("="));
2148 try!(self.print_expr(&**rhs));
2150 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
2151 try!(self.print_expr(&**lhs));
2152 try!(space(&mut self.s));
2153 try!(word(&mut self.s, op.node.to_string()));
2154 try!(self.word_space("="));
2155 try!(self.print_expr(&**rhs));
2157 ast::ExprField(ref expr, id) => {
2158 try!(self.print_expr(&**expr));
2159 try!(word(&mut self.s, "."));
2160 try!(self.print_ident(id.node));
2162 ast::ExprTupField(ref expr, id) => {
2163 try!(self.print_expr(&**expr));
2164 try!(word(&mut self.s, "."));
2165 try!(self.print_usize(id.node));
2167 ast::ExprIndex(ref expr, ref index) => {
2168 try!(self.print_expr(&**expr));
2169 try!(word(&mut self.s, "["));
2170 try!(self.print_expr(&**index));
2171 try!(word(&mut self.s, "]"));
2173 ast::ExprRange(ref start, ref end) => {
2174 if let &Some(ref e) = start {
2175 try!(self.print_expr(&**e));
2177 try!(word(&mut self.s, ".."));
2178 if let &Some(ref e) = end {
2179 try!(self.print_expr(&**e));
2182 ast::ExprPath(None, ref path) => {
2183 try!(self.print_path(path, true, 0))
2185 ast::ExprPath(Some(ref qself), ref path) => {
2186 try!(self.print_qpath(path, qself, true))
2188 ast::ExprBreak(opt_ident) => {
2189 try!(word(&mut self.s, "break"));
2190 try!(space(&mut self.s));
2191 if let Some(ident) = opt_ident {
2192 try!(self.print_ident(ident.node));
2193 try!(space(&mut self.s));
2196 ast::ExprAgain(opt_ident) => {
2197 try!(word(&mut self.s, "continue"));
2198 try!(space(&mut self.s));
2199 if let Some(ident) = opt_ident {
2200 try!(self.print_ident(ident.node));
2201 try!(space(&mut self.s))
2204 ast::ExprRet(ref result) => {
2205 try!(word(&mut self.s, "return"));
2208 try!(word(&mut self.s, " "));
2209 try!(self.print_expr(&**expr));
2214 ast::ExprInlineAsm(ref a) => {
2215 try!(word(&mut self.s, "asm!"));
2217 try!(self.print_string(&a.asm, a.asm_str_style));
2218 try!(self.word_space(":"));
2220 try!(self.commasep(Inconsistent, &a.outputs,
2222 match out.constraint.slice_shift_char() {
2223 Some(('=', operand)) if out.is_rw => {
2224 try!(s.print_string(&format!("+{}", operand),
2227 _ => try!(s.print_string(&out.constraint, ast::CookedStr))
2230 try!(s.print_expr(&*out.expr));
2234 try!(space(&mut self.s));
2235 try!(self.word_space(":"));
2237 try!(self.commasep(Inconsistent, &a.inputs,
2238 |s, &(ref co, ref o)| {
2239 try!(s.print_string(&co, ast::CookedStr));
2241 try!(s.print_expr(&**o));
2245 try!(space(&mut self.s));
2246 try!(self.word_space(":"));
2248 try!(self.commasep(Inconsistent, &a.clobbers,
2250 try!(s.print_string(&co, ast::CookedStr));
2254 let mut options = vec!();
2256 options.push("volatile");
2259 options.push("alignstack");
2261 if a.dialect == ast::AsmDialect::Intel {
2262 options.push("intel");
2265 if !options.is_empty() {
2266 try!(space(&mut self.s));
2267 try!(self.word_space(":"));
2268 try!(self.commasep(Inconsistent, &*options,
2270 try!(s.print_string(co, ast::CookedStr));
2275 try!(self.pclose());
2277 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
2278 ast::ExprParen(ref e) => {
2280 try!(self.print_inner_attributes_inline(attrs));
2281 try!(self.print_expr(&**e));
2282 try!(self.pclose());
2285 try!(self.ann.post(self, NodeExpr(expr)));
2289 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2290 try!(self.print_pat(&*loc.pat));
2291 if let Some(ref ty) = loc.ty {
2292 try!(self.word_space(":"));
2293 try!(self.print_type(&**ty));
2298 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2299 try!(self.maybe_print_comment(decl.span.lo));
2301 ast::DeclLocal(ref loc) => {
2302 try!(self.print_outer_attributes(loc.attrs.as_attr_slice()));
2303 try!(self.space_if_not_bol());
2304 try!(self.ibox(INDENT_UNIT));
2305 try!(self.word_nbsp("let"));
2307 try!(self.ibox(INDENT_UNIT));
2308 try!(self.print_local_decl(&**loc));
2310 if let Some(ref init) = loc.init {
2312 try!(self.word_space("="));
2313 try!(self.print_expr(&**init));
2317 ast::DeclItem(ref item) => self.print_item(&**item)
2321 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2322 try!(word(&mut self.s, &ident.name.as_str()));
2323 self.ann.post(self, NodeIdent(&ident))
2326 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2327 word(&mut self.s, &i.to_string())
2330 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2331 try!(word(&mut self.s, &name.as_str()));
2332 self.ann.post(self, NodeName(&name))
2335 pub fn print_for_decl(&mut self, loc: &ast::Local,
2336 coll: &ast::Expr) -> io::Result<()> {
2337 try!(self.print_local_decl(loc));
2338 try!(space(&mut self.s));
2339 try!(self.word_space("in"));
2340 self.print_expr(coll)
2343 fn print_path(&mut self,
2345 colons_before_params: bool,
2349 try!(self.maybe_print_comment(path.span.lo));
2351 let mut first = !path.global;
2352 for segment in &path.segments[..path.segments.len()-depth] {
2356 try!(word(&mut self.s, "::"))
2359 try!(self.print_ident(segment.identifier));
2361 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2367 fn print_qpath(&mut self,
2370 colons_before_params: bool)
2373 try!(word(&mut self.s, "<"));
2374 try!(self.print_type(&qself.ty));
2375 if qself.position > 0 {
2376 try!(space(&mut self.s));
2377 try!(self.word_space("as"));
2378 let depth = path.segments.len() - qself.position;
2379 try!(self.print_path(&path, false, depth));
2381 try!(word(&mut self.s, ">"));
2382 try!(word(&mut self.s, "::"));
2383 let item_segment = path.segments.last().unwrap();
2384 try!(self.print_ident(item_segment.identifier));
2385 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2388 fn print_path_parameters(&mut self,
2389 parameters: &ast::PathParameters,
2390 colons_before_params: bool)
2393 if parameters.is_empty() {
2397 if colons_before_params {
2398 try!(word(&mut self.s, "::"))
2402 ast::AngleBracketedParameters(ref data) => {
2403 try!(word(&mut self.s, "<"));
2405 let mut comma = false;
2406 for lifetime in &data.lifetimes {
2408 try!(self.word_space(","))
2410 try!(self.print_lifetime(lifetime));
2414 if !data.types.is_empty() {
2416 try!(self.word_space(","))
2421 |s, ty| s.print_type(&**ty)));
2425 for binding in data.bindings.iter() {
2427 try!(self.word_space(","))
2429 try!(self.print_ident(binding.ident));
2430 try!(space(&mut self.s));
2431 try!(self.word_space("="));
2432 try!(self.print_type(&*binding.ty));
2436 try!(word(&mut self.s, ">"))
2439 ast::ParenthesizedParameters(ref data) => {
2440 try!(word(&mut self.s, "("));
2444 |s, ty| s.print_type(&**ty)));
2445 try!(word(&mut self.s, ")"));
2450 try!(self.space_if_not_bol());
2451 try!(self.word_space("->"));
2452 try!(self.print_type(&**ty));
2461 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2462 try!(self.maybe_print_comment(pat.span.lo));
2463 try!(self.ann.pre(self, NodePat(pat)));
2464 /* Pat isn't normalized, but the beauty of it
2465 is that it doesn't matter */
2467 ast::PatWild => try!(word(&mut self.s, "_")),
2468 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2469 match binding_mode {
2470 ast::BindByRef(mutbl) => {
2471 try!(self.word_nbsp("ref"));
2472 try!(self.print_mutability(mutbl));
2474 ast::BindByValue(ast::MutImmutable) => {}
2475 ast::BindByValue(ast::MutMutable) => {
2476 try!(self.word_nbsp("mut"));
2479 try!(self.print_ident(path1.node));
2482 try!(word(&mut self.s, "@"));
2483 try!(self.print_pat(&**p));
2488 ast::PatEnum(ref path, ref args_) => {
2489 try!(self.print_path(path, true, 0));
2491 None => try!(word(&mut self.s, "(..)")),
2493 if !args.is_empty() {
2495 try!(self.commasep(Inconsistent, &args[..],
2496 |s, p| s.print_pat(&**p)));
2497 try!(self.pclose());
2502 ast::PatQPath(ref qself, ref path) => {
2503 try!(self.print_qpath(path, qself, false));
2505 ast::PatStruct(ref path, ref fields, etc) => {
2506 try!(self.print_path(path, true, 0));
2508 try!(self.word_space("{"));
2509 try!(self.commasep_cmnt(
2510 Consistent, &fields[..],
2512 try!(s.cbox(INDENT_UNIT));
2513 if !f.node.is_shorthand {
2514 try!(s.print_ident(f.node.ident));
2515 try!(s.word_nbsp(":"));
2517 try!(s.print_pat(&*f.node.pat));
2520 |f| f.node.pat.span));
2522 if !fields.is_empty() { try!(self.word_space(",")); }
2523 try!(word(&mut self.s, ".."));
2525 try!(space(&mut self.s));
2526 try!(word(&mut self.s, "}"));
2528 ast::PatTup(ref elts) => {
2530 try!(self.commasep(Inconsistent,
2532 |s, p| s.print_pat(&**p)));
2533 if elts.len() == 1 {
2534 try!(word(&mut self.s, ","));
2536 try!(self.pclose());
2538 ast::PatBox(ref inner) => {
2539 try!(word(&mut self.s, "box "));
2540 try!(self.print_pat(&**inner));
2542 ast::PatRegion(ref inner, mutbl) => {
2543 try!(word(&mut self.s, "&"));
2544 if mutbl == ast::MutMutable {
2545 try!(word(&mut self.s, "mut "));
2547 try!(self.print_pat(&**inner));
2549 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2550 ast::PatRange(ref begin, ref end) => {
2551 try!(self.print_expr(&**begin));
2552 try!(space(&mut self.s));
2553 try!(word(&mut self.s, "..."));
2554 try!(self.print_expr(&**end));
2556 ast::PatVec(ref before, ref slice, ref after) => {
2557 try!(word(&mut self.s, "["));
2558 try!(self.commasep(Inconsistent,
2560 |s, p| s.print_pat(&**p)));
2561 if let Some(ref p) = *slice {
2562 if !before.is_empty() { try!(self.word_space(",")); }
2563 if p.node != ast::PatWild {
2564 try!(self.print_pat(&**p));
2566 try!(word(&mut self.s, ".."));
2567 if !after.is_empty() { try!(self.word_space(",")); }
2569 try!(self.commasep(Inconsistent,
2571 |s, p| s.print_pat(&**p)));
2572 try!(word(&mut self.s, "]"));
2574 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2576 self.ann.post(self, NodePat(pat))
2579 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2580 // I have no idea why this check is necessary, but here it
2582 if arm.attrs.is_empty() {
2583 try!(space(&mut self.s));
2585 try!(self.cbox(INDENT_UNIT));
2587 try!(self.print_outer_attributes(&arm.attrs));
2588 let mut first = true;
2589 for p in &arm.pats {
2593 try!(space(&mut self.s));
2594 try!(self.word_space("|"));
2596 try!(self.print_pat(&**p));
2598 try!(space(&mut self.s));
2599 if let Some(ref e) = arm.guard {
2600 try!(self.word_space("if"));
2601 try!(self.print_expr(&**e));
2602 try!(space(&mut self.s));
2604 try!(self.word_space("=>"));
2606 match arm.body.node {
2607 ast::ExprBlock(ref blk) => {
2608 // the block will close the pattern's ibox
2609 try!(self.print_block_unclosed_indent(&**blk, INDENT_UNIT));
2611 // If it is a user-provided unsafe block, print a comma after it
2612 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2613 try!(word(&mut self.s, ","));
2617 try!(self.end()); // close the ibox for the pattern
2618 try!(self.print_expr(&*arm.body));
2619 try!(word(&mut self.s, ","));
2622 self.end() // close enclosing cbox
2625 // Returns whether it printed anything
2626 fn print_explicit_self(&mut self,
2627 explicit_self: &ast::ExplicitSelf_,
2628 mutbl: ast::Mutability) -> io::Result<bool> {
2629 try!(self.print_mutability(mutbl));
2630 match *explicit_self {
2631 ast::SelfStatic => { return Ok(false); }
2632 ast::SelfValue(_) => {
2633 try!(word(&mut self.s, "self"));
2635 ast::SelfRegion(ref lt, m, _) => {
2636 try!(word(&mut self.s, "&"));
2637 try!(self.print_opt_lifetime(lt));
2638 try!(self.print_mutability(m));
2639 try!(word(&mut self.s, "self"));
2641 ast::SelfExplicit(ref typ, _) => {
2642 try!(word(&mut self.s, "self"));
2643 try!(self.word_space(":"));
2644 try!(self.print_type(&**typ));
2650 pub fn print_fn(&mut self,
2652 unsafety: ast::Unsafety,
2653 constness: ast::Constness,
2655 name: Option<ast::Ident>,
2656 generics: &ast::Generics,
2657 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2658 vis: ast::Visibility) -> io::Result<()> {
2659 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2661 if let Some(name) = name {
2663 try!(self.print_ident(name));
2665 try!(self.print_generics(generics));
2666 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2667 self.print_where_clause(&generics.where_clause)
2670 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2671 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2673 // It is unfortunate to duplicate the commasep logic, but we want the
2674 // self type and the args all in the same box.
2675 try!(self.rbox(0, Inconsistent));
2676 let mut first = true;
2677 if let Some(explicit_self) = opt_explicit_self {
2678 let m = match *explicit_self {
2679 ast::SelfStatic => ast::MutImmutable,
2680 _ => match decl.inputs[0].pat.node {
2681 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2682 _ => ast::MutImmutable
2685 first = !try!(self.print_explicit_self(explicit_self, m));
2688 // HACK(eddyb) ignore the separately printed self argument.
2689 let args = if first {
2696 if first { first = false; } else { try!(self.word_space(",")); }
2697 try!(self.print_arg(arg));
2703 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2704 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2707 try!(self.print_fn_args(decl, opt_explicit_self));
2709 try!(word(&mut self.s, ", ..."));
2711 try!(self.pclose());
2713 self.print_fn_output(decl)
2716 pub fn print_fn_block_args(
2720 try!(word(&mut self.s, "|"));
2721 try!(self.print_fn_args(decl, None));
2722 try!(word(&mut self.s, "|"));
2724 if let ast::DefaultReturn(..) = decl.output {
2728 try!(self.space_if_not_bol());
2729 try!(self.word_space("->"));
2731 ast::Return(ref ty) => {
2732 try!(self.print_type(&**ty));
2733 self.maybe_print_comment(ty.span.lo)
2735 ast::DefaultReturn(..) => unreachable!(),
2736 ast::NoReturn(span) => {
2737 try!(self.word_nbsp("!"));
2738 self.maybe_print_comment(span.lo)
2743 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2745 match capture_clause {
2746 ast::CaptureByValue => self.word_space("move"),
2747 ast::CaptureByRef => Ok(()),
2751 pub fn print_bounds(&mut self,
2753 bounds: &[ast::TyParamBound])
2755 if !bounds.is_empty() {
2756 try!(word(&mut self.s, prefix));
2757 let mut first = true;
2758 for bound in bounds {
2763 try!(self.word_space("+"));
2767 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2768 self.print_poly_trait_ref(tref)
2770 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2771 try!(word(&mut self.s, "?"));
2772 self.print_poly_trait_ref(tref)
2774 RegionTyParamBound(ref lt) => {
2775 self.print_lifetime(lt)
2785 pub fn print_lifetime(&mut self,
2786 lifetime: &ast::Lifetime)
2789 self.print_name(lifetime.name)
2792 pub fn print_lifetime_def(&mut self,
2793 lifetime: &ast::LifetimeDef)
2796 try!(self.print_lifetime(&lifetime.lifetime));
2798 for v in &lifetime.bounds {
2799 try!(word(&mut self.s, sep));
2800 try!(self.print_lifetime(v));
2806 pub fn print_generics(&mut self,
2807 generics: &ast::Generics)
2810 let total = generics.lifetimes.len() + generics.ty_params.len();
2815 try!(word(&mut self.s, "<"));
2817 let mut ints = Vec::new();
2822 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2823 if idx < generics.lifetimes.len() {
2824 let lifetime = &generics.lifetimes[idx];
2825 s.print_lifetime_def(lifetime)
2827 let idx = idx - generics.lifetimes.len();
2828 let param = &generics.ty_params[idx];
2829 s.print_ty_param(param)
2833 try!(word(&mut self.s, ">"));
2837 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2838 try!(self.print_ident(param.ident));
2839 try!(self.print_bounds(":", ¶m.bounds));
2840 match param.default {
2841 Some(ref default) => {
2842 try!(space(&mut self.s));
2843 try!(self.word_space("="));
2844 self.print_type(&**default)
2850 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2852 if where_clause.predicates.is_empty() {
2856 try!(space(&mut self.s));
2857 try!(self.word_space("where"));
2859 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2861 try!(self.word_space(","));
2865 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2869 try!(self.print_formal_lifetime_list(bound_lifetimes));
2870 try!(self.print_type(&**bounded_ty));
2871 try!(self.print_bounds(":", bounds));
2873 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2876 try!(self.print_lifetime(lifetime));
2877 try!(word(&mut self.s, ":"));
2879 for (i, bound) in bounds.iter().enumerate() {
2880 try!(self.print_lifetime(bound));
2883 try!(word(&mut self.s, ":"));
2887 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2888 try!(self.print_path(path, false, 0));
2889 try!(space(&mut self.s));
2890 try!(self.word_space("="));
2891 try!(self.print_type(&**ty));
2899 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2901 ast::ViewPathSimple(ident, ref path) => {
2902 try!(self.print_path(path, false, 0));
2904 if path.segments.last().unwrap().identifier.name !=
2906 try!(space(&mut self.s));
2907 try!(self.word_space("as"));
2908 try!(self.print_ident(ident));
2914 ast::ViewPathGlob(ref path) => {
2915 try!(self.print_path(path, false, 0));
2916 word(&mut self.s, "::*")
2919 ast::ViewPathList(ref path, ref idents) => {
2920 if path.segments.is_empty() {
2921 try!(word(&mut self.s, "{"));
2923 try!(self.print_path(path, false, 0));
2924 try!(word(&mut self.s, "::{"));
2926 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2928 ast::PathListIdent { name, rename, .. } => {
2929 try!(s.print_ident(name));
2930 if let Some(ident) = rename {
2931 try!(space(&mut s.s));
2932 try!(s.word_space("as"));
2933 try!(s.print_ident(ident));
2937 ast::PathListMod { rename, .. } => {
2938 try!(word(&mut s.s, "self"));
2939 if let Some(ident) = rename {
2940 try!(space(&mut s.s));
2941 try!(s.word_space("as"));
2942 try!(s.print_ident(ident));
2948 word(&mut self.s, "}")
2953 pub fn print_mutability(&mut self,
2954 mutbl: ast::Mutability) -> io::Result<()> {
2956 ast::MutMutable => self.word_nbsp("mut"),
2957 ast::MutImmutable => Ok(()),
2961 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2962 try!(self.print_mutability(mt.mutbl));
2963 self.print_type(&*mt.ty)
2966 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2967 try!(self.ibox(INDENT_UNIT));
2968 match input.ty.node {
2969 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2971 match input.pat.node {
2972 ast::PatIdent(_, ref path1, _) if
2974 parse::token::special_idents::invalid.name => {
2978 try!(self.print_pat(&*input.pat));
2979 try!(word(&mut self.s, ":"));
2980 try!(space(&mut self.s));
2983 try!(self.print_type(&*input.ty));
2989 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2990 if let ast::DefaultReturn(..) = decl.output {
2994 try!(self.space_if_not_bol());
2995 try!(self.ibox(INDENT_UNIT));
2996 try!(self.word_space("->"));
2999 try!(self.word_nbsp("!")),
3000 ast::DefaultReturn(..) => unreachable!(),
3001 ast::Return(ref ty) =>
3002 try!(self.print_type(&**ty))
3007 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
3012 pub fn print_ty_fn(&mut self,
3014 unsafety: ast::Unsafety,
3016 name: Option<ast::Ident>,
3017 generics: &ast::Generics,
3018 opt_explicit_self: Option<&ast::ExplicitSelf_>)
3020 try!(self.ibox(INDENT_UNIT));
3021 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
3022 try!(word(&mut self.s, "for"));
3023 try!(self.print_generics(generics));
3025 let generics = ast::Generics {
3026 lifetimes: Vec::new(),
3027 ty_params: OwnedSlice::empty(),
3028 where_clause: ast::WhereClause {
3029 id: ast::DUMMY_NODE_ID,
3030 predicates: Vec::new(),
3033 try!(self.print_fn(decl,
3035 ast::Constness::NotConst,
3044 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
3045 next_pos: Option<BytePos>)
3047 let cm = match self.cm {
3051 match self.next_comment() {
3053 if (*cmnt).style != comments::Trailing { return Ok(()) }
3054 let span_line = cm.lookup_char_pos(span.hi);
3055 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3056 let mut next = (*cmnt).pos + BytePos(1);
3057 match next_pos { None => (), Some(p) => next = p }
3058 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3059 span_line.line == comment_line.line {
3060 try!(self.print_comment(cmnt));
3061 self.cur_cmnt_and_lit.cur_cmnt += 1;
3069 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3070 // If there aren't any remaining comments, then we need to manually
3071 // make sure there is a line break at the end.
3072 if self.next_comment().is_none() {
3073 try!(hardbreak(&mut self.s));
3076 match self.next_comment() {
3078 try!(self.print_comment(cmnt));
3079 self.cur_cmnt_and_lit.cur_cmnt += 1;
3087 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3088 opt_abi: Option<abi::Abi>)
3091 Some(abi::Rust) => Ok(()),
3093 try!(self.word_nbsp("extern"));
3094 self.word_nbsp(&abi.to_string())
3100 pub fn print_extern_opt_abi(&mut self,
3101 opt_abi: Option<abi::Abi>) -> io::Result<()> {
3104 try!(self.word_nbsp("extern"));
3105 self.word_nbsp(&abi.to_string())
3111 pub fn print_fn_header_info(&mut self,
3112 unsafety: ast::Unsafety,
3113 constness: ast::Constness,
3115 vis: ast::Visibility) -> io::Result<()> {
3116 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3119 ast::Constness::NotConst => {}
3120 ast::Constness::Const => try!(self.word_nbsp("const"))
3123 try!(self.print_unsafety(unsafety));
3125 if abi != abi::Rust {
3126 try!(self.word_nbsp("extern"));
3127 try!(self.word_nbsp(&abi.to_string()));
3130 word(&mut self.s, "fn")
3133 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3135 ast::Unsafety::Normal => Ok(()),
3136 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3141 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3153 fn test_fun_to_string() {
3154 let abba_ident = token::str_to_ident("abba");
3156 let decl = ast::FnDecl {
3158 output: ast::DefaultReturn(codemap::DUMMY_SP),
3161 let generics = ast::Generics::default();
3162 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3163 ast::Constness::NotConst,
3170 fn test_variant_to_string() {
3171 let ident = token::str_to_ident("principal_skinner");
3173 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3176 // making this up as I go.... ?
3177 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3181 let varstr = variant_to_string(&var);
3182 assert_eq!(varstr, "principal_skinner");
3186 fn test_signed_int_to_string() {
3187 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3188 let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3189 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3190 lit_to_string(&codemap::dummy_spanned(neg_int)));