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),
312 pub fn ty_to_string(ty: &ast::Ty) -> String {
313 to_string(|s| s.print_type(ty))
316 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
317 to_string(|s| s.print_bounds("", bounds))
320 pub fn pat_to_string(pat: &ast::Pat) -> String {
321 to_string(|s| s.print_pat(pat))
324 pub fn arm_to_string(arm: &ast::Arm) -> String {
325 to_string(|s| s.print_arm(arm))
328 pub fn expr_to_string(e: &ast::Expr) -> String {
329 to_string(|s| s.print_expr(e))
332 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
333 to_string(|s| s.print_lifetime(e))
336 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
337 to_string(|s| s.print_tt(tt))
340 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
341 to_string(|s| s.print_tts(tts))
344 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
345 to_string(|s| s.print_stmt(stmt))
348 pub fn attr_to_string(attr: &ast::Attribute) -> String {
349 to_string(|s| s.print_attribute(attr))
352 pub fn item_to_string(i: &ast::Item) -> String {
353 to_string(|s| s.print_item(i))
356 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
357 to_string(|s| s.print_impl_item(i))
360 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
361 to_string(|s| s.print_trait_item(i))
364 pub fn generics_to_string(generics: &ast::Generics) -> String {
365 to_string(|s| s.print_generics(generics))
368 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
369 to_string(|s| s.print_where_clause(i))
372 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
373 to_string(|s| s.print_fn_block_args(p))
376 pub fn path_to_string(p: &ast::Path) -> String {
377 to_string(|s| s.print_path(p, false, 0))
380 pub fn ident_to_string(id: ast::Ident) -> String {
381 to_string(|s| s.print_ident(id))
384 pub fn fun_to_string(decl: &ast::FnDecl,
385 unsafety: ast::Unsafety,
386 constness: ast::Constness,
388 opt_explicit_self: Option<&ast::ExplicitSelf_>,
389 generics: &ast::Generics)
393 try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
394 generics, opt_explicit_self, ast::Inherited));
395 try!(s.end()); // Close the head box
396 s.end() // Close the outer box
400 pub fn block_to_string(blk: &ast::Block) -> String {
402 // containing cbox, will be closed by print-block at }
403 try!(s.cbox(indent_unit));
404 // head-ibox, will be closed by print-block after {
410 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
411 to_string(|s| s.print_meta_item(mi))
414 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
415 to_string(|s| s.print_attribute(attr))
418 pub fn lit_to_string(l: &ast::Lit) -> String {
419 to_string(|s| s.print_literal(l))
422 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
423 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
426 pub fn variant_to_string(var: &ast::Variant) -> String {
427 to_string(|s| s.print_variant(var))
430 pub fn arg_to_string(arg: &ast::Arg) -> String {
431 to_string(|s| s.print_arg(arg))
434 pub fn mac_to_string(arg: &ast::Mac) -> String {
435 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
438 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
440 ast::Public => format!("pub {}", s),
441 ast::Inherited => s.to_string()
445 fn needs_parentheses(expr: &ast::Expr) -> bool {
447 ast::ExprAssign(..) | ast::ExprBinary(..) |
448 ast::ExprClosure(..) |
449 ast::ExprAssignOp(..) | ast::ExprCast(..) |
450 ast::ExprInPlace(..) => true,
455 pub trait PrintState<'a> {
456 fn writer(&mut self) -> &mut pp::Printer<'a>;
457 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
458 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
459 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
460 fn literals(&self) -> &Option<Vec<comments::Literal>>;
462 fn word_space(&mut self, w: &str) -> io::Result<()> {
463 try!(word(self.writer(), w));
467 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
469 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
471 fn is_begin(&mut self) -> bool {
472 match self.writer().last_token() {
473 pp::Token::Begin(_) => true,
478 fn is_end(&mut self) -> bool {
479 match self.writer().last_token() {
480 pp::Token::End => true,
485 // is this the beginning of a line?
486 fn is_bol(&mut self) -> bool {
487 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
490 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
492 try!(hardbreak(self.writer()))
498 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
499 self.boxes().push(b);
500 pp::rbox(self.writer(), u, b)
503 fn ibox(&mut self, u: usize) -> io::Result<()> {
504 self.boxes().push(pp::Breaks::Inconsistent);
505 pp::ibox(self.writer(), u)
508 fn end(&mut self) -> io::Result<()> {
509 self.boxes().pop().unwrap();
510 pp::end(self.writer())
513 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
514 where F: FnMut(&mut Self, &T) -> io::Result<()>,
516 try!(self.rbox(0, b));
517 let mut first = true;
519 if first { first = false; } else { try!(self.word_space(",")); }
525 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
526 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
528 let mut result = None;
530 if let &Some(ref lits) = self.literals()
532 while cur_lit < lits.len() {
533 let ltrl = (*lits)[cur_lit].clone();
534 if ltrl.pos > pos { break; }
543 self.cur_cmnt_and_lit().cur_lit = cur_lit;
547 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
549 match self.next_comment() {
551 if (*cmnt).pos < pos {
552 try!(self.print_comment(cmnt));
553 self.cur_cmnt_and_lit().cur_cmnt += 1;
562 fn print_comment(&mut self,
563 cmnt: &comments::Comment) -> io::Result<()> {
566 assert_eq!(cmnt.lines.len(), 1);
567 try!(zerobreak(self.writer()));
568 try!(word(self.writer(), &cmnt.lines[0]));
569 zerobreak(self.writer())
571 comments::Isolated => {
572 try!(self.hardbreak_if_not_bol());
573 for line in &cmnt.lines {
574 // Don't print empty lines because they will end up as trailing
576 if !line.is_empty() {
577 try!(word(self.writer(), &line[..]));
579 try!(hardbreak(self.writer()));
583 comments::Trailing => {
584 try!(word(self.writer(), " "));
585 if cmnt.lines.len() == 1 {
586 try!(word(self.writer(), &cmnt.lines[0]));
587 hardbreak(self.writer())
590 for line in &cmnt.lines {
591 if !line.is_empty() {
592 try!(word(self.writer(), &line[..]));
594 try!(hardbreak(self.writer()));
599 comments::BlankLine => {
600 // We need to do at least one, possibly two hardbreaks.
601 let is_semi = match self.writer().last_token() {
602 pp::Token::String(s, _) => ";" == s,
605 if is_semi || self.is_begin() || self.is_end() {
606 try!(hardbreak(self.writer()));
608 hardbreak(self.writer())
613 fn next_comment(&mut self) -> Option<comments::Comment> {
614 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
615 match *self.comments() {
617 if cur_cmnt < cmnts.len() {
618 Some(cmnts[cur_cmnt].clone())
627 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
628 try!(self.maybe_print_comment(lit.span.lo));
629 match self.next_lit(lit.span.lo) {
631 return word(self.writer(), &(*ltrl).lit);
636 ast::LitStr(ref st, style) => self.print_string(&st, style),
637 ast::LitByte(byte) => {
638 let mut res = String::from("b'");
639 res.extend(ascii::escape_default(byte).map(|c| c as char));
641 word(self.writer(), &res[..])
643 ast::LitChar(ch) => {
644 let mut res = String::from("'");
645 res.extend(ch.escape_default());
647 word(self.writer(), &res[..])
649 ast::LitInt(i, t) => {
651 ast::SignedIntLit(st, ast::Plus) => {
653 &ast_util::int_ty_to_string(st, Some(i as i64)))
655 ast::SignedIntLit(st, ast::Minus) => {
656 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
658 &format!("-{}", istr))
660 ast::UnsignedIntLit(ut) => {
661 word(self.writer(), &ast_util::uint_ty_to_string(ut, Some(i)))
663 ast::UnsuffixedIntLit(ast::Plus) => {
664 word(self.writer(), &format!("{}", i))
666 ast::UnsuffixedIntLit(ast::Minus) => {
667 word(self.writer(), &format!("-{}", i))
671 ast::LitFloat(ref f, t) => {
676 &ast_util::float_ty_to_string(t)))
678 ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
679 ast::LitBool(val) => {
680 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
682 ast::LitByteStr(ref v) => {
683 let mut escaped: String = String::new();
684 for &ch in v.iter() {
685 escaped.extend(ascii::escape_default(ch)
686 .map(|c| c as char));
688 word(self.writer(), &format!("b\"{}\"", escaped))
693 fn print_string(&mut self, st: &str,
694 style: ast::StrStyle) -> io::Result<()> {
695 let st = match style {
697 (format!("\"{}\"", st.escape_default()))
700 (format!("r{delim}\"{string}\"{delim}",
701 delim=repeat("#", n),
705 word(self.writer(), &st[..])
708 fn print_inner_attributes(&mut self,
709 attrs: &[ast::Attribute]) -> io::Result<()> {
712 match attr.node.style {
713 ast::AttrStyle::Inner => {
714 try!(self.print_attribute(attr));
717 _ => {/* fallthrough */ }
721 try!(self.hardbreak_if_not_bol());
726 fn print_outer_attributes(&mut self,
727 attrs: &[ast::Attribute]) -> io::Result<()> {
730 match attr.node.style {
731 ast::AttrStyle::Outer => {
732 try!(self.print_attribute(attr));
735 _ => {/* fallthrough */ }
739 try!(self.hardbreak_if_not_bol());
744 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
745 try!(self.hardbreak_if_not_bol());
746 try!(self.maybe_print_comment(attr.span.lo));
747 if attr.node.is_sugared_doc {
748 word(self.writer(), &attr.value_str().unwrap())
750 match attr.node.style {
751 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
752 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
754 try!(self.print_meta_item(&*attr.meta()));
755 word(self.writer(), "]")
759 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
760 try!(self.ibox(indent_unit));
762 ast::MetaWord(ref name) => {
763 try!(word(self.writer(), &name));
765 ast::MetaNameValue(ref name, ref value) => {
766 try!(self.word_space(&name[..]));
767 try!(self.word_space("="));
768 try!(self.print_literal(value));
770 ast::MetaList(ref name, ref items) => {
771 try!(word(self.writer(), &name));
773 try!(self.commasep(Consistent,
775 |s, i| s.print_meta_item(&**i)));
783 impl<'a> PrintState<'a> for State<'a> {
784 fn writer(&mut self) -> &mut pp::Printer<'a> {
788 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
792 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
796 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
797 &mut self.cur_cmnt_and_lit
800 fn literals(&self) -> &Option<Vec<comments::Literal>> {
806 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
807 self.boxes.push(pp::Breaks::Consistent);
808 pp::cbox(&mut self.s, u)
811 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
813 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
814 try!(word(&mut self.s, w));
818 pub fn head(&mut self, w: &str) -> io::Result<()> {
819 // outer-box is consistent
820 try!(self.cbox(indent_unit));
821 // head-box is inconsistent
822 try!(self.ibox(w.len() + 1));
823 // keyword that starts the head
825 try!(self.word_nbsp(w));
830 pub fn bopen(&mut self) -> io::Result<()> {
831 try!(word(&mut self.s, "{"));
832 self.end() // close the head-box
835 pub fn bclose_(&mut self, span: codemap::Span,
836 indented: usize) -> io::Result<()> {
837 self.bclose_maybe_open(span, indented, true)
839 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
840 indented: usize, close_box: bool) -> io::Result<()> {
841 try!(self.maybe_print_comment(span.hi));
842 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
843 try!(word(&mut self.s, "}"));
845 try!(self.end()); // close the outer-box
849 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
850 self.bclose_(span, indent_unit)
853 pub fn in_cbox(&self) -> bool {
854 match self.boxes.last() {
855 Some(&last_box) => last_box == pp::Breaks::Consistent,
860 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
861 if !self.is_bol() { try!(space(&mut self.s)); }
864 pub fn break_offset_if_not_bol(&mut self, n: usize,
865 off: isize) -> io::Result<()> {
867 break_offset(&mut self.s, n, off)
869 if off != 0 && self.s.last_token().is_hardbreak_tok() {
870 // We do something pretty sketchy here: tuck the nonzero
871 // offset-adjustment we were going to deposit along with the
872 // break into the previous hardbreak.
873 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
879 // Synthesizes a comment that was not textually present in the original source
881 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
882 try!(word(&mut self.s, "/*"));
883 try!(space(&mut self.s));
884 try!(word(&mut self.s, &text[..]));
885 try!(space(&mut self.s));
886 word(&mut self.s, "*/")
891 pub fn commasep_cmnt<T, F, G>(&mut self,
895 mut get_span: G) -> io::Result<()> where
896 F: FnMut(&mut State, &T) -> io::Result<()>,
897 G: FnMut(&T) -> codemap::Span,
899 try!(self.rbox(0, b));
900 let len = elts.len();
903 try!(self.maybe_print_comment(get_span(elt).hi));
907 try!(word(&mut self.s, ","));
908 try!(self.maybe_print_trailing_comment(get_span(elt),
909 Some(get_span(&elts[i]).hi)));
910 try!(self.space_if_not_bol());
916 pub fn commasep_exprs(&mut self, b: Breaks,
917 exprs: &[P<ast::Expr>]) -> io::Result<()> {
918 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
921 pub fn print_mod(&mut self, _mod: &ast::Mod,
922 attrs: &[ast::Attribute]) -> io::Result<()> {
923 try!(self.print_inner_attributes(attrs));
924 for item in &_mod.items {
925 try!(self.print_item(&**item));
930 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
931 attrs: &[ast::Attribute]) -> io::Result<()> {
932 try!(self.print_inner_attributes(attrs));
933 for item in &nmod.items {
934 try!(self.print_foreign_item(&**item));
939 pub fn print_opt_lifetime(&mut self,
940 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
941 if let Some(l) = *lifetime {
942 try!(self.print_lifetime(&l));
948 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
949 try!(self.maybe_print_comment(ty.span.lo));
952 ast::TyVec(ref ty) => {
953 try!(word(&mut self.s, "["));
954 try!(self.print_type(&**ty));
955 try!(word(&mut self.s, "]"));
957 ast::TyPtr(ref mt) => {
958 try!(word(&mut self.s, "*"));
960 ast::MutMutable => try!(self.word_nbsp("mut")),
961 ast::MutImmutable => try!(self.word_nbsp("const")),
963 try!(self.print_type(&*mt.ty));
965 ast::TyRptr(ref lifetime, ref mt) => {
966 try!(word(&mut self.s, "&"));
967 try!(self.print_opt_lifetime(lifetime));
968 try!(self.print_mt(mt));
970 ast::TyTup(ref elts) => {
972 try!(self.commasep(Inconsistent, &elts[..],
973 |s, ty| s.print_type(&**ty)));
975 try!(word(&mut self.s, ","));
979 ast::TyParen(ref typ) => {
981 try!(self.print_type(&**typ));
984 ast::TyBareFn(ref f) => {
985 let generics = ast::Generics {
986 lifetimes: f.lifetimes.clone(),
987 ty_params: OwnedSlice::empty(),
988 where_clause: ast::WhereClause {
989 id: ast::DUMMY_NODE_ID,
990 predicates: Vec::new(),
993 try!(self.print_ty_fn(f.abi,
1000 ast::TyPath(None, ref path) => {
1001 try!(self.print_path(path, false, 0));
1003 ast::TyPath(Some(ref qself), ref path) => {
1004 try!(self.print_qpath(path, qself, false))
1006 ast::TyObjectSum(ref ty, ref bounds) => {
1007 try!(self.print_type(&**ty));
1008 try!(self.print_bounds("+", &bounds[..]));
1010 ast::TyPolyTraitRef(ref bounds) => {
1011 try!(self.print_bounds("", &bounds[..]));
1013 ast::TyFixedLengthVec(ref ty, ref v) => {
1014 try!(word(&mut self.s, "["));
1015 try!(self.print_type(&**ty));
1016 try!(word(&mut self.s, "; "));
1017 try!(self.print_expr(&**v));
1018 try!(word(&mut self.s, "]"));
1020 ast::TyTypeof(ref e) => {
1021 try!(word(&mut self.s, "typeof("));
1022 try!(self.print_expr(&**e));
1023 try!(word(&mut self.s, ")"));
1026 try!(word(&mut self.s, "_"));
1028 ast::TyMac(ref m) => {
1029 try!(self.print_mac(m, token::Paren));
1035 pub fn print_foreign_item(&mut self,
1036 item: &ast::ForeignItem) -> io::Result<()> {
1037 try!(self.hardbreak_if_not_bol());
1038 try!(self.maybe_print_comment(item.span.lo));
1039 try!(self.print_outer_attributes(&item.attrs));
1041 ast::ForeignItemFn(ref decl, ref generics) => {
1042 try!(self.head(""));
1043 try!(self.print_fn(decl, ast::Unsafety::Normal,
1044 ast::Constness::NotConst,
1045 abi::Rust, Some(item.ident),
1046 generics, None, item.vis));
1047 try!(self.end()); // end head-ibox
1048 try!(word(&mut self.s, ";"));
1049 self.end() // end the outer fn box
1051 ast::ForeignItemStatic(ref t, m) => {
1052 try!(self.head(&visibility_qualified(item.vis,
1055 try!(self.word_space("mut"));
1057 try!(self.print_ident(item.ident));
1058 try!(self.word_space(":"));
1059 try!(self.print_type(&**t));
1060 try!(word(&mut self.s, ";"));
1061 try!(self.end()); // end the head-ibox
1062 self.end() // end the outer cbox
1067 fn print_associated_const(&mut self,
1070 default: Option<&ast::Expr>,
1071 vis: ast::Visibility)
1074 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1075 try!(self.word_space("const"));
1076 try!(self.print_ident(ident));
1077 try!(self.word_space(":"));
1078 try!(self.print_type(ty));
1079 if let Some(expr) = default {
1080 try!(space(&mut self.s));
1081 try!(self.word_space("="));
1082 try!(self.print_expr(expr));
1084 word(&mut self.s, ";")
1087 fn print_associated_type(&mut self,
1089 bounds: Option<&ast::TyParamBounds>,
1090 ty: Option<&ast::Ty>)
1092 try!(self.word_space("type"));
1093 try!(self.print_ident(ident));
1094 if let Some(bounds) = bounds {
1095 try!(self.print_bounds(":", bounds));
1097 if let Some(ty) = ty {
1098 try!(space(&mut self.s));
1099 try!(self.word_space("="));
1100 try!(self.print_type(ty));
1102 word(&mut self.s, ";")
1105 /// Pretty-print an item
1106 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1107 try!(self.hardbreak_if_not_bol());
1108 try!(self.maybe_print_comment(item.span.lo));
1109 try!(self.print_outer_attributes(&item.attrs));
1110 try!(self.ann.pre(self, NodeItem(item)));
1112 ast::ItemExternCrate(ref optional_path) => {
1113 try!(self.head(&visibility_qualified(item.vis,
1115 if let Some(p) = *optional_path {
1116 let val = p.as_str();
1117 if val.contains("-") {
1118 try!(self.print_string(&val, ast::CookedStr));
1120 try!(self.print_name(p));
1122 try!(space(&mut self.s));
1123 try!(word(&mut self.s, "as"));
1124 try!(space(&mut self.s));
1126 try!(self.print_ident(item.ident));
1127 try!(word(&mut self.s, ";"));
1128 try!(self.end()); // end inner head-block
1129 try!(self.end()); // end outer head-block
1131 ast::ItemUse(ref vp) => {
1132 try!(self.head(&visibility_qualified(item.vis,
1134 try!(self.print_view_path(&**vp));
1135 try!(word(&mut self.s, ";"));
1136 try!(self.end()); // end inner head-block
1137 try!(self.end()); // end outer head-block
1139 ast::ItemStatic(ref ty, m, ref expr) => {
1140 try!(self.head(&visibility_qualified(item.vis,
1142 if m == ast::MutMutable {
1143 try!(self.word_space("mut"));
1145 try!(self.print_ident(item.ident));
1146 try!(self.word_space(":"));
1147 try!(self.print_type(&**ty));
1148 try!(space(&mut self.s));
1149 try!(self.end()); // end the head-ibox
1151 try!(self.word_space("="));
1152 try!(self.print_expr(&**expr));
1153 try!(word(&mut self.s, ";"));
1154 try!(self.end()); // end the outer cbox
1156 ast::ItemConst(ref ty, ref expr) => {
1157 try!(self.head(&visibility_qualified(item.vis,
1159 try!(self.print_ident(item.ident));
1160 try!(self.word_space(":"));
1161 try!(self.print_type(&**ty));
1162 try!(space(&mut self.s));
1163 try!(self.end()); // end the head-ibox
1165 try!(self.word_space("="));
1166 try!(self.print_expr(&**expr));
1167 try!(word(&mut self.s, ";"));
1168 try!(self.end()); // end the outer cbox
1170 ast::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1171 try!(self.head(""));
1182 try!(word(&mut self.s, " "));
1183 try!(self.print_block_with_attrs(&**body, &item.attrs));
1185 ast::ItemMod(ref _mod) => {
1186 try!(self.head(&visibility_qualified(item.vis,
1188 try!(self.print_ident(item.ident));
1191 try!(self.print_mod(_mod, &item.attrs));
1192 try!(self.bclose(item.span));
1194 ast::ItemForeignMod(ref nmod) => {
1195 try!(self.head("extern"));
1196 try!(self.word_nbsp(&nmod.abi.to_string()));
1198 try!(self.print_foreign_mod(nmod, &item.attrs));
1199 try!(self.bclose(item.span));
1201 ast::ItemTy(ref ty, ref params) => {
1202 try!(self.ibox(indent_unit));
1204 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
1205 try!(self.print_ident(item.ident));
1206 try!(self.print_generics(params));
1207 try!(self.end()); // end the inner ibox
1209 try!(self.print_where_clause(¶ms.where_clause));
1210 try!(space(&mut self.s));
1211 try!(self.word_space("="));
1212 try!(self.print_type(&**ty));
1213 try!(word(&mut self.s, ";"));
1214 try!(self.end()); // end the outer ibox
1216 ast::ItemEnum(ref enum_definition, ref params) => {
1217 try!(self.print_enum_def(
1225 ast::ItemStruct(ref struct_def, ref generics) => {
1226 try!(self.head(&visibility_qualified(item.vis,"struct")));
1227 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1230 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
1231 try!(self.head(""));
1232 try!(self.print_visibility(item.vis));
1233 try!(self.print_unsafety(unsafety));
1234 try!(self.word_nbsp("impl"));
1235 try!(self.print_trait_ref(trait_ref));
1236 try!(space(&mut self.s));
1237 try!(self.word_space("for"));
1238 try!(self.word_space(".."));
1240 try!(self.bclose(item.span));
1242 ast::ItemImpl(unsafety,
1247 ref impl_items) => {
1248 try!(self.head(""));
1249 try!(self.print_visibility(item.vis));
1250 try!(self.print_unsafety(unsafety));
1251 try!(self.word_nbsp("impl"));
1253 if generics.is_parameterized() {
1254 try!(self.print_generics(generics));
1255 try!(space(&mut self.s));
1259 ast::ImplPolarity::Negative => {
1260 try!(word(&mut self.s, "!"));
1267 try!(self.print_trait_ref(t));
1268 try!(space(&mut self.s));
1269 try!(self.word_space("for"));
1274 try!(self.print_type(&**ty));
1275 try!(self.print_where_clause(&generics.where_clause));
1277 try!(space(&mut self.s));
1279 try!(self.print_inner_attributes(&item.attrs));
1280 for impl_item in impl_items {
1281 try!(self.print_impl_item(impl_item));
1283 try!(self.bclose(item.span));
1285 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
1286 try!(self.head(""));
1287 try!(self.print_visibility(item.vis));
1288 try!(self.print_unsafety(unsafety));
1289 try!(self.word_nbsp("trait"));
1290 try!(self.print_ident(item.ident));
1291 try!(self.print_generics(generics));
1292 let mut real_bounds = Vec::with_capacity(bounds.len());
1293 for b in bounds.iter() {
1294 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1295 try!(space(&mut self.s));
1296 try!(self.word_space("for ?"));
1297 try!(self.print_trait_ref(&ptr.trait_ref));
1299 real_bounds.push(b.clone());
1302 try!(self.print_bounds(":", &real_bounds[..]));
1303 try!(self.print_where_clause(&generics.where_clause));
1304 try!(word(&mut self.s, " "));
1306 for trait_item in trait_items {
1307 try!(self.print_trait_item(trait_item));
1309 try!(self.bclose(item.span));
1311 ast::ItemMac(codemap::Spanned { ref node, .. }) => {
1312 try!(self.print_visibility(item.vis));
1313 try!(self.print_path(&node.path, false, 0));
1314 try!(word(&mut self.s, "! "));
1315 try!(self.print_ident(item.ident));
1316 try!(self.cbox(indent_unit));
1318 try!(self.print_tts(&node.tts[..]));
1319 try!(self.pclose());
1320 try!(word(&mut self.s, ";"));
1324 self.ann.post(self, NodeItem(item))
1327 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1328 self.print_path(&t.path, false, 0)
1331 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1332 if !lifetimes.is_empty() {
1333 try!(word(&mut self.s, "for<"));
1334 let mut comma = false;
1335 for lifetime_def in lifetimes {
1337 try!(self.word_space(","))
1339 try!(self.print_lifetime_def(lifetime_def));
1342 try!(word(&mut self.s, ">"));
1347 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1348 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1349 self.print_trait_ref(&t.trait_ref)
1352 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1353 generics: &ast::Generics, ident: ast::Ident,
1354 span: codemap::Span,
1355 visibility: ast::Visibility) -> io::Result<()> {
1356 try!(self.head(&visibility_qualified(visibility, "enum")));
1357 try!(self.print_ident(ident));
1358 try!(self.print_generics(generics));
1359 try!(self.print_where_clause(&generics.where_clause));
1360 try!(space(&mut self.s));
1361 self.print_variants(&enum_definition.variants, span)
1364 pub fn print_variants(&mut self,
1365 variants: &[P<ast::Variant>],
1366 span: codemap::Span) -> io::Result<()> {
1369 try!(self.space_if_not_bol());
1370 try!(self.maybe_print_comment(v.span.lo));
1371 try!(self.print_outer_attributes(&v.node.attrs));
1372 try!(self.ibox(indent_unit));
1373 try!(self.print_variant(&**v));
1374 try!(word(&mut self.s, ","));
1376 try!(self.maybe_print_trailing_comment(v.span, None));
1381 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1383 ast::Public => self.word_nbsp("pub"),
1384 ast::Inherited => Ok(())
1388 pub fn print_struct(&mut self,
1389 struct_def: &ast::VariantData,
1390 generics: &ast::Generics,
1392 span: codemap::Span,
1393 print_finalizer: bool) -> io::Result<()> {
1394 try!(self.print_ident(ident));
1395 try!(self.print_generics(generics));
1396 if !struct_def.is_struct() {
1397 if struct_def.is_tuple() {
1400 Inconsistent, struct_def.fields(),
1402 match field.node.kind {
1403 ast::NamedField(..) => panic!("unexpected named field"),
1404 ast::UnnamedField(vis) => {
1405 try!(s.print_visibility(vis));
1406 try!(s.maybe_print_comment(field.span.lo));
1407 s.print_type(&*field.node.ty)
1412 try!(self.pclose());
1414 try!(self.print_where_clause(&generics.where_clause));
1415 if print_finalizer {
1416 try!(word(&mut self.s, ";"));
1419 self.end() // close the outer-box
1421 try!(self.print_where_clause(&generics.where_clause));
1424 try!(self.hardbreak_if_not_bol());
1426 for field in struct_def.fields() {
1427 match field.node.kind {
1428 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1429 ast::NamedField(ident, visibility) => {
1430 try!(self.hardbreak_if_not_bol());
1431 try!(self.maybe_print_comment(field.span.lo));
1432 try!(self.print_outer_attributes(&field.node.attrs));
1433 try!(self.print_visibility(visibility));
1434 try!(self.print_ident(ident));
1435 try!(self.word_nbsp(":"));
1436 try!(self.print_type(&*field.node.ty));
1437 try!(word(&mut self.s, ","));
1446 /// This doesn't deserve to be called "pretty" printing, but it should be
1447 /// meaning-preserving. A quick hack that might help would be to look at the
1448 /// spans embedded in the TTs to decide where to put spaces and newlines.
1449 /// But it'd be better to parse these according to the grammar of the
1450 /// appropriate macro, transcribe back into the grammar we just parsed from,
1451 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1452 /// expression arguments as expressions). It can be done! I think.
1453 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1455 TokenTree::Token(_, ref tk) => {
1456 try!(word(&mut self.s, &token_to_string(tk)));
1458 parse::token::DocComment(..) => {
1459 hardbreak(&mut self.s)
1464 TokenTree::Delimited(_, ref delimed) => {
1465 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1466 try!(space(&mut self.s));
1467 try!(self.print_tts(&delimed.tts));
1468 try!(space(&mut self.s));
1469 word(&mut self.s, &token_to_string(&delimed.close_token()))
1471 TokenTree::Sequence(_, ref seq) => {
1472 try!(word(&mut self.s, "$("));
1473 for tt_elt in &seq.tts {
1474 try!(self.print_tt(tt_elt));
1476 try!(word(&mut self.s, ")"));
1477 match seq.separator {
1479 try!(word(&mut self.s, &token_to_string(tk)));
1484 ast::ZeroOrMore => word(&mut self.s, "*"),
1485 ast::OneOrMore => word(&mut self.s, "+"),
1491 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1493 let mut suppress_space = false;
1494 for (i, tt) in tts.iter().enumerate() {
1495 if i != 0 && !suppress_space {
1496 try!(space(&mut self.s));
1498 try!(self.print_tt(tt));
1499 // There should be no space between the module name and the following `::` in paths,
1500 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1501 suppress_space = match tt {
1502 &TokenTree::Token(_, token::Ident(_, token::ModName)) |
1503 &TokenTree::Token(_, token::MatchNt(_, _, _, token::ModName)) |
1504 &TokenTree::Token(_, token::SubstNt(_, token::ModName)) => true,
1511 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1512 try!(self.head(""));
1513 let generics = ast_util::empty_generics();
1514 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1515 match v.node.disr_expr {
1517 try!(space(&mut self.s));
1518 try!(self.word_space("="));
1519 self.print_expr(&**d)
1525 pub fn print_method_sig(&mut self,
1528 vis: ast::Visibility)
1530 self.print_fn(&m.decl,
1536 Some(&m.explicit_self.node),
1540 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1542 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1543 try!(self.hardbreak_if_not_bol());
1544 try!(self.maybe_print_comment(ti.span.lo));
1545 try!(self.print_outer_attributes(&ti.attrs));
1547 ast::ConstTraitItem(ref ty, ref default) => {
1548 try!(self.print_associated_const(ti.ident, &ty,
1549 default.as_ref().map(|expr| &**expr),
1552 ast::MethodTraitItem(ref sig, ref body) => {
1554 try!(self.head(""));
1556 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1557 if let Some(ref body) = *body {
1559 try!(self.print_block_with_attrs(body, &ti.attrs));
1561 try!(word(&mut self.s, ";"));
1564 ast::TypeTraitItem(ref bounds, ref default) => {
1565 try!(self.print_associated_type(ti.ident, Some(bounds),
1566 default.as_ref().map(|ty| &**ty)));
1569 self.ann.post(self, NodeSubItem(ti.id))
1572 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1573 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1574 try!(self.hardbreak_if_not_bol());
1575 try!(self.maybe_print_comment(ii.span.lo));
1576 try!(self.print_outer_attributes(&ii.attrs));
1578 ast::ConstImplItem(ref ty, ref expr) => {
1579 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1581 ast::MethodImplItem(ref sig, ref body) => {
1582 try!(self.head(""));
1583 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1585 try!(self.print_block_with_attrs(body, &ii.attrs));
1587 ast::TypeImplItem(ref ty) => {
1588 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1590 ast::MacImplItem(codemap::Spanned { ref node, .. }) => {
1591 // code copied from ItemMac:
1592 try!(self.print_path(&node.path, false, 0));
1593 try!(word(&mut self.s, "! "));
1594 try!(self.cbox(indent_unit));
1596 try!(self.print_tts(&node.tts[..]));
1597 try!(self.pclose());
1598 try!(word(&mut self.s, ";"));
1602 self.ann.post(self, NodeSubItem(ii.id))
1605 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1606 try!(self.maybe_print_comment(st.span.lo));
1608 ast::StmtDecl(ref decl, _) => {
1609 try!(self.print_decl(&**decl));
1611 ast::StmtExpr(ref expr, _) => {
1612 try!(self.space_if_not_bol());
1613 try!(self.print_expr(&**expr));
1615 ast::StmtSemi(ref expr, _) => {
1616 try!(self.space_if_not_bol());
1617 try!(self.print_expr(&**expr));
1618 try!(word(&mut self.s, ";"));
1620 ast::StmtMac(ref mac, style) => {
1621 try!(self.space_if_not_bol());
1622 let delim = match style {
1623 ast::MacStmtWithBraces => token::Brace,
1626 try!(self.print_mac(&**mac, delim));
1628 ast::MacStmtWithBraces => {}
1629 _ => try!(word(&mut self.s, ";")),
1633 if parse::classify::stmt_ends_with_semi(&st.node) {
1634 try!(word(&mut self.s, ";"));
1636 self.maybe_print_trailing_comment(st.span, None)
1639 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1640 self.print_block_with_attrs(blk, &[])
1643 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1644 self.print_block_unclosed_indent(blk, indent_unit)
1647 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1648 indented: usize) -> io::Result<()> {
1649 self.print_block_maybe_unclosed(blk, indented, &[], false)
1652 pub fn print_block_with_attrs(&mut self,
1654 attrs: &[ast::Attribute]) -> io::Result<()> {
1655 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1658 pub fn print_block_maybe_unclosed(&mut self,
1661 attrs: &[ast::Attribute],
1662 close_box: bool) -> io::Result<()> {
1664 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1665 ast::DefaultBlock => ()
1667 try!(self.maybe_print_comment(blk.span.lo));
1668 try!(self.ann.pre(self, NodeBlock(blk)));
1671 try!(self.print_inner_attributes(attrs));
1673 for st in &blk.stmts {
1674 try!(self.print_stmt(&**st));
1678 try!(self.space_if_not_bol());
1679 try!(self.print_expr(&**expr));
1680 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1684 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1685 self.ann.post(self, NodeBlock(blk))
1688 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1692 // "another else-if"
1693 ast::ExprIf(ref i, ref then, ref e) => {
1694 try!(self.cbox(indent_unit - 1));
1696 try!(word(&mut self.s, " else if "));
1697 try!(self.print_expr(&**i));
1698 try!(space(&mut self.s));
1699 try!(self.print_block(&**then));
1700 self.print_else(e.as_ref().map(|e| &**e))
1702 // "another else-if-let"
1703 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1704 try!(self.cbox(indent_unit - 1));
1706 try!(word(&mut self.s, " else if let "));
1707 try!(self.print_pat(&**pat));
1708 try!(space(&mut self.s));
1709 try!(self.word_space("="));
1710 try!(self.print_expr(&**expr));
1711 try!(space(&mut self.s));
1712 try!(self.print_block(&**then));
1713 self.print_else(e.as_ref().map(|e| &**e))
1716 ast::ExprBlock(ref b) => {
1717 try!(self.cbox(indent_unit - 1));
1719 try!(word(&mut self.s, " else "));
1720 self.print_block(&**b)
1722 // BLEAH, constraints would be great here
1724 panic!("print_if saw if with weird alternative");
1732 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1733 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1734 try!(self.head("if"));
1735 try!(self.print_expr(test));
1736 try!(space(&mut self.s));
1737 try!(self.print_block(blk));
1738 self.print_else(elseopt)
1741 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1742 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1743 try!(self.head("if let"));
1744 try!(self.print_pat(pat));
1745 try!(space(&mut self.s));
1746 try!(self.word_space("="));
1747 try!(self.print_expr(expr));
1748 try!(space(&mut self.s));
1749 try!(self.print_block(blk));
1750 self.print_else(elseopt)
1753 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1755 try!(self.print_path(&m.node.path, false, 0));
1756 try!(word(&mut self.s, "!"));
1758 token::Paren => try!(self.popen()),
1759 token::Bracket => try!(word(&mut self.s, "[")),
1760 token::Brace => try!(self.bopen()),
1762 try!(self.print_tts(&m.node.tts));
1764 token::Paren => self.pclose(),
1765 token::Bracket => word(&mut self.s, "]"),
1766 token::Brace => self.bclose(m.span),
1771 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1773 try!(self.commasep_exprs(Inconsistent, args));
1777 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1778 binop: ast::BinOp) -> bool {
1779 match sub_expr.node {
1780 ast::ExprBinary(ref sub_op, _, _) => {
1781 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1782 AssocOp::from_ast_binop(binop.node).precedence() {
1792 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1793 let needs_par = needs_parentheses(expr);
1797 try!(self.print_expr(expr));
1799 try!(self.pclose());
1804 fn print_expr_in_place(&mut self,
1806 expr: &ast::Expr) -> io::Result<()> {
1807 try!(self.print_expr_maybe_paren(place));
1808 try!(space(&mut self.s));
1809 try!(self.word_space("<-"));
1810 self.print_expr_maybe_paren(expr)
1813 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1814 try!(self.ibox(indent_unit));
1815 try!(word(&mut self.s, "["));
1816 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1817 try!(word(&mut self.s, "]"));
1821 fn print_expr_repeat(&mut self,
1822 element: &ast::Expr,
1823 count: &ast::Expr) -> io::Result<()> {
1824 try!(self.ibox(indent_unit));
1825 try!(word(&mut self.s, "["));
1826 try!(self.print_expr(element));
1827 try!(self.word_space(";"));
1828 try!(self.print_expr(count));
1829 try!(word(&mut self.s, "]"));
1833 fn print_expr_struct(&mut self,
1835 fields: &[ast::Field],
1836 wth: &Option<P<ast::Expr>>) -> io::Result<()> {
1837 try!(self.print_path(path, true, 0));
1838 try!(word(&mut self.s, "{"));
1839 try!(self.commasep_cmnt(
1843 try!(s.ibox(indent_unit));
1844 try!(s.print_ident(field.ident.node));
1845 try!(s.word_space(":"));
1846 try!(s.print_expr(&*field.expr));
1852 try!(self.ibox(indent_unit));
1853 if !fields.is_empty() {
1854 try!(word(&mut self.s, ","));
1855 try!(space(&mut self.s));
1857 try!(word(&mut self.s, ".."));
1858 try!(self.print_expr(&**expr));
1861 _ => if !fields.is_empty() {
1862 try!(word(&mut self.s, ","))
1865 try!(word(&mut self.s, "}"));
1869 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1871 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1872 if exprs.len() == 1 {
1873 try!(word(&mut self.s, ","));
1878 fn print_expr_call(&mut self,
1880 args: &[P<ast::Expr>]) -> io::Result<()> {
1881 try!(self.print_expr_maybe_paren(func));
1882 self.print_call_post(args)
1885 fn print_expr_method_call(&mut self,
1886 ident: ast::SpannedIdent,
1888 args: &[P<ast::Expr>]) -> io::Result<()> {
1889 let base_args = &args[1..];
1890 try!(self.print_expr(&*args[0]));
1891 try!(word(&mut self.s, "."));
1892 try!(self.print_ident(ident.node));
1893 if !tys.is_empty() {
1894 try!(word(&mut self.s, "::<"));
1895 try!(self.commasep(Inconsistent, tys,
1896 |s, ty| s.print_type(&**ty)));
1897 try!(word(&mut self.s, ">"));
1899 self.print_call_post(base_args)
1902 fn print_expr_binary(&mut self,
1905 rhs: &ast::Expr) -> io::Result<()> {
1906 if self.check_expr_bin_needs_paren(lhs, op) {
1907 try!(self.print_expr_maybe_paren(lhs));
1909 try!(self.print_expr(lhs));
1911 try!(space(&mut self.s));
1912 try!(self.word_space(ast_util::binop_to_string(op.node)));
1913 if self.check_expr_bin_needs_paren(rhs, op) {
1914 self.print_expr_maybe_paren(rhs)
1916 self.print_expr(rhs)
1920 fn print_expr_unary(&mut self,
1922 expr: &ast::Expr) -> io::Result<()> {
1923 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1924 self.print_expr_maybe_paren(expr)
1927 fn print_expr_addr_of(&mut self,
1928 mutability: ast::Mutability,
1929 expr: &ast::Expr) -> io::Result<()> {
1930 try!(word(&mut self.s, "&"));
1931 try!(self.print_mutability(mutability));
1932 self.print_expr_maybe_paren(expr)
1935 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1936 try!(self.maybe_print_comment(expr.span.lo));
1937 try!(self.ibox(indent_unit));
1938 try!(self.ann.pre(self, NodeExpr(expr)));
1940 ast::ExprBox(ref expr) => {
1941 try!(self.word_space("box"));
1942 try!(self.print_expr(expr));
1944 ast::ExprInPlace(ref place, ref expr) => {
1945 try!(self.print_expr_in_place(place, expr));
1947 ast::ExprVec(ref exprs) => {
1948 try!(self.print_expr_vec(&exprs[..]));
1950 ast::ExprRepeat(ref element, ref count) => {
1951 try!(self.print_expr_repeat(&**element, &**count));
1953 ast::ExprStruct(ref path, ref fields, ref wth) => {
1954 try!(self.print_expr_struct(path, &fields[..], wth));
1956 ast::ExprTup(ref exprs) => {
1957 try!(self.print_expr_tup(&exprs[..]));
1959 ast::ExprCall(ref func, ref args) => {
1960 try!(self.print_expr_call(&**func, &args[..]));
1962 ast::ExprMethodCall(ident, ref tys, ref args) => {
1963 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1965 ast::ExprBinary(op, ref lhs, ref rhs) => {
1966 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1968 ast::ExprUnary(op, ref expr) => {
1969 try!(self.print_expr_unary(op, &**expr));
1971 ast::ExprAddrOf(m, ref expr) => {
1972 try!(self.print_expr_addr_of(m, &**expr));
1974 ast::ExprLit(ref lit) => {
1975 try!(self.print_literal(&**lit));
1977 ast::ExprCast(ref expr, ref ty) => {
1978 if let ast::ExprCast(..) = expr.node {
1979 try!(self.print_expr(&**expr));
1981 try!(self.print_expr_maybe_paren(&**expr));
1983 try!(space(&mut self.s));
1984 try!(self.word_space("as"));
1985 try!(self.print_type(&**ty));
1987 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1988 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1990 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1991 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1993 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1994 if let Some(ident) = opt_ident {
1995 try!(self.print_ident(ident));
1996 try!(self.word_space(":"));
1998 try!(self.head("while"));
1999 try!(self.print_expr(&**test));
2000 try!(space(&mut self.s));
2001 try!(self.print_block(&**blk));
2003 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2004 if let Some(ident) = opt_ident {
2005 try!(self.print_ident(ident));
2006 try!(self.word_space(":"));
2008 try!(self.head("while let"));
2009 try!(self.print_pat(&**pat));
2010 try!(space(&mut self.s));
2011 try!(self.word_space("="));
2012 try!(self.print_expr(&**expr));
2013 try!(space(&mut self.s));
2014 try!(self.print_block(&**blk));
2016 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2017 if let Some(ident) = opt_ident {
2018 try!(self.print_ident(ident));
2019 try!(self.word_space(":"));
2021 try!(self.head("for"));
2022 try!(self.print_pat(&**pat));
2023 try!(space(&mut self.s));
2024 try!(self.word_space("in"));
2025 try!(self.print_expr(&**iter));
2026 try!(space(&mut self.s));
2027 try!(self.print_block(&**blk));
2029 ast::ExprLoop(ref blk, opt_ident) => {
2030 if let Some(ident) = opt_ident {
2031 try!(self.print_ident(ident));
2032 try!(self.word_space(":"));
2034 try!(self.head("loop"));
2035 try!(space(&mut self.s));
2036 try!(self.print_block(&**blk));
2038 ast::ExprMatch(ref expr, ref arms) => {
2039 try!(self.cbox(indent_unit));
2041 try!(self.word_nbsp("match"));
2042 try!(self.print_expr(&**expr));
2043 try!(space(&mut self.s));
2046 try!(self.print_arm(arm));
2048 try!(self.bclose_(expr.span, indent_unit));
2050 ast::ExprClosure(capture_clause, ref decl, ref body) => {
2051 try!(self.print_capture_clause(capture_clause));
2053 try!(self.print_fn_block_args(&**decl));
2054 try!(space(&mut self.s));
2056 let default_return = match decl.output {
2057 ast::DefaultReturn(..) => true,
2061 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2062 try!(self.print_block_unclosed(&**body));
2064 // we extract the block, so as not to create another set of boxes
2065 match body.expr.as_ref().unwrap().node {
2066 ast::ExprBlock(ref blk) => {
2067 try!(self.print_block_unclosed(&**blk));
2070 // this is a bare expression
2071 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
2072 try!(self.end()); // need to close a box
2076 // a box will be closed by print_expr, but we didn't want an overall
2077 // wrapper so we closed the corresponding opening. so create an
2078 // empty box to satisfy the close.
2081 ast::ExprBlock(ref blk) => {
2082 // containing cbox, will be closed by print-block at }
2083 try!(self.cbox(indent_unit));
2084 // head-box, will be closed by print-block after {
2086 try!(self.print_block(&**blk));
2088 ast::ExprAssign(ref lhs, ref rhs) => {
2089 try!(self.print_expr(&**lhs));
2090 try!(space(&mut self.s));
2091 try!(self.word_space("="));
2092 try!(self.print_expr(&**rhs));
2094 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
2095 try!(self.print_expr(&**lhs));
2096 try!(space(&mut self.s));
2097 try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
2098 try!(self.word_space("="));
2099 try!(self.print_expr(&**rhs));
2101 ast::ExprField(ref expr, id) => {
2102 try!(self.print_expr(&**expr));
2103 try!(word(&mut self.s, "."));
2104 try!(self.print_ident(id.node));
2106 ast::ExprTupField(ref expr, id) => {
2107 try!(self.print_expr(&**expr));
2108 try!(word(&mut self.s, "."));
2109 try!(self.print_usize(id.node));
2111 ast::ExprIndex(ref expr, ref index) => {
2112 try!(self.print_expr(&**expr));
2113 try!(word(&mut self.s, "["));
2114 try!(self.print_expr(&**index));
2115 try!(word(&mut self.s, "]"));
2117 ast::ExprRange(ref start, ref end) => {
2118 if let &Some(ref e) = start {
2119 try!(self.print_expr(&**e));
2121 try!(word(&mut self.s, ".."));
2122 if let &Some(ref e) = end {
2123 try!(self.print_expr(&**e));
2126 ast::ExprPath(None, ref path) => {
2127 try!(self.print_path(path, true, 0))
2129 ast::ExprPath(Some(ref qself), ref path) => {
2130 try!(self.print_qpath(path, qself, true))
2132 ast::ExprBreak(opt_ident) => {
2133 try!(word(&mut self.s, "break"));
2134 try!(space(&mut self.s));
2135 if let Some(ident) = opt_ident {
2136 try!(self.print_ident(ident.node));
2137 try!(space(&mut self.s));
2140 ast::ExprAgain(opt_ident) => {
2141 try!(word(&mut self.s, "continue"));
2142 try!(space(&mut self.s));
2143 if let Some(ident) = opt_ident {
2144 try!(self.print_ident(ident.node));
2145 try!(space(&mut self.s))
2148 ast::ExprRet(ref result) => {
2149 try!(word(&mut self.s, "return"));
2152 try!(word(&mut self.s, " "));
2153 try!(self.print_expr(&**expr));
2158 ast::ExprInlineAsm(ref a) => {
2159 try!(word(&mut self.s, "asm!"));
2161 try!(self.print_string(&a.asm, a.asm_str_style));
2162 try!(self.word_space(":"));
2164 try!(self.commasep(Inconsistent, &a.outputs,
2165 |s, &(ref co, ref o, is_rw)| {
2166 match co.slice_shift_char() {
2167 Some(('=', operand)) if is_rw => {
2168 try!(s.print_string(&format!("+{}", operand),
2171 _ => try!(s.print_string(&co, ast::CookedStr))
2174 try!(s.print_expr(&**o));
2178 try!(space(&mut self.s));
2179 try!(self.word_space(":"));
2181 try!(self.commasep(Inconsistent, &a.inputs,
2182 |s, &(ref co, ref o)| {
2183 try!(s.print_string(&co, ast::CookedStr));
2185 try!(s.print_expr(&**o));
2189 try!(space(&mut self.s));
2190 try!(self.word_space(":"));
2192 try!(self.commasep(Inconsistent, &a.clobbers,
2194 try!(s.print_string(&co, ast::CookedStr));
2198 let mut options = vec!();
2200 options.push("volatile");
2203 options.push("alignstack");
2205 if a.dialect == ast::AsmDialect::Intel {
2206 options.push("intel");
2209 if !options.is_empty() {
2210 try!(space(&mut self.s));
2211 try!(self.word_space(":"));
2212 try!(self.commasep(Inconsistent, &*options,
2214 try!(s.print_string(co, ast::CookedStr));
2219 try!(self.pclose());
2221 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
2222 ast::ExprParen(ref e) => {
2224 try!(self.print_expr(&**e));
2225 try!(self.pclose());
2228 try!(self.ann.post(self, NodeExpr(expr)));
2232 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2233 try!(self.print_pat(&*loc.pat));
2234 if let Some(ref ty) = loc.ty {
2235 try!(self.word_space(":"));
2236 try!(self.print_type(&**ty));
2241 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2242 try!(self.maybe_print_comment(decl.span.lo));
2244 ast::DeclLocal(ref loc) => {
2245 try!(self.space_if_not_bol());
2246 try!(self.ibox(indent_unit));
2247 try!(self.word_nbsp("let"));
2249 try!(self.ibox(indent_unit));
2250 try!(self.print_local_decl(&**loc));
2252 if let Some(ref init) = loc.init {
2254 try!(self.word_space("="));
2255 try!(self.print_expr(&**init));
2259 ast::DeclItem(ref item) => self.print_item(&**item)
2263 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2264 try!(word(&mut self.s, &ident.name.as_str()));
2265 self.ann.post(self, NodeIdent(&ident))
2268 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2269 word(&mut self.s, &i.to_string())
2272 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2273 try!(word(&mut self.s, &name.as_str()));
2274 self.ann.post(self, NodeName(&name))
2277 pub fn print_for_decl(&mut self, loc: &ast::Local,
2278 coll: &ast::Expr) -> io::Result<()> {
2279 try!(self.print_local_decl(loc));
2280 try!(space(&mut self.s));
2281 try!(self.word_space("in"));
2282 self.print_expr(coll)
2285 fn print_path(&mut self,
2287 colons_before_params: bool,
2291 try!(self.maybe_print_comment(path.span.lo));
2293 let mut first = !path.global;
2294 for segment in &path.segments[..path.segments.len()-depth] {
2298 try!(word(&mut self.s, "::"))
2301 try!(self.print_ident(segment.identifier));
2303 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2309 fn print_qpath(&mut self,
2312 colons_before_params: bool)
2315 try!(word(&mut self.s, "<"));
2316 try!(self.print_type(&qself.ty));
2317 if qself.position > 0 {
2318 try!(space(&mut self.s));
2319 try!(self.word_space("as"));
2320 let depth = path.segments.len() - qself.position;
2321 try!(self.print_path(&path, false, depth));
2323 try!(word(&mut self.s, ">"));
2324 try!(word(&mut self.s, "::"));
2325 let item_segment = path.segments.last().unwrap();
2326 try!(self.print_ident(item_segment.identifier));
2327 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2330 fn print_path_parameters(&mut self,
2331 parameters: &ast::PathParameters,
2332 colons_before_params: bool)
2335 if parameters.is_empty() {
2339 if colons_before_params {
2340 try!(word(&mut self.s, "::"))
2344 ast::AngleBracketedParameters(ref data) => {
2345 try!(word(&mut self.s, "<"));
2347 let mut comma = false;
2348 for lifetime in &data.lifetimes {
2350 try!(self.word_space(","))
2352 try!(self.print_lifetime(lifetime));
2356 if !data.types.is_empty() {
2358 try!(self.word_space(","))
2363 |s, ty| s.print_type(&**ty)));
2367 for binding in data.bindings.iter() {
2369 try!(self.word_space(","))
2371 try!(self.print_ident(binding.ident));
2372 try!(space(&mut self.s));
2373 try!(self.word_space("="));
2374 try!(self.print_type(&*binding.ty));
2378 try!(word(&mut self.s, ">"))
2381 ast::ParenthesizedParameters(ref data) => {
2382 try!(word(&mut self.s, "("));
2386 |s, ty| s.print_type(&**ty)));
2387 try!(word(&mut self.s, ")"));
2392 try!(self.space_if_not_bol());
2393 try!(self.word_space("->"));
2394 try!(self.print_type(&**ty));
2403 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2404 try!(self.maybe_print_comment(pat.span.lo));
2405 try!(self.ann.pre(self, NodePat(pat)));
2406 /* Pat isn't normalized, but the beauty of it
2407 is that it doesn't matter */
2409 ast::PatWild => try!(word(&mut self.s, "_")),
2410 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2411 match binding_mode {
2412 ast::BindByRef(mutbl) => {
2413 try!(self.word_nbsp("ref"));
2414 try!(self.print_mutability(mutbl));
2416 ast::BindByValue(ast::MutImmutable) => {}
2417 ast::BindByValue(ast::MutMutable) => {
2418 try!(self.word_nbsp("mut"));
2421 try!(self.print_ident(path1.node));
2424 try!(word(&mut self.s, "@"));
2425 try!(self.print_pat(&**p));
2430 ast::PatEnum(ref path, ref args_) => {
2431 try!(self.print_path(path, true, 0));
2433 None => try!(word(&mut self.s, "(..)")),
2435 if !args.is_empty() {
2437 try!(self.commasep(Inconsistent, &args[..],
2438 |s, p| s.print_pat(&**p)));
2439 try!(self.pclose());
2444 ast::PatQPath(ref qself, ref path) => {
2445 try!(self.print_qpath(path, qself, false));
2447 ast::PatStruct(ref path, ref fields, etc) => {
2448 try!(self.print_path(path, true, 0));
2450 try!(self.word_space("{"));
2451 try!(self.commasep_cmnt(
2452 Consistent, &fields[..],
2454 try!(s.cbox(indent_unit));
2455 if !f.node.is_shorthand {
2456 try!(s.print_ident(f.node.ident));
2457 try!(s.word_nbsp(":"));
2459 try!(s.print_pat(&*f.node.pat));
2462 |f| f.node.pat.span));
2464 if !fields.is_empty() { try!(self.word_space(",")); }
2465 try!(word(&mut self.s, ".."));
2467 try!(space(&mut self.s));
2468 try!(word(&mut self.s, "}"));
2470 ast::PatTup(ref elts) => {
2472 try!(self.commasep(Inconsistent,
2474 |s, p| s.print_pat(&**p)));
2475 if elts.len() == 1 {
2476 try!(word(&mut self.s, ","));
2478 try!(self.pclose());
2480 ast::PatBox(ref inner) => {
2481 try!(word(&mut self.s, "box "));
2482 try!(self.print_pat(&**inner));
2484 ast::PatRegion(ref inner, mutbl) => {
2485 try!(word(&mut self.s, "&"));
2486 if mutbl == ast::MutMutable {
2487 try!(word(&mut self.s, "mut "));
2489 try!(self.print_pat(&**inner));
2491 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2492 ast::PatRange(ref begin, ref end) => {
2493 try!(self.print_expr(&**begin));
2494 try!(space(&mut self.s));
2495 try!(word(&mut self.s, "..."));
2496 try!(self.print_expr(&**end));
2498 ast::PatVec(ref before, ref slice, ref after) => {
2499 try!(word(&mut self.s, "["));
2500 try!(self.commasep(Inconsistent,
2502 |s, p| s.print_pat(&**p)));
2503 if let Some(ref p) = *slice {
2504 if !before.is_empty() { try!(self.word_space(",")); }
2505 if p.node != ast::PatWild {
2506 try!(self.print_pat(&**p));
2508 try!(word(&mut self.s, ".."));
2509 if !after.is_empty() { try!(self.word_space(",")); }
2511 try!(self.commasep(Inconsistent,
2513 |s, p| s.print_pat(&**p)));
2514 try!(word(&mut self.s, "]"));
2516 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2518 self.ann.post(self, NodePat(pat))
2521 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2522 // I have no idea why this check is necessary, but here it
2524 if arm.attrs.is_empty() {
2525 try!(space(&mut self.s));
2527 try!(self.cbox(indent_unit));
2529 try!(self.print_outer_attributes(&arm.attrs));
2530 let mut first = true;
2531 for p in &arm.pats {
2535 try!(space(&mut self.s));
2536 try!(self.word_space("|"));
2538 try!(self.print_pat(&**p));
2540 try!(space(&mut self.s));
2541 if let Some(ref e) = arm.guard {
2542 try!(self.word_space("if"));
2543 try!(self.print_expr(&**e));
2544 try!(space(&mut self.s));
2546 try!(self.word_space("=>"));
2548 match arm.body.node {
2549 ast::ExprBlock(ref blk) => {
2550 // the block will close the pattern's ibox
2551 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2553 // If it is a user-provided unsafe block, print a comma after it
2554 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2555 try!(word(&mut self.s, ","));
2559 try!(self.end()); // close the ibox for the pattern
2560 try!(self.print_expr(&*arm.body));
2561 try!(word(&mut self.s, ","));
2564 self.end() // close enclosing cbox
2567 // Returns whether it printed anything
2568 fn print_explicit_self(&mut self,
2569 explicit_self: &ast::ExplicitSelf_,
2570 mutbl: ast::Mutability) -> io::Result<bool> {
2571 try!(self.print_mutability(mutbl));
2572 match *explicit_self {
2573 ast::SelfStatic => { return Ok(false); }
2574 ast::SelfValue(_) => {
2575 try!(word(&mut self.s, "self"));
2577 ast::SelfRegion(ref lt, m, _) => {
2578 try!(word(&mut self.s, "&"));
2579 try!(self.print_opt_lifetime(lt));
2580 try!(self.print_mutability(m));
2581 try!(word(&mut self.s, "self"));
2583 ast::SelfExplicit(ref typ, _) => {
2584 try!(word(&mut self.s, "self"));
2585 try!(self.word_space(":"));
2586 try!(self.print_type(&**typ));
2592 pub fn print_fn(&mut self,
2594 unsafety: ast::Unsafety,
2595 constness: ast::Constness,
2597 name: Option<ast::Ident>,
2598 generics: &ast::Generics,
2599 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2600 vis: ast::Visibility) -> io::Result<()> {
2601 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2603 if let Some(name) = name {
2605 try!(self.print_ident(name));
2607 try!(self.print_generics(generics));
2608 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2609 self.print_where_clause(&generics.where_clause)
2612 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2613 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2615 // It is unfortunate to duplicate the commasep logic, but we want the
2616 // self type and the args all in the same box.
2617 try!(self.rbox(0, Inconsistent));
2618 let mut first = true;
2619 if let Some(explicit_self) = opt_explicit_self {
2620 let m = match explicit_self {
2621 &ast::SelfStatic => ast::MutImmutable,
2622 _ => match decl.inputs[0].pat.node {
2623 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2624 _ => ast::MutImmutable
2627 first = !try!(self.print_explicit_self(explicit_self, m));
2630 // HACK(eddyb) ignore the separately printed self argument.
2631 let args = if first {
2638 if first { first = false; } else { try!(self.word_space(",")); }
2639 try!(self.print_arg(arg));
2645 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2646 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2649 try!(self.print_fn_args(decl, opt_explicit_self));
2651 try!(word(&mut self.s, ", ..."));
2653 try!(self.pclose());
2655 self.print_fn_output(decl)
2658 pub fn print_fn_block_args(
2662 try!(word(&mut self.s, "|"));
2663 try!(self.print_fn_args(decl, None));
2664 try!(word(&mut self.s, "|"));
2666 if let ast::DefaultReturn(..) = decl.output {
2670 try!(self.space_if_not_bol());
2671 try!(self.word_space("->"));
2673 ast::Return(ref ty) => {
2674 try!(self.print_type(&**ty));
2675 self.maybe_print_comment(ty.span.lo)
2677 ast::DefaultReturn(..) => unreachable!(),
2678 ast::NoReturn(span) => {
2679 try!(self.word_nbsp("!"));
2680 self.maybe_print_comment(span.lo)
2685 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2687 match capture_clause {
2688 ast::CaptureByValue => self.word_space("move"),
2689 ast::CaptureByRef => Ok(()),
2693 pub fn print_bounds(&mut self,
2695 bounds: &[ast::TyParamBound])
2697 if !bounds.is_empty() {
2698 try!(word(&mut self.s, prefix));
2699 let mut first = true;
2700 for bound in bounds {
2705 try!(self.word_space("+"));
2709 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2710 self.print_poly_trait_ref(tref)
2712 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2713 try!(word(&mut self.s, "?"));
2714 self.print_poly_trait_ref(tref)
2716 RegionTyParamBound(ref lt) => {
2717 self.print_lifetime(lt)
2727 pub fn print_lifetime(&mut self,
2728 lifetime: &ast::Lifetime)
2731 self.print_name(lifetime.name)
2734 pub fn print_lifetime_def(&mut self,
2735 lifetime: &ast::LifetimeDef)
2738 try!(self.print_lifetime(&lifetime.lifetime));
2740 for v in &lifetime.bounds {
2741 try!(word(&mut self.s, sep));
2742 try!(self.print_lifetime(v));
2748 pub fn print_generics(&mut self,
2749 generics: &ast::Generics)
2752 let total = generics.lifetimes.len() + generics.ty_params.len();
2757 try!(word(&mut self.s, "<"));
2759 let mut ints = Vec::new();
2764 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2765 if idx < generics.lifetimes.len() {
2766 let lifetime = &generics.lifetimes[idx];
2767 s.print_lifetime_def(lifetime)
2769 let idx = idx - generics.lifetimes.len();
2770 let param = &generics.ty_params[idx];
2771 s.print_ty_param(param)
2775 try!(word(&mut self.s, ">"));
2779 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2780 try!(self.print_ident(param.ident));
2781 try!(self.print_bounds(":", ¶m.bounds));
2782 match param.default {
2783 Some(ref default) => {
2784 try!(space(&mut self.s));
2785 try!(self.word_space("="));
2786 self.print_type(&**default)
2792 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2794 if where_clause.predicates.is_empty() {
2798 try!(space(&mut self.s));
2799 try!(self.word_space("where"));
2801 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2803 try!(self.word_space(","));
2807 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2811 try!(self.print_formal_lifetime_list(bound_lifetimes));
2812 try!(self.print_type(&**bounded_ty));
2813 try!(self.print_bounds(":", bounds));
2815 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2818 try!(self.print_lifetime(lifetime));
2819 try!(word(&mut self.s, ":"));
2821 for (i, bound) in bounds.iter().enumerate() {
2822 try!(self.print_lifetime(bound));
2825 try!(word(&mut self.s, ":"));
2829 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2830 try!(self.print_path(path, false, 0));
2831 try!(space(&mut self.s));
2832 try!(self.word_space("="));
2833 try!(self.print_type(&**ty));
2841 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2843 ast::ViewPathSimple(ident, ref path) => {
2844 try!(self.print_path(path, false, 0));
2846 if path.segments.last().unwrap().identifier.name !=
2848 try!(space(&mut self.s));
2849 try!(self.word_space("as"));
2850 try!(self.print_ident(ident));
2856 ast::ViewPathGlob(ref path) => {
2857 try!(self.print_path(path, false, 0));
2858 word(&mut self.s, "::*")
2861 ast::ViewPathList(ref path, ref idents) => {
2862 if path.segments.is_empty() {
2863 try!(word(&mut self.s, "{"));
2865 try!(self.print_path(path, false, 0));
2866 try!(word(&mut self.s, "::{"));
2868 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2870 ast::PathListIdent { name, rename, .. } => {
2871 try!(s.print_ident(name));
2872 if let Some(ident) = rename {
2873 try!(space(&mut s.s));
2874 try!(s.word_space("as"));
2875 try!(s.print_ident(ident));
2879 ast::PathListMod { rename, .. } => {
2880 try!(word(&mut s.s, "self"));
2881 if let Some(ident) = rename {
2882 try!(space(&mut s.s));
2883 try!(s.word_space("as"));
2884 try!(s.print_ident(ident));
2890 word(&mut self.s, "}")
2895 pub fn print_mutability(&mut self,
2896 mutbl: ast::Mutability) -> io::Result<()> {
2898 ast::MutMutable => self.word_nbsp("mut"),
2899 ast::MutImmutable => Ok(()),
2903 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2904 try!(self.print_mutability(mt.mutbl));
2905 self.print_type(&*mt.ty)
2908 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2909 try!(self.ibox(indent_unit));
2910 match input.ty.node {
2911 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2913 match input.pat.node {
2914 ast::PatIdent(_, ref path1, _) if
2916 parse::token::special_idents::invalid.name => {
2920 try!(self.print_pat(&*input.pat));
2921 try!(word(&mut self.s, ":"));
2922 try!(space(&mut self.s));
2925 try!(self.print_type(&*input.ty));
2931 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2932 if let ast::DefaultReturn(..) = decl.output {
2936 try!(self.space_if_not_bol());
2937 try!(self.ibox(indent_unit));
2938 try!(self.word_space("->"));
2941 try!(self.word_nbsp("!")),
2942 ast::DefaultReturn(..) => unreachable!(),
2943 ast::Return(ref ty) =>
2944 try!(self.print_type(&**ty))
2949 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2954 pub fn print_ty_fn(&mut self,
2956 unsafety: ast::Unsafety,
2958 name: Option<ast::Ident>,
2959 generics: &ast::Generics,
2960 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2962 try!(self.ibox(indent_unit));
2963 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2964 try!(word(&mut self.s, "for"));
2965 try!(self.print_generics(generics));
2967 let generics = ast::Generics {
2968 lifetimes: Vec::new(),
2969 ty_params: OwnedSlice::empty(),
2970 where_clause: ast::WhereClause {
2971 id: ast::DUMMY_NODE_ID,
2972 predicates: Vec::new(),
2975 try!(self.print_fn(decl,
2977 ast::Constness::NotConst,
2986 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2987 next_pos: Option<BytePos>)
2989 let cm = match self.cm {
2993 match self.next_comment() {
2995 if (*cmnt).style != comments::Trailing { return Ok(()) }
2996 let span_line = cm.lookup_char_pos(span.hi);
2997 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2998 let mut next = (*cmnt).pos + BytePos(1);
2999 match next_pos { None => (), Some(p) => next = p }
3000 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3001 span_line.line == comment_line.line {
3002 try!(self.print_comment(cmnt));
3003 self.cur_cmnt_and_lit.cur_cmnt += 1;
3011 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3012 // If there aren't any remaining comments, then we need to manually
3013 // make sure there is a line break at the end.
3014 if self.next_comment().is_none() {
3015 try!(hardbreak(&mut self.s));
3018 match self.next_comment() {
3020 try!(self.print_comment(cmnt));
3021 self.cur_cmnt_and_lit.cur_cmnt += 1;
3029 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3030 opt_abi: Option<abi::Abi>)
3033 Some(abi::Rust) => Ok(()),
3035 try!(self.word_nbsp("extern"));
3036 self.word_nbsp(&abi.to_string())
3042 pub fn print_extern_opt_abi(&mut self,
3043 opt_abi: Option<abi::Abi>) -> io::Result<()> {
3046 try!(self.word_nbsp("extern"));
3047 self.word_nbsp(&abi.to_string())
3053 pub fn print_fn_header_info(&mut self,
3054 unsafety: ast::Unsafety,
3055 constness: ast::Constness,
3057 vis: ast::Visibility) -> io::Result<()> {
3058 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3061 ast::Constness::NotConst => {}
3062 ast::Constness::Const => try!(self.word_nbsp("const"))
3065 try!(self.print_unsafety(unsafety));
3067 if abi != abi::Rust {
3068 try!(self.word_nbsp("extern"));
3069 try!(self.word_nbsp(&abi.to_string()));
3072 word(&mut self.s, "fn")
3075 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3077 ast::Unsafety::Normal => Ok(()),
3078 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3083 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3095 fn test_fun_to_string() {
3096 let abba_ident = token::str_to_ident("abba");
3098 let decl = ast::FnDecl {
3100 output: ast::DefaultReturn(codemap::DUMMY_SP),
3103 let generics = ast_util::empty_generics();
3104 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3105 ast::Constness::NotConst,
3112 fn test_variant_to_string() {
3113 let ident = token::str_to_ident("principal_skinner");
3115 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3118 // making this up as I go.... ?
3119 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3123 let varstr = variant_to_string(&var);
3124 assert_eq!(varstr, "principal_skinner");
3128 fn test_signed_int_to_string() {
3129 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3130 let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3131 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3132 lit_to_string(&codemap::dummy_spanned(neg_int)));