1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
18 use owned_slice::OwnedSlice;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{self, CodeMap, BytePos};
22 use parse::token::{self, BinOpToken, Token, InternedString};
23 use parse::lexer::comments;
25 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, eof};
27 use print::pp::Breaks::{Consistent, Inconsistent};
32 use std::io::{self, Write, Read};
35 pub enum AnnNode<'a> {
36 NodeIdent(&'a ast::Ident),
37 NodeName(&'a ast::Name),
38 NodeBlock(&'a ast::Block),
39 NodeItem(&'a ast::Item),
40 NodeSubItem(ast::NodeId),
41 NodeExpr(&'a ast::Expr),
42 NodePat(&'a ast::Pat),
46 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
47 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
50 #[derive(Copy, Clone)]
53 impl PpAnn for NoAnn {}
55 #[derive(Copy, Clone)]
56 pub struct CurrentCommentAndLiteral {
61 pub struct State<'a> {
62 pub s: pp::Printer<'a>,
63 cm: Option<&'a CodeMap>,
64 comments: Option<Vec<comments::Comment> >,
65 literals: Option<Vec<comments::Literal> >,
66 cur_cmnt_and_lit: CurrentCommentAndLiteral,
67 boxes: Vec<pp::Breaks>,
71 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
72 static NO_ANN: NoAnn = NoAnn;
73 rust_printer_annotated(writer, &NO_ANN)
76 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
77 ann: &'a PpAnn) -> State<'a> {
79 s: pp::mk_printer(writer, default_columns),
83 cur_cmnt_and_lit: CurrentCommentAndLiteral {
92 #[allow(non_upper_case_globals)]
93 pub const indent_unit: usize = 4;
95 #[allow(non_upper_case_globals)]
96 pub const default_columns: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
102 span_diagnostic: &diagnostic::SpanHandler,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm,
116 if is_expanded && !std_inject::no_std(krate) {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
122 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
123 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
125 // #![feature(no_std)]
126 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
127 attr::mk_list_item(InternedString::new("feature"),
128 vec![no_std_meta.clone(),
129 prelude_import_meta]));
130 try!(s.print_attribute(&fake_attr));
133 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
134 try!(s.print_attribute(&fake_attr));
137 try!(s.print_mod(&krate.module, &krate.attrs));
138 try!(s.print_remaining_comments());
143 pub fn new_from_input(cm: &'a CodeMap,
144 span_diagnostic: &diagnostic::SpanHandler,
149 is_expanded: bool) -> State<'a> {
150 let (cmnts, lits) = comments::gather_comments_and_literals(
160 // If the code is post expansion, don't use the table of
161 // literals, since it doesn't correspond with the literals
162 // in the AST anymore.
163 if is_expanded { None } else { Some(lits) })
166 pub fn new(cm: &'a CodeMap,
169 comments: Option<Vec<comments::Comment>>,
170 literals: Option<Vec<comments::Literal>>) -> State<'a> {
172 s: pp::mk_printer(out, default_columns),
176 cur_cmnt_and_lit: CurrentCommentAndLiteral {
186 pub fn to_string<F>(f: F) -> String where
187 F: FnOnce(&mut State) -> io::Result<()>,
189 let mut wr = Vec::new();
191 let mut printer = rust_printer(Box::new(&mut wr));
192 f(&mut printer).unwrap();
193 eof(&mut printer.s).unwrap();
195 String::from_utf8(wr).unwrap()
198 pub fn binop_to_string(op: BinOpToken) -> &'static str {
204 token::Percent => "%",
213 pub fn token_to_string(tok: &Token) -> String {
215 token::Eq => "=".to_string(),
216 token::Lt => "<".to_string(),
217 token::Le => "<=".to_string(),
218 token::EqEq => "==".to_string(),
219 token::Ne => "!=".to_string(),
220 token::Ge => ">=".to_string(),
221 token::Gt => ">".to_string(),
222 token::Not => "!".to_string(),
223 token::Tilde => "~".to_string(),
224 token::OrOr => "||".to_string(),
225 token::AndAnd => "&&".to_string(),
226 token::BinOp(op) => binop_to_string(op).to_string(),
227 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
229 /* Structural symbols */
230 token::At => "@".to_string(),
231 token::Dot => ".".to_string(),
232 token::DotDot => "..".to_string(),
233 token::DotDotDot => "...".to_string(),
234 token::Comma => ",".to_string(),
235 token::Semi => ";".to_string(),
236 token::Colon => ":".to_string(),
237 token::ModSep => "::".to_string(),
238 token::RArrow => "->".to_string(),
239 token::LArrow => "<-".to_string(),
240 token::FatArrow => "=>".to_string(),
241 token::OpenDelim(token::Paren) => "(".to_string(),
242 token::CloseDelim(token::Paren) => ")".to_string(),
243 token::OpenDelim(token::Bracket) => "[".to_string(),
244 token::CloseDelim(token::Bracket) => "]".to_string(),
245 token::OpenDelim(token::Brace) => "{".to_string(),
246 token::CloseDelim(token::Brace) => "}".to_string(),
247 token::Pound => "#".to_string(),
248 token::Dollar => "$".to_string(),
249 token::Question => "?".to_string(),
252 token::Literal(lit, suf) => {
253 let mut out = match lit {
254 token::Byte(b) => format!("b'{}'", b),
255 token::Char(c) => format!("'{}'", c),
256 token::Float(c) => c.to_string(),
257 token::Integer(c) => c.to_string(),
258 token::Str_(s) => format!("\"{}\"", s),
259 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
260 delim=repeat("#", n),
262 token::ByteStr(v) => format!("b\"{}\"", v),
263 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
264 delim=repeat("#", n),
268 if let Some(s) = suf {
269 out.push_str(&s.as_str())
275 /* Name components */
276 token::Ident(s, _) => s.to_string(),
277 token::Lifetime(s) => s.to_string(),
278 token::Underscore => "_".to_string(),
281 token::DocComment(s) => s.to_string(),
282 token::SubstNt(s, _) => format!("${}", s),
283 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
284 token::Eof => "<eof>".to_string(),
285 token::Whitespace => " ".to_string(),
286 token::Comment => "/* */".to_string(),
287 token::Shebang(s) => format!("/* shebang: {}*/", s),
289 token::SpecialVarNt(var) => format!("${}", var.as_str()),
291 token::Interpolated(ref nt) => match *nt {
292 token::NtExpr(ref e) => expr_to_string(&**e),
293 token::NtMeta(ref e) => meta_item_to_string(&**e),
294 token::NtTy(ref e) => ty_to_string(&**e),
295 token::NtPath(ref e) => path_to_string(&**e),
296 token::NtItem(ref e) => item_to_string(&**e),
297 token::NtBlock(ref e) => block_to_string(&**e),
298 token::NtStmt(ref e) => stmt_to_string(&**e),
299 token::NtPat(ref e) => pat_to_string(&**e),
300 token::NtIdent(ref e, _) => ident_to_string(&**e),
301 token::NtTT(ref e) => tt_to_string(&**e),
302 token::NtArm(ref e) => arm_to_string(&*e),
303 token::NtImplItem(ref e) => impl_item_to_string(&**e),
304 token::NtTraitItem(ref e) => trait_item_to_string(&**e),
305 token::NtGenerics(ref e) => generics_to_string(&*e),
306 token::NtWhereClause(ref e) => where_clause_to_string(&*e),
311 pub fn ty_to_string(ty: &ast::Ty) -> String {
312 to_string(|s| s.print_type(ty))
315 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
316 to_string(|s| s.print_bounds("", bounds))
319 pub fn pat_to_string(pat: &ast::Pat) -> String {
320 to_string(|s| s.print_pat(pat))
323 pub fn arm_to_string(arm: &ast::Arm) -> String {
324 to_string(|s| s.print_arm(arm))
327 pub fn expr_to_string(e: &ast::Expr) -> String {
328 to_string(|s| s.print_expr(e))
331 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
332 to_string(|s| s.print_lifetime(e))
335 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
336 to_string(|s| s.print_tt(tt))
339 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
340 to_string(|s| s.print_tts(tts))
343 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
344 to_string(|s| s.print_stmt(stmt))
347 pub fn attr_to_string(attr: &ast::Attribute) -> String {
348 to_string(|s| s.print_attribute(attr))
351 pub fn item_to_string(i: &ast::Item) -> String {
352 to_string(|s| s.print_item(i))
355 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
356 to_string(|s| s.print_impl_item(i))
359 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
360 to_string(|s| s.print_trait_item(i))
363 pub fn generics_to_string(generics: &ast::Generics) -> String {
364 to_string(|s| s.print_generics(generics))
367 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
368 to_string(|s| s.print_where_clause(i))
371 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
372 to_string(|s| s.print_fn_block_args(p))
375 pub fn path_to_string(p: &ast::Path) -> String {
376 to_string(|s| s.print_path(p, false, 0))
379 pub fn ident_to_string(id: &ast::Ident) -> String {
380 to_string(|s| s.print_ident(*id))
383 pub fn fun_to_string(decl: &ast::FnDecl,
384 unsafety: ast::Unsafety,
385 constness: ast::Constness,
387 opt_explicit_self: Option<&ast::ExplicitSelf_>,
388 generics: &ast::Generics)
392 try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
393 generics, opt_explicit_self, ast::Inherited));
394 try!(s.end()); // Close the head box
395 s.end() // Close the outer box
399 pub fn block_to_string(blk: &ast::Block) -> String {
401 // containing cbox, will be closed by print-block at }
402 try!(s.cbox(indent_unit));
403 // head-ibox, will be closed by print-block after {
409 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
410 to_string(|s| s.print_meta_item(mi))
413 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
414 to_string(|s| s.print_attribute(attr))
417 pub fn lit_to_string(l: &ast::Lit) -> String {
418 to_string(|s| s.print_literal(l))
421 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
422 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
425 pub fn variant_to_string(var: &ast::Variant) -> String {
426 to_string(|s| s.print_variant(var))
429 pub fn arg_to_string(arg: &ast::Arg) -> String {
430 to_string(|s| s.print_arg(arg))
433 pub fn mac_to_string(arg: &ast::Mac) -> String {
434 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
437 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
439 ast::Public => format!("pub {}", s),
440 ast::Inherited => s.to_string()
444 fn needs_parentheses(expr: &ast::Expr) -> bool {
446 ast::ExprAssign(..) | ast::ExprBinary(..) |
447 ast::ExprClosure(..) |
448 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
453 pub trait PrintState<'a> {
454 fn writer(&mut self) -> &mut pp::Printer<'a>;
455 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
456 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
457 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
458 fn literals(&self) -> &Option<Vec<comments::Literal>>;
460 fn word_space(&mut self, w: &str) -> io::Result<()> {
461 try!(word(self.writer(), w));
465 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
467 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
469 fn is_begin(&mut self) -> bool {
470 match self.writer().last_token() {
471 pp::Token::Begin(_) => true,
476 fn is_end(&mut self) -> bool {
477 match self.writer().last_token() {
478 pp::Token::End => true,
483 // is this the beginning of a line?
484 fn is_bol(&mut self) -> bool {
485 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
488 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
490 try!(hardbreak(self.writer()))
496 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
497 self.boxes().push(b);
498 pp::rbox(self.writer(), u, b)
501 fn ibox(&mut self, u: usize) -> io::Result<()> {
502 self.boxes().push(pp::Breaks::Inconsistent);
503 pp::ibox(self.writer(), u)
506 fn end(&mut self) -> io::Result<()> {
507 self.boxes().pop().unwrap();
508 pp::end(self.writer())
511 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
512 where F: FnMut(&mut Self, &T) -> io::Result<()>,
514 try!(self.rbox(0, b));
515 let mut first = true;
517 if first { first = false; } else { try!(self.word_space(",")); }
524 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
525 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
527 let mut result = None;
529 if let &Some(ref lits) = self.literals()
531 while cur_lit < lits.len() {
532 let ltrl = (*lits)[cur_lit].clone();
533 if ltrl.pos > pos { break; }
542 self.cur_cmnt_and_lit().cur_lit = cur_lit;
546 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
548 match self.next_comment() {
550 if (*cmnt).pos < pos {
551 try!(self.print_comment(cmnt));
552 self.cur_cmnt_and_lit().cur_cmnt += 1;
561 fn print_comment(&mut self,
562 cmnt: &comments::Comment) -> io::Result<()> {
565 assert_eq!(cmnt.lines.len(), 1);
566 try!(zerobreak(self.writer()));
567 try!(word(self.writer(), &cmnt.lines[0]));
568 zerobreak(self.writer())
570 comments::Isolated => {
571 try!(self.hardbreak_if_not_bol());
572 for line in &cmnt.lines {
573 // Don't print empty lines because they will end up as trailing
575 if !line.is_empty() {
576 try!(word(self.writer(), &line[..]));
578 try!(hardbreak(self.writer()));
582 comments::Trailing => {
583 try!(word(self.writer(), " "));
584 if cmnt.lines.len() == 1 {
585 try!(word(self.writer(), &cmnt.lines[0]));
586 hardbreak(self.writer())
589 for line in &cmnt.lines {
590 if !line.is_empty() {
591 try!(word(self.writer(), &line[..]));
593 try!(hardbreak(self.writer()));
598 comments::BlankLine => {
599 // We need to do at least one, possibly two hardbreaks.
600 let is_semi = match self.writer().last_token() {
601 pp::Token::String(s, _) => ";" == s,
604 if is_semi || self.is_begin() || self.is_end() {
605 try!(hardbreak(self.writer()));
607 hardbreak(self.writer())
612 fn next_comment(&mut self) -> Option<comments::Comment> {
613 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
614 match *self.comments() {
616 if cur_cmnt < cmnts.len() {
617 Some(cmnts[cur_cmnt].clone())
626 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
627 try!(self.maybe_print_comment(lit.span.lo));
628 match self.next_lit(lit.span.lo) {
630 return word(self.writer(), &(*ltrl).lit);
635 ast::LitStr(ref st, style) => self.print_string(&st, style),
636 ast::LitByte(byte) => {
637 let mut res = String::from("b'");
638 res.extend(ascii::escape_default(byte).map(|c| c as char));
640 word(self.writer(), &res[..])
642 ast::LitChar(ch) => {
643 let mut res = String::from("'");
644 res.extend(ch.escape_default());
646 word(self.writer(), &res[..])
648 ast::LitInt(i, t) => {
650 ast::SignedIntLit(st, ast::Plus) => {
652 &ast_util::int_ty_to_string(st, Some(i as i64)))
654 ast::SignedIntLit(st, ast::Minus) => {
655 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
657 &format!("-{}", istr))
659 ast::UnsignedIntLit(ut) => {
660 word(self.writer(), &ast_util::uint_ty_to_string(ut, Some(i)))
662 ast::UnsuffixedIntLit(ast::Plus) => {
663 word(self.writer(), &format!("{}", i))
665 ast::UnsuffixedIntLit(ast::Minus) => {
666 word(self.writer(), &format!("-{}", i))
670 ast::LitFloat(ref f, t) => {
675 &ast_util::float_ty_to_string(t)))
677 ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
678 ast::LitBool(val) => {
679 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
681 ast::LitByteStr(ref v) => {
682 let mut escaped: String = String::new();
683 for &ch in v.iter() {
684 escaped.extend(ascii::escape_default(ch)
685 .map(|c| c as char));
687 word(self.writer(), &format!("b\"{}\"", escaped))
692 fn print_string(&mut self, st: &str,
693 style: ast::StrStyle) -> io::Result<()> {
694 let st = match style {
696 (format!("\"{}\"", st.escape_default()))
699 (format!("r{delim}\"{string}\"{delim}",
700 delim=repeat("#", n),
704 word(self.writer(), &st[..])
707 fn print_inner_attributes(&mut self,
708 attrs: &[ast::Attribute]) -> io::Result<()> {
711 match attr.node.style {
713 try!(self.print_attribute(attr));
716 _ => {/* fallthrough */ }
720 try!(self.hardbreak_if_not_bol());
725 fn print_outer_attributes(&mut self,
726 attrs: &[ast::Attribute]) -> io::Result<()> {
729 match attr.node.style {
731 try!(self.print_attribute(attr));
734 _ => {/* fallthrough */ }
738 try!(self.hardbreak_if_not_bol());
743 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
744 try!(self.hardbreak_if_not_bol());
745 try!(self.maybe_print_comment(attr.span.lo));
746 if attr.node.is_sugared_doc {
747 word(self.writer(), &attr.value_str().unwrap())
749 match attr.node.style {
750 ast::AttrInner => try!(word(self.writer(), "#![")),
751 ast::AttrOuter => try!(word(self.writer(), "#[")),
753 try!(self.print_meta_item(&*attr.meta()));
754 word(self.writer(), "]")
758 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
759 try!(self.ibox(indent_unit));
761 ast::MetaWord(ref name) => {
762 try!(word(self.writer(), &name));
764 ast::MetaNameValue(ref name, ref value) => {
765 try!(self.word_space(&name[..]));
766 try!(self.word_space("="));
767 try!(self.print_literal(value));
769 ast::MetaList(ref name, ref items) => {
770 try!(word(self.writer(), &name));
772 try!(self.commasep(Consistent,
774 |s, i| s.print_meta_item(&**i)));
782 impl<'a> PrintState<'a> for State<'a> {
783 fn writer(&mut self) -> &mut pp::Printer<'a> {
787 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
791 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
795 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
796 &mut self.cur_cmnt_and_lit
799 fn literals(&self) -> &Option<Vec<comments::Literal>> {
805 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
806 self.boxes.push(pp::Breaks::Consistent);
807 pp::cbox(&mut self.s, u)
810 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
812 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
813 try!(word(&mut self.s, w));
817 pub fn head(&mut self, w: &str) -> io::Result<()> {
818 // outer-box is consistent
819 try!(self.cbox(indent_unit));
820 // head-box is inconsistent
821 try!(self.ibox(w.len() + 1));
822 // keyword that starts the head
824 try!(self.word_nbsp(w));
829 pub fn bopen(&mut self) -> io::Result<()> {
830 try!(word(&mut self.s, "{"));
831 self.end() // close the head-box
834 pub fn bclose_(&mut self, span: codemap::Span,
835 indented: usize) -> io::Result<()> {
836 self.bclose_maybe_open(span, indented, true)
838 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
839 indented: usize, close_box: bool) -> io::Result<()> {
840 try!(self.maybe_print_comment(span.hi));
841 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
842 try!(word(&mut self.s, "}"));
844 try!(self.end()); // close the outer-box
848 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
849 self.bclose_(span, indent_unit)
852 pub fn in_cbox(&self) -> bool {
853 match self.boxes.last() {
854 Some(&last_box) => last_box == pp::Breaks::Consistent,
859 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
860 if !self.is_bol() { try!(space(&mut self.s)); }
863 pub fn break_offset_if_not_bol(&mut self, n: usize,
864 off: isize) -> io::Result<()> {
866 break_offset(&mut self.s, n, off)
868 if off != 0 && self.s.last_token().is_hardbreak_tok() {
869 // We do something pretty sketchy here: tuck the nonzero
870 // offset-adjustment we were going to deposit along with the
871 // break into the previous hardbreak.
872 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
878 // Synthesizes a comment that was not textually present in the original source
880 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
881 try!(word(&mut self.s, "/*"));
882 try!(space(&mut self.s));
883 try!(word(&mut self.s, &text[..]));
884 try!(space(&mut self.s));
885 word(&mut self.s, "*/")
890 pub fn commasep_cmnt<T, F, G>(&mut self,
894 mut get_span: G) -> io::Result<()> where
895 F: FnMut(&mut State, &T) -> io::Result<()>,
896 G: FnMut(&T) -> codemap::Span,
898 try!(self.rbox(0, b));
899 let len = elts.len();
902 try!(self.maybe_print_comment(get_span(elt).hi));
906 try!(word(&mut self.s, ","));
907 try!(self.maybe_print_trailing_comment(get_span(elt),
908 Some(get_span(&elts[i]).hi)));
909 try!(self.space_if_not_bol());
915 pub fn commasep_exprs(&mut self, b: Breaks,
916 exprs: &[P<ast::Expr>]) -> io::Result<()> {
917 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
920 pub fn print_mod(&mut self, _mod: &ast::Mod,
921 attrs: &[ast::Attribute]) -> io::Result<()> {
922 try!(self.print_inner_attributes(attrs));
923 for item in &_mod.items {
924 try!(self.print_item(&**item));
929 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
930 attrs: &[ast::Attribute]) -> io::Result<()> {
931 try!(self.print_inner_attributes(attrs));
932 for item in &nmod.items {
933 try!(self.print_foreign_item(&**item));
938 pub fn print_opt_lifetime(&mut self,
939 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
940 if let Some(l) = *lifetime {
941 try!(self.print_lifetime(&l));
947 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
948 try!(self.maybe_print_comment(ty.span.lo));
951 ast::TyVec(ref ty) => {
952 try!(word(&mut self.s, "["));
953 try!(self.print_type(&**ty));
954 try!(word(&mut self.s, "]"));
956 ast::TyPtr(ref mt) => {
957 try!(word(&mut self.s, "*"));
959 ast::MutMutable => try!(self.word_nbsp("mut")),
960 ast::MutImmutable => try!(self.word_nbsp("const")),
962 try!(self.print_type(&*mt.ty));
964 ast::TyRptr(ref lifetime, ref mt) => {
965 try!(word(&mut self.s, "&"));
966 try!(self.print_opt_lifetime(lifetime));
967 try!(self.print_mt(mt));
969 ast::TyTup(ref elts) => {
971 try!(self.commasep(Inconsistent, &elts[..],
972 |s, ty| s.print_type(&**ty)));
974 try!(word(&mut self.s, ","));
978 ast::TyParen(ref typ) => {
980 try!(self.print_type(&**typ));
983 ast::TyBareFn(ref f) => {
984 let generics = ast::Generics {
985 lifetimes: f.lifetimes.clone(),
986 ty_params: OwnedSlice::empty(),
987 where_clause: ast::WhereClause {
988 id: ast::DUMMY_NODE_ID,
989 predicates: Vec::new(),
992 try!(self.print_ty_fn(f.abi,
999 ast::TyPath(None, ref path) => {
1000 try!(self.print_path(path, false, 0));
1002 ast::TyPath(Some(ref qself), ref path) => {
1003 try!(self.print_qpath(path, qself, false))
1005 ast::TyObjectSum(ref ty, ref bounds) => {
1006 try!(self.print_type(&**ty));
1007 try!(self.print_bounds("+", &bounds[..]));
1009 ast::TyPolyTraitRef(ref bounds) => {
1010 try!(self.print_bounds("", &bounds[..]));
1012 ast::TyFixedLengthVec(ref ty, ref v) => {
1013 try!(word(&mut self.s, "["));
1014 try!(self.print_type(&**ty));
1015 try!(word(&mut self.s, "; "));
1016 try!(self.print_expr(&**v));
1017 try!(word(&mut self.s, "]"));
1019 ast::TyTypeof(ref e) => {
1020 try!(word(&mut self.s, "typeof("));
1021 try!(self.print_expr(&**e));
1022 try!(word(&mut self.s, ")"));
1025 try!(word(&mut self.s, "_"));
1027 ast::TyMac(ref m) => {
1028 try!(self.print_mac(m, token::Paren));
1034 pub fn print_foreign_item(&mut self,
1035 item: &ast::ForeignItem) -> io::Result<()> {
1036 try!(self.hardbreak_if_not_bol());
1037 try!(self.maybe_print_comment(item.span.lo));
1038 try!(self.print_outer_attributes(&item.attrs));
1040 ast::ForeignItemFn(ref decl, ref generics) => {
1041 try!(self.head(""));
1042 try!(self.print_fn(decl, ast::Unsafety::Normal,
1043 ast::Constness::NotConst,
1044 abi::Rust, Some(item.ident),
1045 generics, None, item.vis));
1046 try!(self.end()); // end head-ibox
1047 try!(word(&mut self.s, ";"));
1048 self.end() // end the outer fn box
1050 ast::ForeignItemStatic(ref t, m) => {
1051 try!(self.head(&visibility_qualified(item.vis,
1054 try!(self.word_space("mut"));
1056 try!(self.print_ident(item.ident));
1057 try!(self.word_space(":"));
1058 try!(self.print_type(&**t));
1059 try!(word(&mut self.s, ";"));
1060 try!(self.end()); // end the head-ibox
1061 self.end() // end the outer cbox
1066 fn print_associated_const(&mut self,
1069 default: Option<&ast::Expr>,
1070 vis: ast::Visibility)
1073 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1074 try!(self.word_space("const"));
1075 try!(self.print_ident(ident));
1076 try!(self.word_space(":"));
1077 try!(self.print_type(ty));
1078 if let Some(expr) = default {
1079 try!(space(&mut self.s));
1080 try!(self.word_space("="));
1081 try!(self.print_expr(expr));
1083 word(&mut self.s, ";")
1086 fn print_associated_type(&mut self,
1088 bounds: Option<&ast::TyParamBounds>,
1089 ty: Option<&ast::Ty>)
1091 try!(self.word_space("type"));
1092 try!(self.print_ident(ident));
1093 if let Some(bounds) = bounds {
1094 try!(self.print_bounds(":", bounds));
1096 if let Some(ty) = ty {
1097 try!(space(&mut self.s));
1098 try!(self.word_space("="));
1099 try!(self.print_type(ty));
1101 word(&mut self.s, ";")
1104 /// Pretty-print an item
1105 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1106 try!(self.hardbreak_if_not_bol());
1107 try!(self.maybe_print_comment(item.span.lo));
1108 try!(self.print_outer_attributes(&item.attrs));
1109 try!(self.ann.pre(self, NodeItem(item)));
1111 ast::ItemExternCrate(ref optional_path) => {
1112 try!(self.head(&visibility_qualified(item.vis,
1114 if let Some(p) = *optional_path {
1115 let val = p.as_str();
1116 if val.contains("-") {
1117 try!(self.print_string(&val, ast::CookedStr));
1119 try!(self.print_name(p));
1121 try!(space(&mut self.s));
1122 try!(word(&mut self.s, "as"));
1123 try!(space(&mut self.s));
1125 try!(self.print_ident(item.ident));
1126 try!(word(&mut self.s, ";"));
1127 try!(self.end()); // end inner head-block
1128 try!(self.end()); // end outer head-block
1130 ast::ItemUse(ref vp) => {
1131 try!(self.head(&visibility_qualified(item.vis,
1133 try!(self.print_view_path(&**vp));
1134 try!(word(&mut self.s, ";"));
1135 try!(self.end()); // end inner head-block
1136 try!(self.end()); // end outer head-block
1138 ast::ItemStatic(ref ty, m, ref expr) => {
1139 try!(self.head(&visibility_qualified(item.vis,
1141 if m == ast::MutMutable {
1142 try!(self.word_space("mut"));
1144 try!(self.print_ident(item.ident));
1145 try!(self.word_space(":"));
1146 try!(self.print_type(&**ty));
1147 try!(space(&mut self.s));
1148 try!(self.end()); // end the head-ibox
1150 try!(self.word_space("="));
1151 try!(self.print_expr(&**expr));
1152 try!(word(&mut self.s, ";"));
1153 try!(self.end()); // end the outer cbox
1155 ast::ItemConst(ref ty, ref expr) => {
1156 try!(self.head(&visibility_qualified(item.vis,
1158 try!(self.print_ident(item.ident));
1159 try!(self.word_space(":"));
1160 try!(self.print_type(&**ty));
1161 try!(space(&mut self.s));
1162 try!(self.end()); // end the head-ibox
1164 try!(self.word_space("="));
1165 try!(self.print_expr(&**expr));
1166 try!(word(&mut self.s, ";"));
1167 try!(self.end()); // end the outer cbox
1169 ast::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1170 try!(self.head(""));
1181 try!(word(&mut self.s, " "));
1182 try!(self.print_block_with_attrs(&**body, &item.attrs));
1184 ast::ItemMod(ref _mod) => {
1185 try!(self.head(&visibility_qualified(item.vis,
1187 try!(self.print_ident(item.ident));
1190 try!(self.print_mod(_mod, &item.attrs));
1191 try!(self.bclose(item.span));
1193 ast::ItemForeignMod(ref nmod) => {
1194 try!(self.head("extern"));
1195 try!(self.word_nbsp(&nmod.abi.to_string()));
1197 try!(self.print_foreign_mod(nmod, &item.attrs));
1198 try!(self.bclose(item.span));
1200 ast::ItemTy(ref ty, ref params) => {
1201 try!(self.ibox(indent_unit));
1203 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
1204 try!(self.print_ident(item.ident));
1205 try!(self.print_generics(params));
1206 try!(self.end()); // end the inner ibox
1208 try!(self.print_where_clause(¶ms.where_clause));
1209 try!(space(&mut self.s));
1210 try!(self.word_space("="));
1211 try!(self.print_type(&**ty));
1212 try!(word(&mut self.s, ";"));
1213 try!(self.end()); // end the outer ibox
1215 ast::ItemEnum(ref enum_definition, ref params) => {
1216 try!(self.print_enum_def(
1224 ast::ItemStruct(ref struct_def, ref generics) => {
1225 try!(self.head(&visibility_qualified(item.vis,"struct")));
1226 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
1229 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
1230 try!(self.head(""));
1231 try!(self.print_visibility(item.vis));
1232 try!(self.print_unsafety(unsafety));
1233 try!(self.word_nbsp("impl"));
1234 try!(self.print_trait_ref(trait_ref));
1235 try!(space(&mut self.s));
1236 try!(self.word_space("for"));
1237 try!(self.word_space(".."));
1239 try!(self.bclose(item.span));
1241 ast::ItemImpl(unsafety,
1246 ref impl_items) => {
1247 try!(self.head(""));
1248 try!(self.print_visibility(item.vis));
1249 try!(self.print_unsafety(unsafety));
1250 try!(self.word_nbsp("impl"));
1252 if generics.is_parameterized() {
1253 try!(self.print_generics(generics));
1254 try!(space(&mut self.s));
1258 ast::ImplPolarity::Negative => {
1259 try!(word(&mut self.s, "!"));
1266 try!(self.print_trait_ref(t));
1267 try!(space(&mut self.s));
1268 try!(self.word_space("for"));
1273 try!(self.print_type(&**ty));
1274 try!(self.print_where_clause(&generics.where_clause));
1276 try!(space(&mut self.s));
1278 try!(self.print_inner_attributes(&item.attrs));
1279 for impl_item in impl_items {
1280 try!(self.print_impl_item(impl_item));
1282 try!(self.bclose(item.span));
1284 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
1285 try!(self.head(""));
1286 try!(self.print_visibility(item.vis));
1287 try!(self.print_unsafety(unsafety));
1288 try!(self.word_nbsp("trait"));
1289 try!(self.print_ident(item.ident));
1290 try!(self.print_generics(generics));
1291 let mut real_bounds = Vec::with_capacity(bounds.len());
1292 for b in bounds.iter() {
1293 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1294 try!(space(&mut self.s));
1295 try!(self.word_space("for ?"));
1296 try!(self.print_trait_ref(&ptr.trait_ref));
1298 real_bounds.push(b.clone());
1301 try!(self.print_bounds(":", &real_bounds[..]));
1302 try!(self.print_where_clause(&generics.where_clause));
1303 try!(word(&mut self.s, " "));
1305 for trait_item in trait_items {
1306 try!(self.print_trait_item(trait_item));
1308 try!(self.bclose(item.span));
1310 // I think it's reasonable to hide the context here:
1311 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1313 try!(self.print_visibility(item.vis));
1314 try!(self.print_path(pth, 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(&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::StructDef,
1391 generics: &ast::Generics,
1393 span: codemap::Span) -> io::Result<()> {
1394 try!(self.print_ident(ident));
1395 try!(self.print_generics(generics));
1396 if ast_util::struct_def_is_tuple_like(struct_def) {
1397 if !struct_def.fields.is_empty() {
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 try!(word(&mut self.s, ";"));
1417 self.end() // close the outer-box
1419 try!(self.print_where_clause(&generics.where_clause));
1422 try!(self.hardbreak_if_not_bol());
1424 for field in &struct_def.fields {
1425 match field.node.kind {
1426 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1427 ast::NamedField(ident, visibility) => {
1428 try!(self.hardbreak_if_not_bol());
1429 try!(self.maybe_print_comment(field.span.lo));
1430 try!(self.print_outer_attributes(&field.node.attrs));
1431 try!(self.print_visibility(visibility));
1432 try!(self.print_ident(ident));
1433 try!(self.word_nbsp(":"));
1434 try!(self.print_type(&*field.node.ty));
1435 try!(word(&mut self.s, ","));
1444 /// This doesn't deserve to be called "pretty" printing, but it should be
1445 /// meaning-preserving. A quick hack that might help would be to look at the
1446 /// spans embedded in the TTs to decide where to put spaces and newlines.
1447 /// But it'd be better to parse these according to the grammar of the
1448 /// appropriate macro, transcribe back into the grammar we just parsed from,
1449 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1450 /// expression arguments as expressions). It can be done! I think.
1451 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1453 ast::TtToken(_, ref tk) => {
1454 try!(word(&mut self.s, &token_to_string(tk)));
1456 parse::token::DocComment(..) => {
1457 hardbreak(&mut self.s)
1462 ast::TtDelimited(_, ref delimed) => {
1463 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1464 try!(space(&mut self.s));
1465 try!(self.print_tts(&delimed.tts));
1466 try!(space(&mut self.s));
1467 word(&mut self.s, &token_to_string(&delimed.close_token()))
1469 ast::TtSequence(_, ref seq) => {
1470 try!(word(&mut self.s, "$("));
1471 for tt_elt in &seq.tts {
1472 try!(self.print_tt(tt_elt));
1474 try!(word(&mut self.s, ")"));
1475 match seq.separator {
1477 try!(word(&mut self.s, &token_to_string(tk)));
1482 ast::ZeroOrMore => word(&mut self.s, "*"),
1483 ast::OneOrMore => word(&mut self.s, "+"),
1489 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1491 let mut suppress_space = false;
1492 for (i, tt) in tts.iter().enumerate() {
1493 if i != 0 && !suppress_space {
1494 try!(space(&mut self.s));
1496 try!(self.print_tt(tt));
1497 // There should be no space between the module name and the following `::` in paths,
1498 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1499 suppress_space = match tt {
1500 &ast::TtToken(_, token::Ident(_, token::ModName)) |
1501 &ast::TtToken(_, token::MatchNt(_, _, _, token::ModName)) |
1502 &ast::TtToken(_, token::SubstNt(_, token::ModName)) => true,
1509 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1511 ast::TupleVariantKind(ref args) => {
1512 try!(self.print_ident(v.node.name));
1513 if !args.is_empty() {
1515 try!(self.commasep(Consistent,
1517 |s, arg| s.print_type(&*arg.ty)));
1518 try!(self.pclose());
1521 ast::StructVariantKind(ref struct_def) => {
1522 try!(self.head(""));
1523 let generics = ast_util::empty_generics();
1524 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1527 match v.node.disr_expr {
1529 try!(space(&mut self.s));
1530 try!(self.word_space("="));
1531 self.print_expr(&**d)
1537 pub fn print_method_sig(&mut self,
1540 vis: ast::Visibility)
1542 self.print_fn(&m.decl,
1548 Some(&m.explicit_self.node),
1552 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1554 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1555 try!(self.hardbreak_if_not_bol());
1556 try!(self.maybe_print_comment(ti.span.lo));
1557 try!(self.print_outer_attributes(&ti.attrs));
1559 ast::ConstTraitItem(ref ty, ref default) => {
1560 try!(self.print_associated_const(ti.ident, &ty,
1561 default.as_ref().map(|expr| &**expr),
1564 ast::MethodTraitItem(ref sig, ref body) => {
1566 try!(self.head(""));
1568 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1569 if let Some(ref body) = *body {
1571 try!(self.print_block_with_attrs(body, &ti.attrs));
1573 try!(word(&mut self.s, ";"));
1576 ast::TypeTraitItem(ref bounds, ref default) => {
1577 try!(self.print_associated_type(ti.ident, Some(bounds),
1578 default.as_ref().map(|ty| &**ty)));
1581 self.ann.post(self, NodeSubItem(ti.id))
1584 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1585 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1586 try!(self.hardbreak_if_not_bol());
1587 try!(self.maybe_print_comment(ii.span.lo));
1588 try!(self.print_outer_attributes(&ii.attrs));
1590 ast::ConstImplItem(ref ty, ref expr) => {
1591 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1593 ast::MethodImplItem(ref sig, ref body) => {
1594 try!(self.head(""));
1595 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1597 try!(self.print_block_with_attrs(body, &ii.attrs));
1599 ast::TypeImplItem(ref ty) => {
1600 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1602 ast::MacImplItem(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1604 // code copied from ItemMac:
1605 try!(self.print_path(pth, false, 0));
1606 try!(word(&mut self.s, "! "));
1607 try!(self.cbox(indent_unit));
1609 try!(self.print_tts(&tts[..]));
1610 try!(self.pclose());
1611 try!(word(&mut self.s, ";"));
1615 self.ann.post(self, NodeSubItem(ii.id))
1618 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1619 try!(self.maybe_print_comment(st.span.lo));
1621 ast::StmtDecl(ref decl, _) => {
1622 try!(self.print_decl(&**decl));
1624 ast::StmtExpr(ref expr, _) => {
1625 try!(self.space_if_not_bol());
1626 try!(self.print_expr(&**expr));
1628 ast::StmtSemi(ref expr, _) => {
1629 try!(self.space_if_not_bol());
1630 try!(self.print_expr(&**expr));
1631 try!(word(&mut self.s, ";"));
1633 ast::StmtMac(ref mac, style) => {
1634 try!(self.space_if_not_bol());
1635 let delim = match style {
1636 ast::MacStmtWithBraces => token::Brace,
1639 try!(self.print_mac(&**mac, delim));
1641 ast::MacStmtWithBraces => {}
1642 _ => try!(word(&mut self.s, ";")),
1646 if parse::classify::stmt_ends_with_semi(&st.node) {
1647 try!(word(&mut self.s, ";"));
1649 self.maybe_print_trailing_comment(st.span, None)
1652 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1653 self.print_block_with_attrs(blk, &[])
1656 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1657 self.print_block_unclosed_indent(blk, indent_unit)
1660 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1661 indented: usize) -> io::Result<()> {
1662 self.print_block_maybe_unclosed(blk, indented, &[], false)
1665 pub fn print_block_with_attrs(&mut self,
1667 attrs: &[ast::Attribute]) -> io::Result<()> {
1668 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1671 pub fn print_block_maybe_unclosed(&mut self,
1674 attrs: &[ast::Attribute],
1675 close_box: bool) -> io::Result<()> {
1677 ast::UnsafeBlock(..) | ast::PushUnsafeBlock(..) => try!(self.word_space("unsafe")),
1678 ast::DefaultBlock | ast::PopUnsafeBlock(..) => ()
1680 try!(self.maybe_print_comment(blk.span.lo));
1681 try!(self.ann.pre(self, NodeBlock(blk)));
1684 try!(self.print_inner_attributes(attrs));
1686 for st in &blk.stmts {
1687 try!(self.print_stmt(&**st));
1691 try!(self.space_if_not_bol());
1692 try!(self.print_expr(&**expr));
1693 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1697 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1698 self.ann.post(self, NodeBlock(blk))
1701 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1705 // "another else-if"
1706 ast::ExprIf(ref i, ref then, ref e) => {
1707 try!(self.cbox(indent_unit - 1));
1709 try!(word(&mut self.s, " else if "));
1710 try!(self.print_expr(&**i));
1711 try!(space(&mut self.s));
1712 try!(self.print_block(&**then));
1713 self.print_else(e.as_ref().map(|e| &**e))
1715 // "another else-if-let"
1716 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1717 try!(self.cbox(indent_unit - 1));
1719 try!(word(&mut self.s, " else if let "));
1720 try!(self.print_pat(&**pat));
1721 try!(space(&mut self.s));
1722 try!(self.word_space("="));
1723 try!(self.print_expr(&**expr));
1724 try!(space(&mut self.s));
1725 try!(self.print_block(&**then));
1726 self.print_else(e.as_ref().map(|e| &**e))
1729 ast::ExprBlock(ref b) => {
1730 try!(self.cbox(indent_unit - 1));
1732 try!(word(&mut self.s, " else "));
1733 self.print_block(&**b)
1735 // BLEAH, constraints would be great here
1737 panic!("print_if saw if with weird alternative");
1745 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1746 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1747 try!(self.head("if"));
1748 try!(self.print_expr(test));
1749 try!(space(&mut self.s));
1750 try!(self.print_block(blk));
1751 self.print_else(elseopt)
1754 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1755 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1756 try!(self.head("if let"));
1757 try!(self.print_pat(pat));
1758 try!(space(&mut self.s));
1759 try!(self.word_space("="));
1760 try!(self.print_expr(expr));
1761 try!(space(&mut self.s));
1762 try!(self.print_block(blk));
1763 self.print_else(elseopt)
1766 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1769 // I think it's reasonable to hide the ctxt here:
1770 ast::MacInvocTT(ref pth, ref tts, _) => {
1771 try!(self.print_path(pth, false, 0));
1772 try!(word(&mut self.s, "!"));
1774 token::Paren => try!(self.popen()),
1775 token::Bracket => try!(word(&mut self.s, "[")),
1776 token::Brace => try!(self.bopen()),
1778 try!(self.print_tts(tts));
1780 token::Paren => self.pclose(),
1781 token::Bracket => word(&mut self.s, "]"),
1782 token::Brace => self.bclose(m.span),
1789 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1791 try!(self.commasep_exprs(Inconsistent, args));
1795 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1796 binop: ast::BinOp) -> bool {
1797 match sub_expr.node {
1798 ast::ExprBinary(ref sub_op, _, _) => {
1799 if ast_util::operator_prec(sub_op.node) <
1800 ast_util::operator_prec(binop.node) {
1810 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1811 let needs_par = needs_parentheses(expr);
1815 try!(self.print_expr(expr));
1817 try!(self.pclose());
1822 fn print_expr_box(&mut self,
1823 place: &Option<P<ast::Expr>>,
1824 expr: &ast::Expr) -> io::Result<()> {
1825 try!(word(&mut self.s, "box"));
1826 try!(word(&mut self.s, "("));
1827 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1828 try!(self.word_space(")"));
1829 self.print_expr(expr)
1832 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1833 try!(self.ibox(indent_unit));
1834 try!(word(&mut self.s, "["));
1835 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1836 try!(word(&mut self.s, "]"));
1840 fn print_expr_repeat(&mut self,
1841 element: &ast::Expr,
1842 count: &ast::Expr) -> io::Result<()> {
1843 try!(self.ibox(indent_unit));
1844 try!(word(&mut self.s, "["));
1845 try!(self.print_expr(element));
1846 try!(self.word_space(";"));
1847 try!(self.print_expr(count));
1848 try!(word(&mut self.s, "]"));
1852 fn print_expr_struct(&mut self,
1854 fields: &[ast::Field],
1855 wth: &Option<P<ast::Expr>>) -> io::Result<()> {
1856 try!(self.print_path(path, true, 0));
1857 try!(word(&mut self.s, "{"));
1858 try!(self.commasep_cmnt(
1862 try!(s.ibox(indent_unit));
1863 try!(s.print_ident(field.ident.node));
1864 try!(s.word_space(":"));
1865 try!(s.print_expr(&*field.expr));
1871 try!(self.ibox(indent_unit));
1872 if !fields.is_empty() {
1873 try!(word(&mut self.s, ","));
1874 try!(space(&mut self.s));
1876 try!(word(&mut self.s, ".."));
1877 try!(self.print_expr(&**expr));
1880 _ => if !fields.is_empty() {
1881 try!(word(&mut self.s, ","))
1884 try!(word(&mut self.s, "}"));
1888 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1890 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1891 if exprs.len() == 1 {
1892 try!(word(&mut self.s, ","));
1897 fn print_expr_call(&mut self,
1899 args: &[P<ast::Expr>]) -> io::Result<()> {
1900 try!(self.print_expr_maybe_paren(func));
1901 self.print_call_post(args)
1904 fn print_expr_method_call(&mut self,
1905 ident: ast::SpannedIdent,
1907 args: &[P<ast::Expr>]) -> io::Result<()> {
1908 let base_args = &args[1..];
1909 try!(self.print_expr(&*args[0]));
1910 try!(word(&mut self.s, "."));
1911 try!(self.print_ident(ident.node));
1912 if !tys.is_empty() {
1913 try!(word(&mut self.s, "::<"));
1914 try!(self.commasep(Inconsistent, tys,
1915 |s, ty| s.print_type(&**ty)));
1916 try!(word(&mut self.s, ">"));
1918 self.print_call_post(base_args)
1921 fn print_expr_binary(&mut self,
1924 rhs: &ast::Expr) -> io::Result<()> {
1925 if self.check_expr_bin_needs_paren(lhs, op) {
1926 try!(self.print_expr_maybe_paren(lhs));
1928 try!(self.print_expr(lhs));
1930 try!(space(&mut self.s));
1931 try!(self.word_space(ast_util::binop_to_string(op.node)));
1932 if self.check_expr_bin_needs_paren(rhs, op) {
1933 self.print_expr_maybe_paren(rhs)
1935 self.print_expr(rhs)
1939 fn print_expr_unary(&mut self,
1941 expr: &ast::Expr) -> io::Result<()> {
1942 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1943 self.print_expr_maybe_paren(expr)
1946 fn print_expr_addr_of(&mut self,
1947 mutability: ast::Mutability,
1948 expr: &ast::Expr) -> io::Result<()> {
1949 try!(word(&mut self.s, "&"));
1950 try!(self.print_mutability(mutability));
1951 self.print_expr_maybe_paren(expr)
1954 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1955 try!(self.maybe_print_comment(expr.span.lo));
1956 try!(self.ibox(indent_unit));
1957 try!(self.ann.pre(self, NodeExpr(expr)));
1959 ast::ExprBox(ref place, ref expr) => {
1960 try!(self.print_expr_box(place, &**expr));
1962 ast::ExprVec(ref exprs) => {
1963 try!(self.print_expr_vec(&exprs[..]));
1965 ast::ExprRepeat(ref element, ref count) => {
1966 try!(self.print_expr_repeat(&**element, &**count));
1968 ast::ExprStruct(ref path, ref fields, ref wth) => {
1969 try!(self.print_expr_struct(path, &fields[..], wth));
1971 ast::ExprTup(ref exprs) => {
1972 try!(self.print_expr_tup(&exprs[..]));
1974 ast::ExprCall(ref func, ref args) => {
1975 try!(self.print_expr_call(&**func, &args[..]));
1977 ast::ExprMethodCall(ident, ref tys, ref args) => {
1978 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1980 ast::ExprBinary(op, ref lhs, ref rhs) => {
1981 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1983 ast::ExprUnary(op, ref expr) => {
1984 try!(self.print_expr_unary(op, &**expr));
1986 ast::ExprAddrOf(m, ref expr) => {
1987 try!(self.print_expr_addr_of(m, &**expr));
1989 ast::ExprLit(ref lit) => {
1990 try!(self.print_literal(&**lit));
1992 ast::ExprCast(ref expr, ref ty) => {
1993 if let ast::ExprCast(..) = expr.node {
1994 try!(self.print_expr(&**expr));
1996 try!(self.print_expr_maybe_paren(&**expr));
1998 try!(space(&mut self.s));
1999 try!(self.word_space("as"));
2000 try!(self.print_type(&**ty));
2002 ast::ExprIf(ref test, ref blk, ref elseopt) => {
2003 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
2005 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2006 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
2008 ast::ExprWhile(ref test, ref blk, opt_ident) => {
2009 if let Some(ident) = opt_ident {
2010 try!(self.print_ident(ident));
2011 try!(self.word_space(":"));
2013 try!(self.head("while"));
2014 try!(self.print_expr(&**test));
2015 try!(space(&mut self.s));
2016 try!(self.print_block(&**blk));
2018 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2019 if let Some(ident) = opt_ident {
2020 try!(self.print_ident(ident));
2021 try!(self.word_space(":"));
2023 try!(self.head("while let"));
2024 try!(self.print_pat(&**pat));
2025 try!(space(&mut self.s));
2026 try!(self.word_space("="));
2027 try!(self.print_expr(&**expr));
2028 try!(space(&mut self.s));
2029 try!(self.print_block(&**blk));
2031 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2032 if let Some(ident) = opt_ident {
2033 try!(self.print_ident(ident));
2034 try!(self.word_space(":"));
2036 try!(self.head("for"));
2037 try!(self.print_pat(&**pat));
2038 try!(space(&mut self.s));
2039 try!(self.word_space("in"));
2040 try!(self.print_expr(&**iter));
2041 try!(space(&mut self.s));
2042 try!(self.print_block(&**blk));
2044 ast::ExprLoop(ref blk, opt_ident) => {
2045 if let Some(ident) = opt_ident {
2046 try!(self.print_ident(ident));
2047 try!(self.word_space(":"));
2049 try!(self.head("loop"));
2050 try!(space(&mut self.s));
2051 try!(self.print_block(&**blk));
2053 ast::ExprMatch(ref expr, ref arms, _) => {
2054 try!(self.cbox(indent_unit));
2056 try!(self.word_nbsp("match"));
2057 try!(self.print_expr(&**expr));
2058 try!(space(&mut self.s));
2061 try!(self.print_arm(arm));
2063 try!(self.bclose_(expr.span, indent_unit));
2065 ast::ExprClosure(capture_clause, ref decl, ref body) => {
2066 try!(self.print_capture_clause(capture_clause));
2068 try!(self.print_fn_block_args(&**decl));
2069 try!(space(&mut self.s));
2071 let default_return = match decl.output {
2072 ast::DefaultReturn(..) => true,
2076 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2077 try!(self.print_block_unclosed(&**body));
2079 // we extract the block, so as not to create another set of boxes
2080 match body.expr.as_ref().unwrap().node {
2081 ast::ExprBlock(ref blk) => {
2082 try!(self.print_block_unclosed(&**blk));
2085 // this is a bare expression
2086 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
2087 try!(self.end()); // need to close a box
2091 // a box will be closed by print_expr, but we didn't want an overall
2092 // wrapper so we closed the corresponding opening. so create an
2093 // empty box to satisfy the close.
2096 ast::ExprBlock(ref blk) => {
2097 // containing cbox, will be closed by print-block at }
2098 try!(self.cbox(indent_unit));
2099 // head-box, will be closed by print-block after {
2101 try!(self.print_block(&**blk));
2103 ast::ExprAssign(ref lhs, ref rhs) => {
2104 try!(self.print_expr(&**lhs));
2105 try!(space(&mut self.s));
2106 try!(self.word_space("="));
2107 try!(self.print_expr(&**rhs));
2109 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
2110 try!(self.print_expr(&**lhs));
2111 try!(space(&mut self.s));
2112 try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
2113 try!(self.word_space("="));
2114 try!(self.print_expr(&**rhs));
2116 ast::ExprField(ref expr, id) => {
2117 try!(self.print_expr(&**expr));
2118 try!(word(&mut self.s, "."));
2119 try!(self.print_ident(id.node));
2121 ast::ExprTupField(ref expr, id) => {
2122 try!(self.print_expr(&**expr));
2123 try!(word(&mut self.s, "."));
2124 try!(self.print_usize(id.node));
2126 ast::ExprIndex(ref expr, ref index) => {
2127 try!(self.print_expr(&**expr));
2128 try!(word(&mut self.s, "["));
2129 try!(self.print_expr(&**index));
2130 try!(word(&mut self.s, "]"));
2132 ast::ExprRange(ref start, ref end) => {
2133 if let &Some(ref e) = start {
2134 try!(self.print_expr(&**e));
2136 try!(word(&mut self.s, ".."));
2137 if let &Some(ref e) = end {
2138 try!(self.print_expr(&**e));
2141 ast::ExprPath(None, ref path) => {
2142 try!(self.print_path(path, true, 0))
2144 ast::ExprPath(Some(ref qself), ref path) => {
2145 try!(self.print_qpath(path, qself, true))
2147 ast::ExprBreak(opt_ident) => {
2148 try!(word(&mut self.s, "break"));
2149 try!(space(&mut self.s));
2150 if let Some(ident) = opt_ident {
2151 try!(self.print_ident(ident.node));
2152 try!(space(&mut self.s));
2155 ast::ExprAgain(opt_ident) => {
2156 try!(word(&mut self.s, "continue"));
2157 try!(space(&mut self.s));
2158 if let Some(ident) = opt_ident {
2159 try!(self.print_ident(ident.node));
2160 try!(space(&mut self.s))
2163 ast::ExprRet(ref result) => {
2164 try!(word(&mut self.s, "return"));
2167 try!(word(&mut self.s, " "));
2168 try!(self.print_expr(&**expr));
2173 ast::ExprInlineAsm(ref a) => {
2174 try!(word(&mut self.s, "asm!"));
2176 try!(self.print_string(&a.asm, a.asm_str_style));
2177 try!(self.word_space(":"));
2179 try!(self.commasep(Inconsistent, &a.outputs,
2180 |s, &(ref co, ref o, is_rw)| {
2181 match co.slice_shift_char() {
2182 Some(('=', operand)) if is_rw => {
2183 try!(s.print_string(&format!("+{}", operand),
2186 _ => try!(s.print_string(&co, ast::CookedStr))
2189 try!(s.print_expr(&**o));
2193 try!(space(&mut self.s));
2194 try!(self.word_space(":"));
2196 try!(self.commasep(Inconsistent, &a.inputs,
2197 |s, &(ref co, ref o)| {
2198 try!(s.print_string(&co, ast::CookedStr));
2200 try!(s.print_expr(&**o));
2204 try!(space(&mut self.s));
2205 try!(self.word_space(":"));
2207 try!(self.commasep(Inconsistent, &a.clobbers,
2209 try!(s.print_string(&co, ast::CookedStr));
2213 let mut options = vec!();
2215 options.push("volatile");
2218 options.push("alignstack");
2220 if a.dialect == ast::AsmDialect::AsmIntel {
2221 options.push("intel");
2224 if !options.is_empty() {
2225 try!(space(&mut self.s));
2226 try!(self.word_space(":"));
2227 try!(self.commasep(Inconsistent, &*options,
2229 try!(s.print_string(co, ast::CookedStr));
2234 try!(self.pclose());
2236 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
2237 ast::ExprParen(ref e) => {
2239 try!(self.print_expr(&**e));
2240 try!(self.pclose());
2243 try!(self.ann.post(self, NodeExpr(expr)));
2247 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2248 try!(self.print_pat(&*loc.pat));
2249 if let Some(ref ty) = loc.ty {
2250 try!(self.word_space(":"));
2251 try!(self.print_type(&**ty));
2256 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2257 try!(self.maybe_print_comment(decl.span.lo));
2259 ast::DeclLocal(ref loc) => {
2260 try!(self.space_if_not_bol());
2261 try!(self.ibox(indent_unit));
2262 try!(self.word_nbsp("let"));
2264 try!(self.ibox(indent_unit));
2265 try!(self.print_local_decl(&**loc));
2267 if let Some(ref init) = loc.init {
2269 try!(self.word_space("="));
2270 try!(self.print_expr(&**init));
2274 ast::DeclItem(ref item) => self.print_item(&**item)
2278 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2279 try!(word(&mut self.s, &ident.name.as_str()));
2280 self.ann.post(self, NodeIdent(&ident))
2283 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2284 word(&mut self.s, &i.to_string())
2287 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2288 try!(word(&mut self.s, &name.as_str()));
2289 self.ann.post(self, NodeName(&name))
2292 pub fn print_for_decl(&mut self, loc: &ast::Local,
2293 coll: &ast::Expr) -> io::Result<()> {
2294 try!(self.print_local_decl(loc));
2295 try!(space(&mut self.s));
2296 try!(self.word_space("in"));
2297 self.print_expr(coll)
2300 fn print_path(&mut self,
2302 colons_before_params: bool,
2306 try!(self.maybe_print_comment(path.span.lo));
2308 let mut first = !path.global;
2309 for segment in &path.segments[..path.segments.len()-depth] {
2313 try!(word(&mut self.s, "::"))
2316 try!(self.print_ident(segment.identifier));
2318 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2324 fn print_qpath(&mut self,
2327 colons_before_params: bool)
2330 try!(word(&mut self.s, "<"));
2331 try!(self.print_type(&qself.ty));
2332 if qself.position > 0 {
2333 try!(space(&mut self.s));
2334 try!(self.word_space("as"));
2335 let depth = path.segments.len() - qself.position;
2336 try!(self.print_path(&path, false, depth));
2338 try!(word(&mut self.s, ">"));
2339 try!(word(&mut self.s, "::"));
2340 let item_segment = path.segments.last().unwrap();
2341 try!(self.print_ident(item_segment.identifier));
2342 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2345 fn print_path_parameters(&mut self,
2346 parameters: &ast::PathParameters,
2347 colons_before_params: bool)
2350 if parameters.is_empty() {
2354 if colons_before_params {
2355 try!(word(&mut self.s, "::"))
2359 ast::AngleBracketedParameters(ref data) => {
2360 try!(word(&mut self.s, "<"));
2362 let mut comma = false;
2363 for lifetime in &data.lifetimes {
2365 try!(self.word_space(","))
2367 try!(self.print_lifetime(lifetime));
2371 if !data.types.is_empty() {
2373 try!(self.word_space(","))
2378 |s, ty| s.print_type(&**ty)));
2382 for binding in data.bindings.iter() {
2384 try!(self.word_space(","))
2386 try!(self.print_ident(binding.ident));
2387 try!(space(&mut self.s));
2388 try!(self.word_space("="));
2389 try!(self.print_type(&*binding.ty));
2393 try!(word(&mut self.s, ">"))
2396 ast::ParenthesizedParameters(ref data) => {
2397 try!(word(&mut self.s, "("));
2401 |s, ty| s.print_type(&**ty)));
2402 try!(word(&mut self.s, ")"));
2407 try!(self.space_if_not_bol());
2408 try!(self.word_space("->"));
2409 try!(self.print_type(&**ty));
2418 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2419 try!(self.maybe_print_comment(pat.span.lo));
2420 try!(self.ann.pre(self, NodePat(pat)));
2421 /* Pat isn't normalized, but the beauty of it
2422 is that it doesn't matter */
2424 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2425 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2426 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2427 match binding_mode {
2428 ast::BindByRef(mutbl) => {
2429 try!(self.word_nbsp("ref"));
2430 try!(self.print_mutability(mutbl));
2432 ast::BindByValue(ast::MutImmutable) => {}
2433 ast::BindByValue(ast::MutMutable) => {
2434 try!(self.word_nbsp("mut"));
2437 try!(self.print_ident(path1.node));
2440 try!(word(&mut self.s, "@"));
2441 try!(self.print_pat(&**p));
2446 ast::PatEnum(ref path, ref args_) => {
2447 try!(self.print_path(path, true, 0));
2449 None => try!(word(&mut self.s, "(..)")),
2451 if !args.is_empty() {
2453 try!(self.commasep(Inconsistent, &args[..],
2454 |s, p| s.print_pat(&**p)));
2455 try!(self.pclose());
2460 ast::PatQPath(ref qself, ref path) => {
2461 try!(self.print_qpath(path, qself, false));
2463 ast::PatStruct(ref path, ref fields, etc) => {
2464 try!(self.print_path(path, true, 0));
2466 try!(self.word_space("{"));
2467 try!(self.commasep_cmnt(
2468 Consistent, &fields[..],
2470 try!(s.cbox(indent_unit));
2471 if !f.node.is_shorthand {
2472 try!(s.print_ident(f.node.ident));
2473 try!(s.word_nbsp(":"));
2475 try!(s.print_pat(&*f.node.pat));
2478 |f| f.node.pat.span));
2480 if !fields.is_empty() { try!(self.word_space(",")); }
2481 try!(word(&mut self.s, ".."));
2483 try!(space(&mut self.s));
2484 try!(word(&mut self.s, "}"));
2486 ast::PatTup(ref elts) => {
2488 try!(self.commasep(Inconsistent,
2490 |s, p| s.print_pat(&**p)));
2491 if elts.len() == 1 {
2492 try!(word(&mut self.s, ","));
2494 try!(self.pclose());
2496 ast::PatBox(ref inner) => {
2497 try!(word(&mut self.s, "box "));
2498 try!(self.print_pat(&**inner));
2500 ast::PatRegion(ref inner, mutbl) => {
2501 try!(word(&mut self.s, "&"));
2502 if mutbl == ast::MutMutable {
2503 try!(word(&mut self.s, "mut "));
2505 try!(self.print_pat(&**inner));
2507 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2508 ast::PatRange(ref begin, ref end) => {
2509 try!(self.print_expr(&**begin));
2510 try!(space(&mut self.s));
2511 try!(word(&mut self.s, "..."));
2512 try!(self.print_expr(&**end));
2514 ast::PatVec(ref before, ref slice, ref after) => {
2515 try!(word(&mut self.s, "["));
2516 try!(self.commasep(Inconsistent,
2518 |s, p| s.print_pat(&**p)));
2519 if let Some(ref p) = *slice {
2520 if !before.is_empty() { try!(self.word_space(",")); }
2521 try!(self.print_pat(&**p));
2523 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2524 // this case is handled by print_pat
2526 _ => try!(word(&mut self.s, "..")),
2528 if !after.is_empty() { try!(self.word_space(",")); }
2530 try!(self.commasep(Inconsistent,
2532 |s, p| s.print_pat(&**p)));
2533 try!(word(&mut self.s, "]"));
2535 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2537 self.ann.post(self, NodePat(pat))
2540 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2541 // I have no idea why this check is necessary, but here it
2543 if arm.attrs.is_empty() {
2544 try!(space(&mut self.s));
2546 try!(self.cbox(indent_unit));
2548 try!(self.print_outer_attributes(&arm.attrs));
2549 let mut first = true;
2550 for p in &arm.pats {
2554 try!(space(&mut self.s));
2555 try!(self.word_space("|"));
2557 try!(self.print_pat(&**p));
2559 try!(space(&mut self.s));
2560 if let Some(ref e) = arm.guard {
2561 try!(self.word_space("if"));
2562 try!(self.print_expr(&**e));
2563 try!(space(&mut self.s));
2565 try!(self.word_space("=>"));
2567 match arm.body.node {
2568 ast::ExprBlock(ref blk) => {
2569 // the block will close the pattern's ibox
2570 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2572 // If it is a user-provided unsafe block, print a comma after it
2573 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2574 try!(word(&mut self.s, ","));
2578 try!(self.end()); // close the ibox for the pattern
2579 try!(self.print_expr(&*arm.body));
2580 try!(word(&mut self.s, ","));
2583 self.end() // close enclosing cbox
2586 // Returns whether it printed anything
2587 fn print_explicit_self(&mut self,
2588 explicit_self: &ast::ExplicitSelf_,
2589 mutbl: ast::Mutability) -> io::Result<bool> {
2590 try!(self.print_mutability(mutbl));
2591 match *explicit_self {
2592 ast::SelfStatic => { return Ok(false); }
2593 ast::SelfValue(_) => {
2594 try!(word(&mut self.s, "self"));
2596 ast::SelfRegion(ref lt, m, _) => {
2597 try!(word(&mut self.s, "&"));
2598 try!(self.print_opt_lifetime(lt));
2599 try!(self.print_mutability(m));
2600 try!(word(&mut self.s, "self"));
2602 ast::SelfExplicit(ref typ, _) => {
2603 try!(word(&mut self.s, "self"));
2604 try!(self.word_space(":"));
2605 try!(self.print_type(&**typ));
2611 pub fn print_fn(&mut self,
2613 unsafety: ast::Unsafety,
2614 constness: ast::Constness,
2616 name: Option<ast::Ident>,
2617 generics: &ast::Generics,
2618 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2619 vis: ast::Visibility) -> io::Result<()> {
2620 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2622 if let Some(name) = name {
2624 try!(self.print_ident(name));
2626 try!(self.print_generics(generics));
2627 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2628 self.print_where_clause(&generics.where_clause)
2631 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2632 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2634 // It is unfortunate to duplicate the commasep logic, but we want the
2635 // self type and the args all in the same box.
2636 try!(self.rbox(0, Inconsistent));
2637 let mut first = true;
2638 if let Some(explicit_self) = opt_explicit_self {
2639 let m = match explicit_self {
2640 &ast::SelfStatic => ast::MutImmutable,
2641 _ => match decl.inputs[0].pat.node {
2642 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2643 _ => ast::MutImmutable
2646 first = !try!(self.print_explicit_self(explicit_self, m));
2649 // HACK(eddyb) ignore the separately printed self argument.
2650 let args = if first {
2657 if first { first = false; } else { try!(self.word_space(",")); }
2658 try!(self.print_arg(arg));
2664 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2665 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2668 try!(self.print_fn_args(decl, opt_explicit_self));
2670 try!(word(&mut self.s, ", ..."));
2672 try!(self.pclose());
2674 self.print_fn_output(decl)
2677 pub fn print_fn_block_args(
2681 try!(word(&mut self.s, "|"));
2682 try!(self.print_fn_args(decl, None));
2683 try!(word(&mut self.s, "|"));
2685 if let ast::DefaultReturn(..) = decl.output {
2689 try!(self.space_if_not_bol());
2690 try!(self.word_space("->"));
2692 ast::Return(ref ty) => {
2693 try!(self.print_type(&**ty));
2694 self.maybe_print_comment(ty.span.lo)
2696 ast::DefaultReturn(..) => unreachable!(),
2697 ast::NoReturn(span) => {
2698 try!(self.word_nbsp("!"));
2699 self.maybe_print_comment(span.lo)
2704 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2706 match capture_clause {
2707 ast::CaptureByValue => self.word_space("move"),
2708 ast::CaptureByRef => Ok(()),
2712 pub fn print_bounds(&mut self,
2714 bounds: &[ast::TyParamBound])
2716 if !bounds.is_empty() {
2717 try!(word(&mut self.s, prefix));
2718 let mut first = true;
2719 for bound in bounds {
2724 try!(self.word_space("+"));
2728 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2729 self.print_poly_trait_ref(tref)
2731 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2732 try!(word(&mut self.s, "?"));
2733 self.print_poly_trait_ref(tref)
2735 RegionTyParamBound(ref lt) => {
2736 self.print_lifetime(lt)
2746 pub fn print_lifetime(&mut self,
2747 lifetime: &ast::Lifetime)
2750 self.print_name(lifetime.name)
2753 pub fn print_lifetime_def(&mut self,
2754 lifetime: &ast::LifetimeDef)
2757 try!(self.print_lifetime(&lifetime.lifetime));
2759 for v in &lifetime.bounds {
2760 try!(word(&mut self.s, sep));
2761 try!(self.print_lifetime(v));
2767 pub fn print_generics(&mut self,
2768 generics: &ast::Generics)
2771 let total = generics.lifetimes.len() + generics.ty_params.len();
2776 try!(word(&mut self.s, "<"));
2778 let mut ints = Vec::new();
2783 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2784 if idx < generics.lifetimes.len() {
2785 let lifetime = &generics.lifetimes[idx];
2786 s.print_lifetime_def(lifetime)
2788 let idx = idx - generics.lifetimes.len();
2789 let param = &generics.ty_params[idx];
2790 s.print_ty_param(param)
2794 try!(word(&mut self.s, ">"));
2798 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2799 try!(self.print_ident(param.ident));
2800 try!(self.print_bounds(":", ¶m.bounds));
2801 match param.default {
2802 Some(ref default) => {
2803 try!(space(&mut self.s));
2804 try!(self.word_space("="));
2805 self.print_type(&**default)
2811 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2813 if where_clause.predicates.is_empty() {
2817 try!(space(&mut self.s));
2818 try!(self.word_space("where"));
2820 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2822 try!(self.word_space(","));
2826 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2830 try!(self.print_formal_lifetime_list(bound_lifetimes));
2831 try!(self.print_type(&**bounded_ty));
2832 try!(self.print_bounds(":", bounds));
2834 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2837 try!(self.print_lifetime(lifetime));
2838 try!(word(&mut self.s, ":"));
2840 for (i, bound) in bounds.iter().enumerate() {
2841 try!(self.print_lifetime(bound));
2844 try!(word(&mut self.s, ":"));
2848 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2849 try!(self.print_path(path, false, 0));
2850 try!(space(&mut self.s));
2851 try!(self.word_space("="));
2852 try!(self.print_type(&**ty));
2860 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2862 ast::ViewPathSimple(ident, ref path) => {
2863 try!(self.print_path(path, false, 0));
2865 // FIXME(#6993) can't compare identifiers directly here
2866 if path.segments.last().unwrap().identifier.name !=
2868 try!(space(&mut self.s));
2869 try!(self.word_space("as"));
2870 try!(self.print_ident(ident));
2876 ast::ViewPathGlob(ref path) => {
2877 try!(self.print_path(path, false, 0));
2878 word(&mut self.s, "::*")
2881 ast::ViewPathList(ref path, ref idents) => {
2882 if path.segments.is_empty() {
2883 try!(word(&mut self.s, "{"));
2885 try!(self.print_path(path, false, 0));
2886 try!(word(&mut self.s, "::{"));
2888 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2890 ast::PathListIdent { name, rename, .. } => {
2891 try!(s.print_ident(name));
2892 if let Some(ident) = rename {
2893 try!(space(&mut s.s));
2894 try!(s.word_space("as"));
2895 try!(s.print_ident(ident));
2899 ast::PathListMod { rename, .. } => {
2900 try!(word(&mut s.s, "self"));
2901 if let Some(ident) = rename {
2902 try!(space(&mut s.s));
2903 try!(s.word_space("as"));
2904 try!(s.print_ident(ident));
2910 word(&mut self.s, "}")
2915 pub fn print_mutability(&mut self,
2916 mutbl: ast::Mutability) -> io::Result<()> {
2918 ast::MutMutable => self.word_nbsp("mut"),
2919 ast::MutImmutable => Ok(()),
2923 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2924 try!(self.print_mutability(mt.mutbl));
2925 self.print_type(&*mt.ty)
2928 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2929 try!(self.ibox(indent_unit));
2930 match input.ty.node {
2931 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2933 match input.pat.node {
2934 ast::PatIdent(_, ref path1, _) if
2936 parse::token::special_idents::invalid.name => {
2940 try!(self.print_pat(&*input.pat));
2941 try!(word(&mut self.s, ":"));
2942 try!(space(&mut self.s));
2945 try!(self.print_type(&*input.ty));
2951 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2952 if let ast::DefaultReturn(..) = decl.output {
2956 try!(self.space_if_not_bol());
2957 try!(self.ibox(indent_unit));
2958 try!(self.word_space("->"));
2961 try!(self.word_nbsp("!")),
2962 ast::DefaultReturn(..) => unreachable!(),
2963 ast::Return(ref ty) =>
2964 try!(self.print_type(&**ty))
2969 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2974 pub fn print_ty_fn(&mut self,
2976 unsafety: ast::Unsafety,
2978 name: Option<ast::Ident>,
2979 generics: &ast::Generics,
2980 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2982 try!(self.ibox(indent_unit));
2983 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2984 try!(word(&mut self.s, "for"));
2985 try!(self.print_generics(generics));
2987 let generics = ast::Generics {
2988 lifetimes: Vec::new(),
2989 ty_params: OwnedSlice::empty(),
2990 where_clause: ast::WhereClause {
2991 id: ast::DUMMY_NODE_ID,
2992 predicates: Vec::new(),
2995 try!(self.print_fn(decl,
2997 ast::Constness::NotConst,
3006 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
3007 next_pos: Option<BytePos>)
3009 let cm = match self.cm {
3013 match self.next_comment() {
3015 if (*cmnt).style != comments::Trailing { return Ok(()) }
3016 let span_line = cm.lookup_char_pos(span.hi);
3017 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3018 let mut next = (*cmnt).pos + BytePos(1);
3019 match next_pos { None => (), Some(p) => next = p }
3020 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3021 span_line.line == comment_line.line {
3022 try!(self.print_comment(cmnt));
3023 self.cur_cmnt_and_lit.cur_cmnt += 1;
3031 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3032 // If there aren't any remaining comments, then we need to manually
3033 // make sure there is a line break at the end.
3034 if self.next_comment().is_none() {
3035 try!(hardbreak(&mut self.s));
3038 match self.next_comment() {
3040 try!(self.print_comment(cmnt));
3041 self.cur_cmnt_and_lit.cur_cmnt += 1;
3049 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3050 opt_abi: Option<abi::Abi>)
3053 Some(abi::Rust) => Ok(()),
3055 try!(self.word_nbsp("extern"));
3056 self.word_nbsp(&abi.to_string())
3062 pub fn print_extern_opt_abi(&mut self,
3063 opt_abi: Option<abi::Abi>) -> io::Result<()> {
3066 try!(self.word_nbsp("extern"));
3067 self.word_nbsp(&abi.to_string())
3073 pub fn print_fn_header_info(&mut self,
3074 unsafety: ast::Unsafety,
3075 constness: ast::Constness,
3077 vis: ast::Visibility) -> io::Result<()> {
3078 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3079 try!(self.print_unsafety(unsafety));
3082 ast::Constness::NotConst => {}
3083 ast::Constness::Const => try!(self.word_nbsp("const"))
3086 if abi != abi::Rust {
3087 try!(self.word_nbsp("extern"));
3088 try!(self.word_nbsp(&abi.to_string()));
3091 word(&mut self.s, "fn")
3094 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3096 ast::Unsafety::Normal => Ok(()),
3097 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3102 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3114 fn test_fun_to_string() {
3115 let abba_ident = token::str_to_ident("abba");
3117 let decl = ast::FnDecl {
3119 output: ast::DefaultReturn(codemap::DUMMY_SP),
3122 let generics = ast_util::empty_generics();
3123 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3124 ast::Constness::NotConst,
3131 fn test_variant_to_string() {
3132 let ident = token::str_to_ident("principal_skinner");
3134 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3137 // making this up as I go.... ?
3138 kind: ast::TupleVariantKind(Vec::new()),
3143 let varstr = variant_to_string(&var);
3144 assert_eq!(varstr, "principal_skinner");
3148 fn test_signed_int_to_string() {
3149 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3150 let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3151 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3152 lit_to_string(&codemap::dummy_spanned(neg_int)));