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 util::parser::AssocOp;
19 use owned_slice::OwnedSlice;
20 use attr::{AttrMetaMethods, AttributeMethods};
21 use codemap::{self, CodeMap, BytePos};
23 use parse::token::{self, BinOpToken, Token, InternedString};
24 use parse::lexer::comments;
26 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
27 use print::pp::{Breaks, eof};
28 use print::pp::Breaks::{Consistent, Inconsistent};
33 use std::io::{self, Write, Read};
36 pub enum AnnNode<'a> {
37 NodeIdent(&'a ast::Ident),
38 NodeName(&'a ast::Name),
39 NodeBlock(&'a ast::Block),
40 NodeItem(&'a ast::Item),
41 NodeSubItem(ast::NodeId),
42 NodeExpr(&'a ast::Expr),
43 NodePat(&'a ast::Pat),
47 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
48 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
51 #[derive(Copy, Clone)]
54 impl PpAnn for NoAnn {}
56 #[derive(Copy, Clone)]
57 pub struct CurrentCommentAndLiteral {
62 pub struct State<'a> {
63 pub s: pp::Printer<'a>,
64 cm: Option<&'a CodeMap>,
65 comments: Option<Vec<comments::Comment> >,
66 literals: Option<Vec<comments::Literal> >,
67 cur_cmnt_and_lit: CurrentCommentAndLiteral,
68 boxes: Vec<pp::Breaks>,
72 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
73 static NO_ANN: NoAnn = NoAnn;
74 rust_printer_annotated(writer, &NO_ANN)
77 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
78 ann: &'a PpAnn) -> State<'a> {
80 s: pp::mk_printer(writer, default_columns),
84 cur_cmnt_and_lit: CurrentCommentAndLiteral {
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::no_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"));
124 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
126 // #![feature(no_std)]
127 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
128 attr::mk_list_item(InternedString::new("feature"),
129 vec![no_std_meta.clone(),
130 prelude_import_meta]));
131 try!(s.print_attribute(&fake_attr));
134 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
135 try!(s.print_attribute(&fake_attr));
138 try!(s.print_mod(&krate.module, &krate.attrs));
139 try!(s.print_remaining_comments());
144 pub fn new_from_input(cm: &'a CodeMap,
145 span_diagnostic: &diagnostic::SpanHandler,
150 is_expanded: bool) -> State<'a> {
151 let (cmnts, lits) = comments::gather_comments_and_literals(
161 // If the code is post expansion, don't use the table of
162 // literals, since it doesn't correspond with the literals
163 // in the AST anymore.
164 if is_expanded { None } else { Some(lits) })
167 pub fn new(cm: &'a CodeMap,
170 comments: Option<Vec<comments::Comment>>,
171 literals: Option<Vec<comments::Literal>>) -> State<'a> {
173 s: pp::mk_printer(out, default_columns),
177 cur_cmnt_and_lit: CurrentCommentAndLiteral {
187 pub fn to_string<F>(f: F) -> String where
188 F: FnOnce(&mut State) -> io::Result<()>,
190 let mut wr = Vec::new();
192 let mut printer = rust_printer(Box::new(&mut wr));
193 f(&mut printer).unwrap();
194 eof(&mut printer.s).unwrap();
196 String::from_utf8(wr).unwrap()
199 pub fn binop_to_string(op: BinOpToken) -> &'static str {
205 token::Percent => "%",
214 pub fn token_to_string(tok: &Token) -> String {
216 token::Eq => "=".to_string(),
217 token::Lt => "<".to_string(),
218 token::Le => "<=".to_string(),
219 token::EqEq => "==".to_string(),
220 token::Ne => "!=".to_string(),
221 token::Ge => ">=".to_string(),
222 token::Gt => ">".to_string(),
223 token::Not => "!".to_string(),
224 token::Tilde => "~".to_string(),
225 token::OrOr => "||".to_string(),
226 token::AndAnd => "&&".to_string(),
227 token::BinOp(op) => binop_to_string(op).to_string(),
228 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
230 /* Structural symbols */
231 token::At => "@".to_string(),
232 token::Dot => ".".to_string(),
233 token::DotDot => "..".to_string(),
234 token::DotDotDot => "...".to_string(),
235 token::Comma => ",".to_string(),
236 token::Semi => ";".to_string(),
237 token::Colon => ":".to_string(),
238 token::ModSep => "::".to_string(),
239 token::RArrow => "->".to_string(),
240 token::LArrow => "<-".to_string(),
241 token::FatArrow => "=>".to_string(),
242 token::OpenDelim(token::Paren) => "(".to_string(),
243 token::CloseDelim(token::Paren) => ")".to_string(),
244 token::OpenDelim(token::Bracket) => "[".to_string(),
245 token::CloseDelim(token::Bracket) => "]".to_string(),
246 token::OpenDelim(token::Brace) => "{".to_string(),
247 token::CloseDelim(token::Brace) => "}".to_string(),
248 token::Pound => "#".to_string(),
249 token::Dollar => "$".to_string(),
250 token::Question => "?".to_string(),
253 token::Literal(lit, suf) => {
254 let mut out = match lit {
255 token::Byte(b) => format!("b'{}'", b),
256 token::Char(c) => format!("'{}'", c),
257 token::Float(c) => c.to_string(),
258 token::Integer(c) => c.to_string(),
259 token::Str_(s) => format!("\"{}\"", s),
260 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
261 delim=repeat("#", n),
263 token::ByteStr(v) => format!("b\"{}\"", v),
264 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
265 delim=repeat("#", n),
269 if let Some(s) = suf {
270 out.push_str(&s.as_str())
276 /* Name components */
277 token::Ident(s, _) => s.to_string(),
278 token::Lifetime(s) => s.to_string(),
279 token::Underscore => "_".to_string(),
282 token::DocComment(s) => s.to_string(),
283 token::SubstNt(s, _) => format!("${}", s),
284 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
285 token::Eof => "<eof>".to_string(),
286 token::Whitespace => " ".to_string(),
287 token::Comment => "/* */".to_string(),
288 token::Shebang(s) => format!("/* shebang: {}*/", s),
290 token::SpecialVarNt(var) => format!("${}", var.as_str()),
292 token::Interpolated(ref nt) => match *nt {
293 token::NtExpr(ref e) => expr_to_string(&**e),
294 token::NtMeta(ref e) => meta_item_to_string(&**e),
295 token::NtTy(ref e) => ty_to_string(&**e),
296 token::NtPath(ref e) => path_to_string(&**e),
297 token::NtItem(ref e) => item_to_string(&**e),
298 token::NtBlock(ref e) => block_to_string(&**e),
299 token::NtStmt(ref e) => stmt_to_string(&**e),
300 token::NtPat(ref e) => pat_to_string(&**e),
301 token::NtIdent(ref e, _) => ident_to_string(**e),
302 token::NtTT(ref e) => tt_to_string(&**e),
303 token::NtArm(ref e) => arm_to_string(&*e),
304 token::NtImplItem(ref e) => impl_item_to_string(&**e),
305 token::NtTraitItem(ref e) => trait_item_to_string(&**e),
306 token::NtGenerics(ref e) => generics_to_string(&*e),
307 token::NtWhereClause(ref e) => where_clause_to_string(&*e),
308 token::NtArg(ref e) => arg_to_string(&*e),
313 pub fn ty_to_string(ty: &ast::Ty) -> String {
314 to_string(|s| s.print_type(ty))
317 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
318 to_string(|s| s.print_bounds("", bounds))
321 pub fn pat_to_string(pat: &ast::Pat) -> String {
322 to_string(|s| s.print_pat(pat))
325 pub fn arm_to_string(arm: &ast::Arm) -> String {
326 to_string(|s| s.print_arm(arm))
329 pub fn expr_to_string(e: &ast::Expr) -> String {
330 to_string(|s| s.print_expr(e))
333 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
334 to_string(|s| s.print_lifetime(e))
337 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
338 to_string(|s| s.print_tt(tt))
341 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
342 to_string(|s| s.print_tts(tts))
345 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
346 to_string(|s| s.print_stmt(stmt))
349 pub fn attr_to_string(attr: &ast::Attribute) -> String {
350 to_string(|s| s.print_attribute(attr))
353 pub fn item_to_string(i: &ast::Item) -> String {
354 to_string(|s| s.print_item(i))
357 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
358 to_string(|s| s.print_impl_item(i))
361 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
362 to_string(|s| s.print_trait_item(i))
365 pub fn generics_to_string(generics: &ast::Generics) -> String {
366 to_string(|s| s.print_generics(generics))
369 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
370 to_string(|s| s.print_where_clause(i))
373 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
374 to_string(|s| s.print_fn_block_args(p))
377 pub fn path_to_string(p: &ast::Path) -> String {
378 to_string(|s| s.print_path(p, false, 0))
381 pub fn ident_to_string(id: ast::Ident) -> String {
382 to_string(|s| s.print_ident(id))
385 pub fn fun_to_string(decl: &ast::FnDecl,
386 unsafety: ast::Unsafety,
387 constness: ast::Constness,
389 opt_explicit_self: Option<&ast::ExplicitSelf_>,
390 generics: &ast::Generics)
394 try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
395 generics, opt_explicit_self, ast::Inherited));
396 try!(s.end()); // Close the head box
397 s.end() // Close the outer box
401 pub fn block_to_string(blk: &ast::Block) -> String {
403 // containing cbox, will be closed by print-block at }
404 try!(s.cbox(indent_unit));
405 // head-ibox, will be closed by print-block after {
411 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
412 to_string(|s| s.print_meta_item(mi))
415 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
416 to_string(|s| s.print_attribute(attr))
419 pub fn lit_to_string(l: &ast::Lit) -> String {
420 to_string(|s| s.print_literal(l))
423 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
424 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
427 pub fn variant_to_string(var: &ast::Variant) -> String {
428 to_string(|s| s.print_variant(var))
431 pub fn arg_to_string(arg: &ast::Arg) -> String {
432 to_string(|s| s.print_arg(arg))
435 pub fn mac_to_string(arg: &ast::Mac) -> String {
436 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
439 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
441 ast::Public => format!("pub {}", s),
442 ast::Inherited => s.to_string()
446 fn needs_parentheses(expr: &ast::Expr) -> bool {
448 ast::ExprAssign(..) | ast::ExprBinary(..) |
449 ast::ExprClosure(..) |
450 ast::ExprAssignOp(..) | ast::ExprCast(..) |
451 ast::ExprInPlace(..) => true,
456 pub trait PrintState<'a> {
457 fn writer(&mut self) -> &mut pp::Printer<'a>;
458 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
459 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
460 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
461 fn literals(&self) -> &Option<Vec<comments::Literal>>;
463 fn word_space(&mut self, w: &str) -> io::Result<()> {
464 try!(word(self.writer(), w));
468 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
470 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
472 fn is_begin(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::Begin(_) => true,
479 fn is_end(&mut self) -> bool {
480 match self.writer().last_token() {
481 pp::Token::End => true,
486 // is this the beginning of a line?
487 fn is_bol(&mut self) -> bool {
488 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
491 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
493 try!(hardbreak(self.writer()))
499 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
500 self.boxes().push(b);
501 pp::rbox(self.writer(), u, b)
504 fn ibox(&mut self, u: usize) -> io::Result<()> {
505 self.boxes().push(pp::Breaks::Inconsistent);
506 pp::ibox(self.writer(), u)
509 fn end(&mut self) -> io::Result<()> {
510 self.boxes().pop().unwrap();
511 pp::end(self.writer())
514 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
515 where F: FnMut(&mut Self, &T) -> io::Result<()>,
517 try!(self.rbox(0, b));
518 let mut first = true;
520 if first { first = false; } else { try!(self.word_space(",")); }
526 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
527 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
529 let mut result = None;
531 if let &Some(ref lits) = self.literals()
533 while cur_lit < lits.len() {
534 let ltrl = (*lits)[cur_lit].clone();
535 if ltrl.pos > pos { break; }
544 self.cur_cmnt_and_lit().cur_lit = cur_lit;
548 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
550 match self.next_comment() {
552 if (*cmnt).pos < pos {
553 try!(self.print_comment(cmnt));
554 self.cur_cmnt_and_lit().cur_cmnt += 1;
563 fn print_comment(&mut self,
564 cmnt: &comments::Comment) -> io::Result<()> {
567 assert_eq!(cmnt.lines.len(), 1);
568 try!(zerobreak(self.writer()));
569 try!(word(self.writer(), &cmnt.lines[0]));
570 zerobreak(self.writer())
572 comments::Isolated => {
573 try!(self.hardbreak_if_not_bol());
574 for line in &cmnt.lines {
575 // Don't print empty lines because they will end up as trailing
577 if !line.is_empty() {
578 try!(word(self.writer(), &line[..]));
580 try!(hardbreak(self.writer()));
584 comments::Trailing => {
585 try!(word(self.writer(), " "));
586 if cmnt.lines.len() == 1 {
587 try!(word(self.writer(), &cmnt.lines[0]));
588 hardbreak(self.writer())
591 for line in &cmnt.lines {
592 if !line.is_empty() {
593 try!(word(self.writer(), &line[..]));
595 try!(hardbreak(self.writer()));
600 comments::BlankLine => {
601 // We need to do at least one, possibly two hardbreaks.
602 let is_semi = match self.writer().last_token() {
603 pp::Token::String(s, _) => ";" == s,
606 if is_semi || self.is_begin() || self.is_end() {
607 try!(hardbreak(self.writer()));
609 hardbreak(self.writer())
614 fn next_comment(&mut self) -> Option<comments::Comment> {
615 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
616 match *self.comments() {
618 if cur_cmnt < cmnts.len() {
619 Some(cmnts[cur_cmnt].clone())
628 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
629 try!(self.maybe_print_comment(lit.span.lo));
630 match self.next_lit(lit.span.lo) {
632 return word(self.writer(), &(*ltrl).lit);
637 ast::LitStr(ref st, style) => self.print_string(&st, style),
638 ast::LitByte(byte) => {
639 let mut res = String::from("b'");
640 res.extend(ascii::escape_default(byte).map(|c| c as char));
642 word(self.writer(), &res[..])
644 ast::LitChar(ch) => {
645 let mut res = String::from("'");
646 res.extend(ch.escape_default());
648 word(self.writer(), &res[..])
650 ast::LitInt(i, t) => {
652 ast::SignedIntLit(st, ast::Plus) => {
654 &ast_util::int_ty_to_string(st, Some(i as i64)))
656 ast::SignedIntLit(st, ast::Minus) => {
657 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
659 &format!("-{}", istr))
661 ast::UnsignedIntLit(ut) => {
662 word(self.writer(), &ast_util::uint_ty_to_string(ut, Some(i)))
664 ast::UnsuffixedIntLit(ast::Plus) => {
665 word(self.writer(), &format!("{}", i))
667 ast::UnsuffixedIntLit(ast::Minus) => {
668 word(self.writer(), &format!("-{}", i))
672 ast::LitFloat(ref f, t) => {
677 &ast_util::float_ty_to_string(t)))
679 ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
680 ast::LitBool(val) => {
681 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
683 ast::LitByteStr(ref v) => {
684 let mut escaped: String = String::new();
685 for &ch in v.iter() {
686 escaped.extend(ascii::escape_default(ch)
687 .map(|c| c as char));
689 word(self.writer(), &format!("b\"{}\"", escaped))
694 fn print_string(&mut self, st: &str,
695 style: ast::StrStyle) -> io::Result<()> {
696 let st = match style {
698 (format!("\"{}\"", st.escape_default()))
701 (format!("r{delim}\"{string}\"{delim}",
702 delim=repeat("#", n),
706 word(self.writer(), &st[..])
709 fn print_inner_attributes(&mut self,
710 attrs: &[ast::Attribute]) -> io::Result<()> {
713 match attr.node.style {
714 ast::AttrStyle::Inner => {
715 try!(self.print_attribute(attr));
718 _ => {/* fallthrough */ }
722 try!(self.hardbreak_if_not_bol());
727 fn print_outer_attributes(&mut self,
728 attrs: &[ast::Attribute]) -> io::Result<()> {
731 match attr.node.style {
732 ast::AttrStyle::Outer => {
733 try!(self.print_attribute(attr));
736 _ => {/* fallthrough */ }
740 try!(self.hardbreak_if_not_bol());
745 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
746 try!(self.hardbreak_if_not_bol());
747 try!(self.maybe_print_comment(attr.span.lo));
748 if attr.node.is_sugared_doc {
749 word(self.writer(), &attr.value_str().unwrap())
751 match attr.node.style {
752 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
753 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
755 try!(self.print_meta_item(&*attr.meta()));
756 word(self.writer(), "]")
760 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
761 try!(self.ibox(indent_unit));
763 ast::MetaWord(ref name) => {
764 try!(word(self.writer(), &name));
766 ast::MetaNameValue(ref name, ref value) => {
767 try!(self.word_space(&name[..]));
768 try!(self.word_space("="));
769 try!(self.print_literal(value));
771 ast::MetaList(ref name, ref items) => {
772 try!(word(self.writer(), &name));
774 try!(self.commasep(Consistent,
776 |s, i| s.print_meta_item(&**i)));
784 impl<'a> PrintState<'a> for State<'a> {
785 fn writer(&mut self) -> &mut pp::Printer<'a> {
789 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
793 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
797 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
798 &mut self.cur_cmnt_and_lit
801 fn literals(&self) -> &Option<Vec<comments::Literal>> {
807 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
808 self.boxes.push(pp::Breaks::Consistent);
809 pp::cbox(&mut self.s, u)
812 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
814 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
815 try!(word(&mut self.s, w));
819 pub fn head(&mut self, w: &str) -> io::Result<()> {
820 // outer-box is consistent
821 try!(self.cbox(indent_unit));
822 // head-box is inconsistent
823 try!(self.ibox(w.len() + 1));
824 // keyword that starts the head
826 try!(self.word_nbsp(w));
831 pub fn bopen(&mut self) -> io::Result<()> {
832 try!(word(&mut self.s, "{"));
833 self.end() // close the head-box
836 pub fn bclose_(&mut self, span: codemap::Span,
837 indented: usize) -> io::Result<()> {
838 self.bclose_maybe_open(span, indented, true)
840 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
841 indented: usize, close_box: bool) -> io::Result<()> {
842 try!(self.maybe_print_comment(span.hi));
843 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
844 try!(word(&mut self.s, "}"));
846 try!(self.end()); // close the outer-box
850 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
851 self.bclose_(span, indent_unit)
854 pub fn in_cbox(&self) -> bool {
855 match self.boxes.last() {
856 Some(&last_box) => last_box == pp::Breaks::Consistent,
861 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
862 if !self.is_bol() { try!(space(&mut self.s)); }
865 pub fn break_offset_if_not_bol(&mut self, n: usize,
866 off: isize) -> io::Result<()> {
868 break_offset(&mut self.s, n, off)
870 if off != 0 && self.s.last_token().is_hardbreak_tok() {
871 // We do something pretty sketchy here: tuck the nonzero
872 // offset-adjustment we were going to deposit along with the
873 // break into the previous hardbreak.
874 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
880 // Synthesizes a comment that was not textually present in the original source
882 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
883 try!(word(&mut self.s, "/*"));
884 try!(space(&mut self.s));
885 try!(word(&mut self.s, &text[..]));
886 try!(space(&mut self.s));
887 word(&mut self.s, "*/")
892 pub fn commasep_cmnt<T, F, G>(&mut self,
896 mut get_span: G) -> io::Result<()> where
897 F: FnMut(&mut State, &T) -> io::Result<()>,
898 G: FnMut(&T) -> codemap::Span,
900 try!(self.rbox(0, b));
901 let len = elts.len();
904 try!(self.maybe_print_comment(get_span(elt).hi));
908 try!(word(&mut self.s, ","));
909 try!(self.maybe_print_trailing_comment(get_span(elt),
910 Some(get_span(&elts[i]).hi)));
911 try!(self.space_if_not_bol());
917 pub fn commasep_exprs(&mut self, b: Breaks,
918 exprs: &[P<ast::Expr>]) -> io::Result<()> {
919 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
922 pub fn print_mod(&mut self, _mod: &ast::Mod,
923 attrs: &[ast::Attribute]) -> io::Result<()> {
924 try!(self.print_inner_attributes(attrs));
925 for item in &_mod.items {
926 try!(self.print_item(&**item));
931 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
932 attrs: &[ast::Attribute]) -> io::Result<()> {
933 try!(self.print_inner_attributes(attrs));
934 for item in &nmod.items {
935 try!(self.print_foreign_item(&**item));
940 pub fn print_opt_lifetime(&mut self,
941 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
942 if let Some(l) = *lifetime {
943 try!(self.print_lifetime(&l));
949 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
950 try!(self.maybe_print_comment(ty.span.lo));
953 ast::TyVec(ref ty) => {
954 try!(word(&mut self.s, "["));
955 try!(self.print_type(&**ty));
956 try!(word(&mut self.s, "]"));
958 ast::TyPtr(ref mt) => {
959 try!(word(&mut self.s, "*"));
961 ast::MutMutable => try!(self.word_nbsp("mut")),
962 ast::MutImmutable => try!(self.word_nbsp("const")),
964 try!(self.print_type(&*mt.ty));
966 ast::TyRptr(ref lifetime, ref mt) => {
967 try!(word(&mut self.s, "&"));
968 try!(self.print_opt_lifetime(lifetime));
969 try!(self.print_mt(mt));
971 ast::TyTup(ref elts) => {
973 try!(self.commasep(Inconsistent, &elts[..],
974 |s, ty| s.print_type(&**ty)));
976 try!(word(&mut self.s, ","));
980 ast::TyParen(ref typ) => {
982 try!(self.print_type(&**typ));
985 ast::TyBareFn(ref f) => {
986 let generics = ast::Generics {
987 lifetimes: f.lifetimes.clone(),
988 ty_params: OwnedSlice::empty(),
989 where_clause: ast::WhereClause {
990 id: ast::DUMMY_NODE_ID,
991 predicates: Vec::new(),
994 try!(self.print_ty_fn(f.abi,
1001 ast::TyPath(None, ref path) => {
1002 try!(self.print_path(path, false, 0));
1004 ast::TyPath(Some(ref qself), ref path) => {
1005 try!(self.print_qpath(path, qself, false))
1007 ast::TyObjectSum(ref ty, ref bounds) => {
1008 try!(self.print_type(&**ty));
1009 try!(self.print_bounds("+", &bounds[..]));
1011 ast::TyPolyTraitRef(ref bounds) => {
1012 try!(self.print_bounds("", &bounds[..]));
1014 ast::TyFixedLengthVec(ref ty, ref v) => {
1015 try!(word(&mut self.s, "["));
1016 try!(self.print_type(&**ty));
1017 try!(word(&mut self.s, "; "));
1018 try!(self.print_expr(&**v));
1019 try!(word(&mut self.s, "]"));
1021 ast::TyTypeof(ref e) => {
1022 try!(word(&mut self.s, "typeof("));
1023 try!(self.print_expr(&**e));
1024 try!(word(&mut self.s, ")"));
1027 try!(word(&mut self.s, "_"));
1029 ast::TyMac(ref m) => {
1030 try!(self.print_mac(m, token::Paren));
1036 pub fn print_foreign_item(&mut self,
1037 item: &ast::ForeignItem) -> io::Result<()> {
1038 try!(self.hardbreak_if_not_bol());
1039 try!(self.maybe_print_comment(item.span.lo));
1040 try!(self.print_outer_attributes(&item.attrs));
1042 ast::ForeignItemFn(ref decl, ref generics) => {
1043 try!(self.head(""));
1044 try!(self.print_fn(decl, ast::Unsafety::Normal,
1045 ast::Constness::NotConst,
1046 abi::Rust, Some(item.ident),
1047 generics, None, item.vis));
1048 try!(self.end()); // end head-ibox
1049 try!(word(&mut self.s, ";"));
1050 self.end() // end the outer fn box
1052 ast::ForeignItemStatic(ref t, m) => {
1053 try!(self.head(&visibility_qualified(item.vis,
1056 try!(self.word_space("mut"));
1058 try!(self.print_ident(item.ident));
1059 try!(self.word_space(":"));
1060 try!(self.print_type(&**t));
1061 try!(word(&mut self.s, ";"));
1062 try!(self.end()); // end the head-ibox
1063 self.end() // end the outer cbox
1068 fn print_associated_const(&mut self,
1071 default: Option<&ast::Expr>,
1072 vis: ast::Visibility)
1075 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1076 try!(self.word_space("const"));
1077 try!(self.print_ident(ident));
1078 try!(self.word_space(":"));
1079 try!(self.print_type(ty));
1080 if let Some(expr) = default {
1081 try!(space(&mut self.s));
1082 try!(self.word_space("="));
1083 try!(self.print_expr(expr));
1085 word(&mut self.s, ";")
1088 fn print_associated_type(&mut self,
1090 bounds: Option<&ast::TyParamBounds>,
1091 ty: Option<&ast::Ty>)
1093 try!(self.word_space("type"));
1094 try!(self.print_ident(ident));
1095 if let Some(bounds) = bounds {
1096 try!(self.print_bounds(":", bounds));
1098 if let Some(ty) = ty {
1099 try!(space(&mut self.s));
1100 try!(self.word_space("="));
1101 try!(self.print_type(ty));
1103 word(&mut self.s, ";")
1106 /// Pretty-print an item
1107 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1108 try!(self.hardbreak_if_not_bol());
1109 try!(self.maybe_print_comment(item.span.lo));
1110 try!(self.print_outer_attributes(&item.attrs));
1111 try!(self.ann.pre(self, NodeItem(item)));
1113 ast::ItemExternCrate(ref optional_path) => {
1114 try!(self.head(&visibility_qualified(item.vis,
1116 if let Some(p) = *optional_path {
1117 let val = p.as_str();
1118 if val.contains("-") {
1119 try!(self.print_string(&val, ast::CookedStr));
1121 try!(self.print_name(p));
1123 try!(space(&mut self.s));
1124 try!(word(&mut self.s, "as"));
1125 try!(space(&mut self.s));
1127 try!(self.print_ident(item.ident));
1128 try!(word(&mut self.s, ";"));
1129 try!(self.end()); // end inner head-block
1130 try!(self.end()); // end outer head-block
1132 ast::ItemUse(ref vp) => {
1133 try!(self.head(&visibility_qualified(item.vis,
1135 try!(self.print_view_path(&**vp));
1136 try!(word(&mut self.s, ";"));
1137 try!(self.end()); // end inner head-block
1138 try!(self.end()); // end outer head-block
1140 ast::ItemStatic(ref ty, m, ref expr) => {
1141 try!(self.head(&visibility_qualified(item.vis,
1143 if m == ast::MutMutable {
1144 try!(self.word_space("mut"));
1146 try!(self.print_ident(item.ident));
1147 try!(self.word_space(":"));
1148 try!(self.print_type(&**ty));
1149 try!(space(&mut self.s));
1150 try!(self.end()); // end the head-ibox
1152 try!(self.word_space("="));
1153 try!(self.print_expr(&**expr));
1154 try!(word(&mut self.s, ";"));
1155 try!(self.end()); // end the outer cbox
1157 ast::ItemConst(ref ty, ref expr) => {
1158 try!(self.head(&visibility_qualified(item.vis,
1160 try!(self.print_ident(item.ident));
1161 try!(self.word_space(":"));
1162 try!(self.print_type(&**ty));
1163 try!(space(&mut self.s));
1164 try!(self.end()); // end the head-ibox
1166 try!(self.word_space("="));
1167 try!(self.print_expr(&**expr));
1168 try!(word(&mut self.s, ";"));
1169 try!(self.end()); // end the outer cbox
1171 ast::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1172 try!(self.head(""));
1183 try!(word(&mut self.s, " "));
1184 try!(self.print_block_with_attrs(&**body, &item.attrs));
1186 ast::ItemMod(ref _mod) => {
1187 try!(self.head(&visibility_qualified(item.vis,
1189 try!(self.print_ident(item.ident));
1192 try!(self.print_mod(_mod, &item.attrs));
1193 try!(self.bclose(item.span));
1195 ast::ItemForeignMod(ref nmod) => {
1196 try!(self.head("extern"));
1197 try!(self.word_nbsp(&nmod.abi.to_string()));
1199 try!(self.print_foreign_mod(nmod, &item.attrs));
1200 try!(self.bclose(item.span));
1202 ast::ItemTy(ref ty, ref params) => {
1203 try!(self.ibox(indent_unit));
1205 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
1206 try!(self.print_ident(item.ident));
1207 try!(self.print_generics(params));
1208 try!(self.end()); // end the inner ibox
1210 try!(self.print_where_clause(¶ms.where_clause));
1211 try!(space(&mut self.s));
1212 try!(self.word_space("="));
1213 try!(self.print_type(&**ty));
1214 try!(word(&mut self.s, ";"));
1215 try!(self.end()); // end the outer ibox
1217 ast::ItemEnum(ref enum_definition, ref params) => {
1218 try!(self.print_enum_def(
1226 ast::ItemStruct(ref struct_def, ref generics) => {
1227 try!(self.head(&visibility_qualified(item.vis,"struct")));
1228 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1231 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
1232 try!(self.head(""));
1233 try!(self.print_visibility(item.vis));
1234 try!(self.print_unsafety(unsafety));
1235 try!(self.word_nbsp("impl"));
1236 try!(self.print_trait_ref(trait_ref));
1237 try!(space(&mut self.s));
1238 try!(self.word_space("for"));
1239 try!(self.word_space(".."));
1241 try!(self.bclose(item.span));
1243 ast::ItemImpl(unsafety,
1248 ref impl_items) => {
1249 try!(self.head(""));
1250 try!(self.print_visibility(item.vis));
1251 try!(self.print_unsafety(unsafety));
1252 try!(self.word_nbsp("impl"));
1254 if generics.is_parameterized() {
1255 try!(self.print_generics(generics));
1256 try!(space(&mut self.s));
1260 ast::ImplPolarity::Negative => {
1261 try!(word(&mut self.s, "!"));
1268 try!(self.print_trait_ref(t));
1269 try!(space(&mut self.s));
1270 try!(self.word_space("for"));
1275 try!(self.print_type(&**ty));
1276 try!(self.print_where_clause(&generics.where_clause));
1278 try!(space(&mut self.s));
1280 try!(self.print_inner_attributes(&item.attrs));
1281 for impl_item in impl_items {
1282 try!(self.print_impl_item(impl_item));
1284 try!(self.bclose(item.span));
1286 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
1287 try!(self.head(""));
1288 try!(self.print_visibility(item.vis));
1289 try!(self.print_unsafety(unsafety));
1290 try!(self.word_nbsp("trait"));
1291 try!(self.print_ident(item.ident));
1292 try!(self.print_generics(generics));
1293 let mut real_bounds = Vec::with_capacity(bounds.len());
1294 for b in bounds.iter() {
1295 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1296 try!(space(&mut self.s));
1297 try!(self.word_space("for ?"));
1298 try!(self.print_trait_ref(&ptr.trait_ref));
1300 real_bounds.push(b.clone());
1303 try!(self.print_bounds(":", &real_bounds[..]));
1304 try!(self.print_where_clause(&generics.where_clause));
1305 try!(word(&mut self.s, " "));
1307 for trait_item in trait_items {
1308 try!(self.print_trait_item(trait_item));
1310 try!(self.bclose(item.span));
1312 ast::ItemMac(codemap::Spanned { ref node, .. }) => {
1313 try!(self.print_visibility(item.vis));
1314 try!(self.print_path(&node.path, false, 0));
1315 try!(word(&mut self.s, "! "));
1316 try!(self.print_ident(item.ident));
1317 try!(self.cbox(indent_unit));
1319 try!(self.print_tts(&node.tts[..]));
1320 try!(self.pclose());
1321 try!(word(&mut self.s, ";"));
1325 self.ann.post(self, NodeItem(item))
1328 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1329 self.print_path(&t.path, false, 0)
1332 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1333 if !lifetimes.is_empty() {
1334 try!(word(&mut self.s, "for<"));
1335 let mut comma = false;
1336 for lifetime_def in lifetimes {
1338 try!(self.word_space(","))
1340 try!(self.print_lifetime_def(lifetime_def));
1343 try!(word(&mut self.s, ">"));
1348 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1349 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1350 self.print_trait_ref(&t.trait_ref)
1353 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1354 generics: &ast::Generics, ident: ast::Ident,
1355 span: codemap::Span,
1356 visibility: ast::Visibility) -> io::Result<()> {
1357 try!(self.head(&visibility_qualified(visibility, "enum")));
1358 try!(self.print_ident(ident));
1359 try!(self.print_generics(generics));
1360 try!(self.print_where_clause(&generics.where_clause));
1361 try!(space(&mut self.s));
1362 self.print_variants(&enum_definition.variants, span)
1365 pub fn print_variants(&mut self,
1366 variants: &[P<ast::Variant>],
1367 span: codemap::Span) -> io::Result<()> {
1370 try!(self.space_if_not_bol());
1371 try!(self.maybe_print_comment(v.span.lo));
1372 try!(self.print_outer_attributes(&v.node.attrs));
1373 try!(self.ibox(indent_unit));
1374 try!(self.print_variant(&**v));
1375 try!(word(&mut self.s, ","));
1377 try!(self.maybe_print_trailing_comment(v.span, None));
1382 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1384 ast::Public => self.word_nbsp("pub"),
1385 ast::Inherited => Ok(())
1389 pub fn print_struct(&mut self,
1390 struct_def: &ast::VariantData,
1391 generics: &ast::Generics,
1393 span: codemap::Span,
1394 print_finalizer: bool) -> io::Result<()> {
1395 try!(self.print_ident(ident));
1396 try!(self.print_generics(generics));
1397 if !struct_def.is_struct() {
1398 if struct_def.is_tuple() {
1401 Inconsistent, struct_def.fields(),
1403 match field.node.kind {
1404 ast::NamedField(..) => panic!("unexpected named field"),
1405 ast::UnnamedField(vis) => {
1406 try!(s.print_visibility(vis));
1407 try!(s.maybe_print_comment(field.span.lo));
1408 s.print_type(&*field.node.ty)
1413 try!(self.pclose());
1415 try!(self.print_where_clause(&generics.where_clause));
1416 if print_finalizer {
1417 try!(word(&mut self.s, ";"));
1420 self.end() // close the outer-box
1422 try!(self.print_where_clause(&generics.where_clause));
1425 try!(self.hardbreak_if_not_bol());
1427 for field in struct_def.fields() {
1428 match field.node.kind {
1429 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1430 ast::NamedField(ident, visibility) => {
1431 try!(self.hardbreak_if_not_bol());
1432 try!(self.maybe_print_comment(field.span.lo));
1433 try!(self.print_outer_attributes(&field.node.attrs));
1434 try!(self.print_visibility(visibility));
1435 try!(self.print_ident(ident));
1436 try!(self.word_nbsp(":"));
1437 try!(self.print_type(&*field.node.ty));
1438 try!(word(&mut self.s, ","));
1447 /// This doesn't deserve to be called "pretty" printing, but it should be
1448 /// meaning-preserving. A quick hack that might help would be to look at the
1449 /// spans embedded in the TTs to decide where to put spaces and newlines.
1450 /// But it'd be better to parse these according to the grammar of the
1451 /// appropriate macro, transcribe back into the grammar we just parsed from,
1452 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1453 /// expression arguments as expressions). It can be done! I think.
1454 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1456 TokenTree::Token(_, ref tk) => {
1457 try!(word(&mut self.s, &token_to_string(tk)));
1459 parse::token::DocComment(..) => {
1460 hardbreak(&mut self.s)
1465 TokenTree::Delimited(_, ref delimed) => {
1466 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1467 try!(space(&mut self.s));
1468 try!(self.print_tts(&delimed.tts));
1469 try!(space(&mut self.s));
1470 word(&mut self.s, &token_to_string(&delimed.close_token()))
1472 TokenTree::Sequence(_, ref seq) => {
1473 try!(word(&mut self.s, "$("));
1474 for tt_elt in &seq.tts {
1475 try!(self.print_tt(tt_elt));
1477 try!(word(&mut self.s, ")"));
1478 match seq.separator {
1480 try!(word(&mut self.s, &token_to_string(tk)));
1485 ast::ZeroOrMore => word(&mut self.s, "*"),
1486 ast::OneOrMore => word(&mut self.s, "+"),
1492 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1494 let mut suppress_space = false;
1495 for (i, tt) in tts.iter().enumerate() {
1496 if i != 0 && !suppress_space {
1497 try!(space(&mut self.s));
1499 try!(self.print_tt(tt));
1500 // There should be no space between the module name and the following `::` in paths,
1501 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1502 suppress_space = match tt {
1503 &TokenTree::Token(_, token::Ident(_, token::ModName)) |
1504 &TokenTree::Token(_, token::MatchNt(_, _, _, token::ModName)) |
1505 &TokenTree::Token(_, token::SubstNt(_, token::ModName)) => true,
1512 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1513 try!(self.head(""));
1514 let generics = ast_util::empty_generics();
1515 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1516 match v.node.disr_expr {
1518 try!(space(&mut self.s));
1519 try!(self.word_space("="));
1520 self.print_expr(&**d)
1526 pub fn print_method_sig(&mut self,
1529 vis: ast::Visibility)
1531 self.print_fn(&m.decl,
1537 Some(&m.explicit_self.node),
1541 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1543 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1544 try!(self.hardbreak_if_not_bol());
1545 try!(self.maybe_print_comment(ti.span.lo));
1546 try!(self.print_outer_attributes(&ti.attrs));
1548 ast::ConstTraitItem(ref ty, ref default) => {
1549 try!(self.print_associated_const(ti.ident, &ty,
1550 default.as_ref().map(|expr| &**expr),
1553 ast::MethodTraitItem(ref sig, ref body) => {
1555 try!(self.head(""));
1557 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1558 if let Some(ref body) = *body {
1560 try!(self.print_block_with_attrs(body, &ti.attrs));
1562 try!(word(&mut self.s, ";"));
1565 ast::TypeTraitItem(ref bounds, ref default) => {
1566 try!(self.print_associated_type(ti.ident, Some(bounds),
1567 default.as_ref().map(|ty| &**ty)));
1570 self.ann.post(self, NodeSubItem(ti.id))
1573 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1574 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1575 try!(self.hardbreak_if_not_bol());
1576 try!(self.maybe_print_comment(ii.span.lo));
1577 try!(self.print_outer_attributes(&ii.attrs));
1579 ast::ConstImplItem(ref ty, ref expr) => {
1580 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1582 ast::MethodImplItem(ref sig, ref body) => {
1583 try!(self.head(""));
1584 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1586 try!(self.print_block_with_attrs(body, &ii.attrs));
1588 ast::TypeImplItem(ref ty) => {
1589 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1591 ast::MacImplItem(codemap::Spanned { ref node, .. }) => {
1592 // code copied from ItemMac:
1593 try!(self.print_path(&node.path, false, 0));
1594 try!(word(&mut self.s, "! "));
1595 try!(self.cbox(indent_unit));
1597 try!(self.print_tts(&node.tts[..]));
1598 try!(self.pclose());
1599 try!(word(&mut self.s, ";"));
1603 self.ann.post(self, NodeSubItem(ii.id))
1606 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1607 try!(self.maybe_print_comment(st.span.lo));
1609 ast::StmtDecl(ref decl, _) => {
1610 try!(self.print_decl(&**decl));
1612 ast::StmtExpr(ref expr, _) => {
1613 try!(self.space_if_not_bol());
1614 try!(self.print_expr(&**expr));
1616 ast::StmtSemi(ref expr, _) => {
1617 try!(self.space_if_not_bol());
1618 try!(self.print_expr(&**expr));
1619 try!(word(&mut self.s, ";"));
1621 ast::StmtMac(ref mac, style) => {
1622 try!(self.space_if_not_bol());
1623 let delim = match style {
1624 ast::MacStmtWithBraces => token::Brace,
1627 try!(self.print_mac(&**mac, delim));
1629 ast::MacStmtWithBraces => {}
1630 _ => try!(word(&mut self.s, ";")),
1634 if parse::classify::stmt_ends_with_semi(&st.node) {
1635 try!(word(&mut self.s, ";"));
1637 self.maybe_print_trailing_comment(st.span, None)
1640 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1641 self.print_block_with_attrs(blk, &[])
1644 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1645 self.print_block_unclosed_indent(blk, indent_unit)
1648 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1649 indented: usize) -> io::Result<()> {
1650 self.print_block_maybe_unclosed(blk, indented, &[], false)
1653 pub fn print_block_with_attrs(&mut self,
1655 attrs: &[ast::Attribute]) -> io::Result<()> {
1656 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1659 pub fn print_block_maybe_unclosed(&mut self,
1662 attrs: &[ast::Attribute],
1663 close_box: bool) -> io::Result<()> {
1665 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1666 ast::DefaultBlock => ()
1668 try!(self.maybe_print_comment(blk.span.lo));
1669 try!(self.ann.pre(self, NodeBlock(blk)));
1672 try!(self.print_inner_attributes(attrs));
1674 for st in &blk.stmts {
1675 try!(self.print_stmt(&**st));
1679 try!(self.space_if_not_bol());
1680 try!(self.print_expr(&**expr));
1681 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1685 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1686 self.ann.post(self, NodeBlock(blk))
1689 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1693 // "another else-if"
1694 ast::ExprIf(ref i, ref then, ref e) => {
1695 try!(self.cbox(indent_unit - 1));
1697 try!(word(&mut self.s, " else if "));
1698 try!(self.print_expr(&**i));
1699 try!(space(&mut self.s));
1700 try!(self.print_block(&**then));
1701 self.print_else(e.as_ref().map(|e| &**e))
1703 // "another else-if-let"
1704 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1705 try!(self.cbox(indent_unit - 1));
1707 try!(word(&mut self.s, " else if let "));
1708 try!(self.print_pat(&**pat));
1709 try!(space(&mut self.s));
1710 try!(self.word_space("="));
1711 try!(self.print_expr(&**expr));
1712 try!(space(&mut self.s));
1713 try!(self.print_block(&**then));
1714 self.print_else(e.as_ref().map(|e| &**e))
1717 ast::ExprBlock(ref b) => {
1718 try!(self.cbox(indent_unit - 1));
1720 try!(word(&mut self.s, " else "));
1721 self.print_block(&**b)
1723 // BLEAH, constraints would be great here
1725 panic!("print_if saw if with weird alternative");
1733 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1734 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1735 try!(self.head("if"));
1736 try!(self.print_expr(test));
1737 try!(space(&mut self.s));
1738 try!(self.print_block(blk));
1739 self.print_else(elseopt)
1742 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1743 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1744 try!(self.head("if let"));
1745 try!(self.print_pat(pat));
1746 try!(space(&mut self.s));
1747 try!(self.word_space("="));
1748 try!(self.print_expr(expr));
1749 try!(space(&mut self.s));
1750 try!(self.print_block(blk));
1751 self.print_else(elseopt)
1754 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1756 try!(self.print_path(&m.node.path, false, 0));
1757 try!(word(&mut self.s, "!"));
1759 token::Paren => try!(self.popen()),
1760 token::Bracket => try!(word(&mut self.s, "[")),
1761 token::Brace => try!(self.bopen()),
1763 try!(self.print_tts(&m.node.tts));
1765 token::Paren => self.pclose(),
1766 token::Bracket => word(&mut self.s, "]"),
1767 token::Brace => self.bclose(m.span),
1772 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1774 try!(self.commasep_exprs(Inconsistent, args));
1778 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1779 binop: ast::BinOp) -> bool {
1780 match sub_expr.node {
1781 ast::ExprBinary(ref sub_op, _, _) => {
1782 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1783 AssocOp::from_ast_binop(binop.node).precedence() {
1793 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1794 let needs_par = needs_parentheses(expr);
1798 try!(self.print_expr(expr));
1800 try!(self.pclose());
1805 fn print_expr_in_place(&mut self,
1807 expr: &ast::Expr) -> io::Result<()> {
1808 try!(self.print_expr_maybe_paren(place));
1809 try!(space(&mut self.s));
1810 try!(self.word_space("<-"));
1811 self.print_expr_maybe_paren(expr)
1814 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1815 try!(self.ibox(indent_unit));
1816 try!(word(&mut self.s, "["));
1817 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1818 try!(word(&mut self.s, "]"));
1822 fn print_expr_repeat(&mut self,
1823 element: &ast::Expr,
1824 count: &ast::Expr) -> io::Result<()> {
1825 try!(self.ibox(indent_unit));
1826 try!(word(&mut self.s, "["));
1827 try!(self.print_expr(element));
1828 try!(self.word_space(";"));
1829 try!(self.print_expr(count));
1830 try!(word(&mut self.s, "]"));
1834 fn print_expr_struct(&mut self,
1836 fields: &[ast::Field],
1837 wth: &Option<P<ast::Expr>>) -> io::Result<()> {
1838 try!(self.print_path(path, true, 0));
1839 try!(word(&mut self.s, "{"));
1840 try!(self.commasep_cmnt(
1844 try!(s.ibox(indent_unit));
1845 try!(s.print_ident(field.ident.node));
1846 try!(s.word_space(":"));
1847 try!(s.print_expr(&*field.expr));
1853 try!(self.ibox(indent_unit));
1854 if !fields.is_empty() {
1855 try!(word(&mut self.s, ","));
1856 try!(space(&mut self.s));
1858 try!(word(&mut self.s, ".."));
1859 try!(self.print_expr(&**expr));
1862 _ => if !fields.is_empty() {
1863 try!(word(&mut self.s, ","))
1866 try!(word(&mut self.s, "}"));
1870 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1872 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1873 if exprs.len() == 1 {
1874 try!(word(&mut self.s, ","));
1879 fn print_expr_call(&mut self,
1881 args: &[P<ast::Expr>]) -> io::Result<()> {
1882 try!(self.print_expr_maybe_paren(func));
1883 self.print_call_post(args)
1886 fn print_expr_method_call(&mut self,
1887 ident: ast::SpannedIdent,
1889 args: &[P<ast::Expr>]) -> io::Result<()> {
1890 let base_args = &args[1..];
1891 try!(self.print_expr(&*args[0]));
1892 try!(word(&mut self.s, "."));
1893 try!(self.print_ident(ident.node));
1894 if !tys.is_empty() {
1895 try!(word(&mut self.s, "::<"));
1896 try!(self.commasep(Inconsistent, tys,
1897 |s, ty| s.print_type(&**ty)));
1898 try!(word(&mut self.s, ">"));
1900 self.print_call_post(base_args)
1903 fn print_expr_binary(&mut self,
1906 rhs: &ast::Expr) -> io::Result<()> {
1907 if self.check_expr_bin_needs_paren(lhs, op) {
1908 try!(self.print_expr_maybe_paren(lhs));
1910 try!(self.print_expr(lhs));
1912 try!(space(&mut self.s));
1913 try!(self.word_space(ast_util::binop_to_string(op.node)));
1914 if self.check_expr_bin_needs_paren(rhs, op) {
1915 self.print_expr_maybe_paren(rhs)
1917 self.print_expr(rhs)
1921 fn print_expr_unary(&mut self,
1923 expr: &ast::Expr) -> io::Result<()> {
1924 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1925 self.print_expr_maybe_paren(expr)
1928 fn print_expr_addr_of(&mut self,
1929 mutability: ast::Mutability,
1930 expr: &ast::Expr) -> io::Result<()> {
1931 try!(word(&mut self.s, "&"));
1932 try!(self.print_mutability(mutability));
1933 self.print_expr_maybe_paren(expr)
1936 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1937 try!(self.maybe_print_comment(expr.span.lo));
1938 try!(self.ibox(indent_unit));
1939 try!(self.ann.pre(self, NodeExpr(expr)));
1941 ast::ExprBox(ref expr) => {
1942 try!(self.word_space("box"));
1943 try!(self.print_expr(expr));
1945 ast::ExprInPlace(ref place, ref expr) => {
1946 try!(self.print_expr_in_place(place, expr));
1948 ast::ExprVec(ref exprs) => {
1949 try!(self.print_expr_vec(&exprs[..]));
1951 ast::ExprRepeat(ref element, ref count) => {
1952 try!(self.print_expr_repeat(&**element, &**count));
1954 ast::ExprStruct(ref path, ref fields, ref wth) => {
1955 try!(self.print_expr_struct(path, &fields[..], wth));
1957 ast::ExprTup(ref exprs) => {
1958 try!(self.print_expr_tup(&exprs[..]));
1960 ast::ExprCall(ref func, ref args) => {
1961 try!(self.print_expr_call(&**func, &args[..]));
1963 ast::ExprMethodCall(ident, ref tys, ref args) => {
1964 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1966 ast::ExprBinary(op, ref lhs, ref rhs) => {
1967 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1969 ast::ExprUnary(op, ref expr) => {
1970 try!(self.print_expr_unary(op, &**expr));
1972 ast::ExprAddrOf(m, ref expr) => {
1973 try!(self.print_expr_addr_of(m, &**expr));
1975 ast::ExprLit(ref lit) => {
1976 try!(self.print_literal(&**lit));
1978 ast::ExprCast(ref expr, ref ty) => {
1979 if let ast::ExprCast(..) = expr.node {
1980 try!(self.print_expr(&**expr));
1982 try!(self.print_expr_maybe_paren(&**expr));
1984 try!(space(&mut self.s));
1985 try!(self.word_space("as"));
1986 try!(self.print_type(&**ty));
1988 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1989 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1991 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1992 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1994 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1995 if let Some(ident) = opt_ident {
1996 try!(self.print_ident(ident));
1997 try!(self.word_space(":"));
1999 try!(self.head("while"));
2000 try!(self.print_expr(&**test));
2001 try!(space(&mut self.s));
2002 try!(self.print_block(&**blk));
2004 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2005 if let Some(ident) = opt_ident {
2006 try!(self.print_ident(ident));
2007 try!(self.word_space(":"));
2009 try!(self.head("while let"));
2010 try!(self.print_pat(&**pat));
2011 try!(space(&mut self.s));
2012 try!(self.word_space("="));
2013 try!(self.print_expr(&**expr));
2014 try!(space(&mut self.s));
2015 try!(self.print_block(&**blk));
2017 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2018 if let Some(ident) = opt_ident {
2019 try!(self.print_ident(ident));
2020 try!(self.word_space(":"));
2022 try!(self.head("for"));
2023 try!(self.print_pat(&**pat));
2024 try!(space(&mut self.s));
2025 try!(self.word_space("in"));
2026 try!(self.print_expr(&**iter));
2027 try!(space(&mut self.s));
2028 try!(self.print_block(&**blk));
2030 ast::ExprLoop(ref blk, opt_ident) => {
2031 if let Some(ident) = opt_ident {
2032 try!(self.print_ident(ident));
2033 try!(self.word_space(":"));
2035 try!(self.head("loop"));
2036 try!(space(&mut self.s));
2037 try!(self.print_block(&**blk));
2039 ast::ExprMatch(ref expr, ref arms) => {
2040 try!(self.cbox(indent_unit));
2042 try!(self.word_nbsp("match"));
2043 try!(self.print_expr(&**expr));
2044 try!(space(&mut self.s));
2047 try!(self.print_arm(arm));
2049 try!(self.bclose_(expr.span, indent_unit));
2051 ast::ExprClosure(capture_clause, ref decl, ref body) => {
2052 try!(self.print_capture_clause(capture_clause));
2054 try!(self.print_fn_block_args(&**decl));
2055 try!(space(&mut self.s));
2057 let default_return = match decl.output {
2058 ast::DefaultReturn(..) => true,
2062 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2063 try!(self.print_block_unclosed(&**body));
2065 // we extract the block, so as not to create another set of boxes
2066 match body.expr.as_ref().unwrap().node {
2067 ast::ExprBlock(ref blk) => {
2068 try!(self.print_block_unclosed(&**blk));
2071 // this is a bare expression
2072 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
2073 try!(self.end()); // need to close a box
2077 // a box will be closed by print_expr, but we didn't want an overall
2078 // wrapper so we closed the corresponding opening. so create an
2079 // empty box to satisfy the close.
2082 ast::ExprBlock(ref blk) => {
2083 // containing cbox, will be closed by print-block at }
2084 try!(self.cbox(indent_unit));
2085 // head-box, will be closed by print-block after {
2087 try!(self.print_block(&**blk));
2089 ast::ExprAssign(ref lhs, ref rhs) => {
2090 try!(self.print_expr(&**lhs));
2091 try!(space(&mut self.s));
2092 try!(self.word_space("="));
2093 try!(self.print_expr(&**rhs));
2095 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
2096 try!(self.print_expr(&**lhs));
2097 try!(space(&mut self.s));
2098 try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
2099 try!(self.word_space("="));
2100 try!(self.print_expr(&**rhs));
2102 ast::ExprField(ref expr, id) => {
2103 try!(self.print_expr(&**expr));
2104 try!(word(&mut self.s, "."));
2105 try!(self.print_ident(id.node));
2107 ast::ExprTupField(ref expr, id) => {
2108 try!(self.print_expr(&**expr));
2109 try!(word(&mut self.s, "."));
2110 try!(self.print_usize(id.node));
2112 ast::ExprIndex(ref expr, ref index) => {
2113 try!(self.print_expr(&**expr));
2114 try!(word(&mut self.s, "["));
2115 try!(self.print_expr(&**index));
2116 try!(word(&mut self.s, "]"));
2118 ast::ExprRange(ref start, ref end) => {
2119 if let &Some(ref e) = start {
2120 try!(self.print_expr(&**e));
2122 try!(word(&mut self.s, ".."));
2123 if let &Some(ref e) = end {
2124 try!(self.print_expr(&**e));
2127 ast::ExprPath(None, ref path) => {
2128 try!(self.print_path(path, true, 0))
2130 ast::ExprPath(Some(ref qself), ref path) => {
2131 try!(self.print_qpath(path, qself, true))
2133 ast::ExprBreak(opt_ident) => {
2134 try!(word(&mut self.s, "break"));
2135 try!(space(&mut self.s));
2136 if let Some(ident) = opt_ident {
2137 try!(self.print_ident(ident.node));
2138 try!(space(&mut self.s));
2141 ast::ExprAgain(opt_ident) => {
2142 try!(word(&mut self.s, "continue"));
2143 try!(space(&mut self.s));
2144 if let Some(ident) = opt_ident {
2145 try!(self.print_ident(ident.node));
2146 try!(space(&mut self.s))
2149 ast::ExprRet(ref result) => {
2150 try!(word(&mut self.s, "return"));
2153 try!(word(&mut self.s, " "));
2154 try!(self.print_expr(&**expr));
2159 ast::ExprInlineAsm(ref a) => {
2160 try!(word(&mut self.s, "asm!"));
2162 try!(self.print_string(&a.asm, a.asm_str_style));
2163 try!(self.word_space(":"));
2165 try!(self.commasep(Inconsistent, &a.outputs,
2166 |s, &(ref co, ref o, is_rw)| {
2167 match co.slice_shift_char() {
2168 Some(('=', operand)) if is_rw => {
2169 try!(s.print_string(&format!("+{}", operand),
2172 _ => try!(s.print_string(&co, ast::CookedStr))
2175 try!(s.print_expr(&**o));
2179 try!(space(&mut self.s));
2180 try!(self.word_space(":"));
2182 try!(self.commasep(Inconsistent, &a.inputs,
2183 |s, &(ref co, ref o)| {
2184 try!(s.print_string(&co, ast::CookedStr));
2186 try!(s.print_expr(&**o));
2190 try!(space(&mut self.s));
2191 try!(self.word_space(":"));
2193 try!(self.commasep(Inconsistent, &a.clobbers,
2195 try!(s.print_string(&co, ast::CookedStr));
2199 let mut options = vec!();
2201 options.push("volatile");
2204 options.push("alignstack");
2206 if a.dialect == ast::AsmDialect::Intel {
2207 options.push("intel");
2210 if !options.is_empty() {
2211 try!(space(&mut self.s));
2212 try!(self.word_space(":"));
2213 try!(self.commasep(Inconsistent, &*options,
2215 try!(s.print_string(co, ast::CookedStr));
2220 try!(self.pclose());
2222 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
2223 ast::ExprParen(ref e) => {
2225 try!(self.print_expr(&**e));
2226 try!(self.pclose());
2229 try!(self.ann.post(self, NodeExpr(expr)));
2233 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2234 try!(self.print_pat(&*loc.pat));
2235 if let Some(ref ty) = loc.ty {
2236 try!(self.word_space(":"));
2237 try!(self.print_type(&**ty));
2242 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2243 try!(self.maybe_print_comment(decl.span.lo));
2245 ast::DeclLocal(ref loc) => {
2246 try!(self.space_if_not_bol());
2247 try!(self.ibox(indent_unit));
2248 try!(self.word_nbsp("let"));
2250 try!(self.ibox(indent_unit));
2251 try!(self.print_local_decl(&**loc));
2253 if let Some(ref init) = loc.init {
2255 try!(self.word_space("="));
2256 try!(self.print_expr(&**init));
2260 ast::DeclItem(ref item) => self.print_item(&**item)
2264 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2265 try!(word(&mut self.s, &ident.name.as_str()));
2266 self.ann.post(self, NodeIdent(&ident))
2269 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2270 word(&mut self.s, &i.to_string())
2273 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2274 try!(word(&mut self.s, &name.as_str()));
2275 self.ann.post(self, NodeName(&name))
2278 pub fn print_for_decl(&mut self, loc: &ast::Local,
2279 coll: &ast::Expr) -> io::Result<()> {
2280 try!(self.print_local_decl(loc));
2281 try!(space(&mut self.s));
2282 try!(self.word_space("in"));
2283 self.print_expr(coll)
2286 fn print_path(&mut self,
2288 colons_before_params: bool,
2292 try!(self.maybe_print_comment(path.span.lo));
2294 let mut first = !path.global;
2295 for segment in &path.segments[..path.segments.len()-depth] {
2299 try!(word(&mut self.s, "::"))
2302 try!(self.print_ident(segment.identifier));
2304 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2310 fn print_qpath(&mut self,
2313 colons_before_params: bool)
2316 try!(word(&mut self.s, "<"));
2317 try!(self.print_type(&qself.ty));
2318 if qself.position > 0 {
2319 try!(space(&mut self.s));
2320 try!(self.word_space("as"));
2321 let depth = path.segments.len() - qself.position;
2322 try!(self.print_path(&path, false, depth));
2324 try!(word(&mut self.s, ">"));
2325 try!(word(&mut self.s, "::"));
2326 let item_segment = path.segments.last().unwrap();
2327 try!(self.print_ident(item_segment.identifier));
2328 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2331 fn print_path_parameters(&mut self,
2332 parameters: &ast::PathParameters,
2333 colons_before_params: bool)
2336 if parameters.is_empty() {
2340 if colons_before_params {
2341 try!(word(&mut self.s, "::"))
2345 ast::AngleBracketedParameters(ref data) => {
2346 try!(word(&mut self.s, "<"));
2348 let mut comma = false;
2349 for lifetime in &data.lifetimes {
2351 try!(self.word_space(","))
2353 try!(self.print_lifetime(lifetime));
2357 if !data.types.is_empty() {
2359 try!(self.word_space(","))
2364 |s, ty| s.print_type(&**ty)));
2368 for binding in data.bindings.iter() {
2370 try!(self.word_space(","))
2372 try!(self.print_ident(binding.ident));
2373 try!(space(&mut self.s));
2374 try!(self.word_space("="));
2375 try!(self.print_type(&*binding.ty));
2379 try!(word(&mut self.s, ">"))
2382 ast::ParenthesizedParameters(ref data) => {
2383 try!(word(&mut self.s, "("));
2387 |s, ty| s.print_type(&**ty)));
2388 try!(word(&mut self.s, ")"));
2393 try!(self.space_if_not_bol());
2394 try!(self.word_space("->"));
2395 try!(self.print_type(&**ty));
2404 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2405 try!(self.maybe_print_comment(pat.span.lo));
2406 try!(self.ann.pre(self, NodePat(pat)));
2407 /* Pat isn't normalized, but the beauty of it
2408 is that it doesn't matter */
2410 ast::PatWild => try!(word(&mut self.s, "_")),
2411 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2412 match binding_mode {
2413 ast::BindByRef(mutbl) => {
2414 try!(self.word_nbsp("ref"));
2415 try!(self.print_mutability(mutbl));
2417 ast::BindByValue(ast::MutImmutable) => {}
2418 ast::BindByValue(ast::MutMutable) => {
2419 try!(self.word_nbsp("mut"));
2422 try!(self.print_ident(path1.node));
2425 try!(word(&mut self.s, "@"));
2426 try!(self.print_pat(&**p));
2431 ast::PatEnum(ref path, ref args_) => {
2432 try!(self.print_path(path, true, 0));
2434 None => try!(word(&mut self.s, "(..)")),
2436 if !args.is_empty() {
2438 try!(self.commasep(Inconsistent, &args[..],
2439 |s, p| s.print_pat(&**p)));
2440 try!(self.pclose());
2445 ast::PatQPath(ref qself, ref path) => {
2446 try!(self.print_qpath(path, qself, false));
2448 ast::PatStruct(ref path, ref fields, etc) => {
2449 try!(self.print_path(path, true, 0));
2451 try!(self.word_space("{"));
2452 try!(self.commasep_cmnt(
2453 Consistent, &fields[..],
2455 try!(s.cbox(indent_unit));
2456 if !f.node.is_shorthand {
2457 try!(s.print_ident(f.node.ident));
2458 try!(s.word_nbsp(":"));
2460 try!(s.print_pat(&*f.node.pat));
2463 |f| f.node.pat.span));
2465 if !fields.is_empty() { try!(self.word_space(",")); }
2466 try!(word(&mut self.s, ".."));
2468 try!(space(&mut self.s));
2469 try!(word(&mut self.s, "}"));
2471 ast::PatTup(ref elts) => {
2473 try!(self.commasep(Inconsistent,
2475 |s, p| s.print_pat(&**p)));
2476 if elts.len() == 1 {
2477 try!(word(&mut self.s, ","));
2479 try!(self.pclose());
2481 ast::PatBox(ref inner) => {
2482 try!(word(&mut self.s, "box "));
2483 try!(self.print_pat(&**inner));
2485 ast::PatRegion(ref inner, mutbl) => {
2486 try!(word(&mut self.s, "&"));
2487 if mutbl == ast::MutMutable {
2488 try!(word(&mut self.s, "mut "));
2490 try!(self.print_pat(&**inner));
2492 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2493 ast::PatRange(ref begin, ref end) => {
2494 try!(self.print_expr(&**begin));
2495 try!(space(&mut self.s));
2496 try!(word(&mut self.s, "..."));
2497 try!(self.print_expr(&**end));
2499 ast::PatVec(ref before, ref slice, ref after) => {
2500 try!(word(&mut self.s, "["));
2501 try!(self.commasep(Inconsistent,
2503 |s, p| s.print_pat(&**p)));
2504 if let Some(ref p) = *slice {
2505 if !before.is_empty() { try!(self.word_space(",")); }
2506 if p.node != ast::PatWild {
2507 try!(self.print_pat(&**p));
2509 try!(word(&mut self.s, ".."));
2510 if !after.is_empty() { try!(self.word_space(",")); }
2512 try!(self.commasep(Inconsistent,
2514 |s, p| s.print_pat(&**p)));
2515 try!(word(&mut self.s, "]"));
2517 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2519 self.ann.post(self, NodePat(pat))
2522 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2523 // I have no idea why this check is necessary, but here it
2525 if arm.attrs.is_empty() {
2526 try!(space(&mut self.s));
2528 try!(self.cbox(indent_unit));
2530 try!(self.print_outer_attributes(&arm.attrs));
2531 let mut first = true;
2532 for p in &arm.pats {
2536 try!(space(&mut self.s));
2537 try!(self.word_space("|"));
2539 try!(self.print_pat(&**p));
2541 try!(space(&mut self.s));
2542 if let Some(ref e) = arm.guard {
2543 try!(self.word_space("if"));
2544 try!(self.print_expr(&**e));
2545 try!(space(&mut self.s));
2547 try!(self.word_space("=>"));
2549 match arm.body.node {
2550 ast::ExprBlock(ref blk) => {
2551 // the block will close the pattern's ibox
2552 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2554 // If it is a user-provided unsafe block, print a comma after it
2555 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2556 try!(word(&mut self.s, ","));
2560 try!(self.end()); // close the ibox for the pattern
2561 try!(self.print_expr(&*arm.body));
2562 try!(word(&mut self.s, ","));
2565 self.end() // close enclosing cbox
2568 // Returns whether it printed anything
2569 fn print_explicit_self(&mut self,
2570 explicit_self: &ast::ExplicitSelf_,
2571 mutbl: ast::Mutability) -> io::Result<bool> {
2572 try!(self.print_mutability(mutbl));
2573 match *explicit_self {
2574 ast::SelfStatic => { return Ok(false); }
2575 ast::SelfValue(_) => {
2576 try!(word(&mut self.s, "self"));
2578 ast::SelfRegion(ref lt, m, _) => {
2579 try!(word(&mut self.s, "&"));
2580 try!(self.print_opt_lifetime(lt));
2581 try!(self.print_mutability(m));
2582 try!(word(&mut self.s, "self"));
2584 ast::SelfExplicit(ref typ, _) => {
2585 try!(word(&mut self.s, "self"));
2586 try!(self.word_space(":"));
2587 try!(self.print_type(&**typ));
2593 pub fn print_fn(&mut self,
2595 unsafety: ast::Unsafety,
2596 constness: ast::Constness,
2598 name: Option<ast::Ident>,
2599 generics: &ast::Generics,
2600 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2601 vis: ast::Visibility) -> io::Result<()> {
2602 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2604 if let Some(name) = name {
2606 try!(self.print_ident(name));
2608 try!(self.print_generics(generics));
2609 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2610 self.print_where_clause(&generics.where_clause)
2613 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2614 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2616 // It is unfortunate to duplicate the commasep logic, but we want the
2617 // self type and the args all in the same box.
2618 try!(self.rbox(0, Inconsistent));
2619 let mut first = true;
2620 if let Some(explicit_self) = opt_explicit_self {
2621 let m = match explicit_self {
2622 &ast::SelfStatic => ast::MutImmutable,
2623 _ => match decl.inputs[0].pat.node {
2624 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2625 _ => ast::MutImmutable
2628 first = !try!(self.print_explicit_self(explicit_self, m));
2631 // HACK(eddyb) ignore the separately printed self argument.
2632 let args = if first {
2639 if first { first = false; } else { try!(self.word_space(",")); }
2640 try!(self.print_arg(arg));
2646 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2647 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2650 try!(self.print_fn_args(decl, opt_explicit_self));
2652 try!(word(&mut self.s, ", ..."));
2654 try!(self.pclose());
2656 self.print_fn_output(decl)
2659 pub fn print_fn_block_args(
2663 try!(word(&mut self.s, "|"));
2664 try!(self.print_fn_args(decl, None));
2665 try!(word(&mut self.s, "|"));
2667 if let ast::DefaultReturn(..) = decl.output {
2671 try!(self.space_if_not_bol());
2672 try!(self.word_space("->"));
2674 ast::Return(ref ty) => {
2675 try!(self.print_type(&**ty));
2676 self.maybe_print_comment(ty.span.lo)
2678 ast::DefaultReturn(..) => unreachable!(),
2679 ast::NoReturn(span) => {
2680 try!(self.word_nbsp("!"));
2681 self.maybe_print_comment(span.lo)
2686 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2688 match capture_clause {
2689 ast::CaptureByValue => self.word_space("move"),
2690 ast::CaptureByRef => Ok(()),
2694 pub fn print_bounds(&mut self,
2696 bounds: &[ast::TyParamBound])
2698 if !bounds.is_empty() {
2699 try!(word(&mut self.s, prefix));
2700 let mut first = true;
2701 for bound in bounds {
2706 try!(self.word_space("+"));
2710 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2711 self.print_poly_trait_ref(tref)
2713 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2714 try!(word(&mut self.s, "?"));
2715 self.print_poly_trait_ref(tref)
2717 RegionTyParamBound(ref lt) => {
2718 self.print_lifetime(lt)
2728 pub fn print_lifetime(&mut self,
2729 lifetime: &ast::Lifetime)
2732 self.print_name(lifetime.name)
2735 pub fn print_lifetime_def(&mut self,
2736 lifetime: &ast::LifetimeDef)
2739 try!(self.print_lifetime(&lifetime.lifetime));
2741 for v in &lifetime.bounds {
2742 try!(word(&mut self.s, sep));
2743 try!(self.print_lifetime(v));
2749 pub fn print_generics(&mut self,
2750 generics: &ast::Generics)
2753 let total = generics.lifetimes.len() + generics.ty_params.len();
2758 try!(word(&mut self.s, "<"));
2760 let mut ints = Vec::new();
2765 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2766 if idx < generics.lifetimes.len() {
2767 let lifetime = &generics.lifetimes[idx];
2768 s.print_lifetime_def(lifetime)
2770 let idx = idx - generics.lifetimes.len();
2771 let param = &generics.ty_params[idx];
2772 s.print_ty_param(param)
2776 try!(word(&mut self.s, ">"));
2780 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2781 try!(self.print_ident(param.ident));
2782 try!(self.print_bounds(":", ¶m.bounds));
2783 match param.default {
2784 Some(ref default) => {
2785 try!(space(&mut self.s));
2786 try!(self.word_space("="));
2787 self.print_type(&**default)
2793 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2795 if where_clause.predicates.is_empty() {
2799 try!(space(&mut self.s));
2800 try!(self.word_space("where"));
2802 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2804 try!(self.word_space(","));
2808 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2812 try!(self.print_formal_lifetime_list(bound_lifetimes));
2813 try!(self.print_type(&**bounded_ty));
2814 try!(self.print_bounds(":", bounds));
2816 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2819 try!(self.print_lifetime(lifetime));
2820 try!(word(&mut self.s, ":"));
2822 for (i, bound) in bounds.iter().enumerate() {
2823 try!(self.print_lifetime(bound));
2826 try!(word(&mut self.s, ":"));
2830 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2831 try!(self.print_path(path, false, 0));
2832 try!(space(&mut self.s));
2833 try!(self.word_space("="));
2834 try!(self.print_type(&**ty));
2842 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2844 ast::ViewPathSimple(ident, ref path) => {
2845 try!(self.print_path(path, false, 0));
2847 if path.segments.last().unwrap().identifier.name !=
2849 try!(space(&mut self.s));
2850 try!(self.word_space("as"));
2851 try!(self.print_ident(ident));
2857 ast::ViewPathGlob(ref path) => {
2858 try!(self.print_path(path, false, 0));
2859 word(&mut self.s, "::*")
2862 ast::ViewPathList(ref path, ref idents) => {
2863 if path.segments.is_empty() {
2864 try!(word(&mut self.s, "{"));
2866 try!(self.print_path(path, false, 0));
2867 try!(word(&mut self.s, "::{"));
2869 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2871 ast::PathListIdent { name, rename, .. } => {
2872 try!(s.print_ident(name));
2873 if let Some(ident) = rename {
2874 try!(space(&mut s.s));
2875 try!(s.word_space("as"));
2876 try!(s.print_ident(ident));
2880 ast::PathListMod { rename, .. } => {
2881 try!(word(&mut s.s, "self"));
2882 if let Some(ident) = rename {
2883 try!(space(&mut s.s));
2884 try!(s.word_space("as"));
2885 try!(s.print_ident(ident));
2891 word(&mut self.s, "}")
2896 pub fn print_mutability(&mut self,
2897 mutbl: ast::Mutability) -> io::Result<()> {
2899 ast::MutMutable => self.word_nbsp("mut"),
2900 ast::MutImmutable => Ok(()),
2904 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2905 try!(self.print_mutability(mt.mutbl));
2906 self.print_type(&*mt.ty)
2909 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2910 try!(self.ibox(indent_unit));
2911 match input.ty.node {
2912 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2914 match input.pat.node {
2915 ast::PatIdent(_, ref path1, _) if
2917 parse::token::special_idents::invalid.name => {
2921 try!(self.print_pat(&*input.pat));
2922 try!(word(&mut self.s, ":"));
2923 try!(space(&mut self.s));
2926 try!(self.print_type(&*input.ty));
2932 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2933 if let ast::DefaultReturn(..) = decl.output {
2937 try!(self.space_if_not_bol());
2938 try!(self.ibox(indent_unit));
2939 try!(self.word_space("->"));
2942 try!(self.word_nbsp("!")),
2943 ast::DefaultReturn(..) => unreachable!(),
2944 ast::Return(ref ty) =>
2945 try!(self.print_type(&**ty))
2950 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2955 pub fn print_ty_fn(&mut self,
2957 unsafety: ast::Unsafety,
2959 name: Option<ast::Ident>,
2960 generics: &ast::Generics,
2961 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2963 try!(self.ibox(indent_unit));
2964 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2965 try!(word(&mut self.s, "for"));
2966 try!(self.print_generics(generics));
2968 let generics = ast::Generics {
2969 lifetimes: Vec::new(),
2970 ty_params: OwnedSlice::empty(),
2971 where_clause: ast::WhereClause {
2972 id: ast::DUMMY_NODE_ID,
2973 predicates: Vec::new(),
2976 try!(self.print_fn(decl,
2978 ast::Constness::NotConst,
2987 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2988 next_pos: Option<BytePos>)
2990 let cm = match self.cm {
2994 match self.next_comment() {
2996 if (*cmnt).style != comments::Trailing { return Ok(()) }
2997 let span_line = cm.lookup_char_pos(span.hi);
2998 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2999 let mut next = (*cmnt).pos + BytePos(1);
3000 match next_pos { None => (), Some(p) => next = p }
3001 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3002 span_line.line == comment_line.line {
3003 try!(self.print_comment(cmnt));
3004 self.cur_cmnt_and_lit.cur_cmnt += 1;
3012 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3013 // If there aren't any remaining comments, then we need to manually
3014 // make sure there is a line break at the end.
3015 if self.next_comment().is_none() {
3016 try!(hardbreak(&mut self.s));
3019 match self.next_comment() {
3021 try!(self.print_comment(cmnt));
3022 self.cur_cmnt_and_lit.cur_cmnt += 1;
3030 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3031 opt_abi: Option<abi::Abi>)
3034 Some(abi::Rust) => Ok(()),
3036 try!(self.word_nbsp("extern"));
3037 self.word_nbsp(&abi.to_string())
3043 pub fn print_extern_opt_abi(&mut self,
3044 opt_abi: Option<abi::Abi>) -> io::Result<()> {
3047 try!(self.word_nbsp("extern"));
3048 self.word_nbsp(&abi.to_string())
3054 pub fn print_fn_header_info(&mut self,
3055 unsafety: ast::Unsafety,
3056 constness: ast::Constness,
3058 vis: ast::Visibility) -> io::Result<()> {
3059 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3062 ast::Constness::NotConst => {}
3063 ast::Constness::Const => try!(self.word_nbsp("const"))
3066 try!(self.print_unsafety(unsafety));
3068 if abi != abi::Rust {
3069 try!(self.word_nbsp("extern"));
3070 try!(self.word_nbsp(&abi.to_string()));
3073 word(&mut self.s, "fn")
3076 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3078 ast::Unsafety::Normal => Ok(()),
3079 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3084 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3096 fn test_fun_to_string() {
3097 let abba_ident = token::str_to_ident("abba");
3099 let decl = ast::FnDecl {
3101 output: ast::DefaultReturn(codemap::DUMMY_SP),
3104 let generics = ast_util::empty_generics();
3105 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3106 ast::Constness::NotConst,
3113 fn test_variant_to_string() {
3114 let ident = token::str_to_ident("principal_skinner");
3116 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3119 // making this up as I go.... ?
3120 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3124 let varstr = variant_to_string(&var);
3125 assert_eq!(varstr, "principal_skinner");
3129 fn test_signed_int_to_string() {
3130 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3131 let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3132 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3133 lit_to_string(&codemap::dummy_spanned(neg_int)));