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, BlockCheckMode};
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use attr::ThinAttributesExt;
18 use util::parser::AssocOp;
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 pub const INDENT_UNIT: usize = 4;
95 pub const DEFAULT_COLUMNS: usize = 78;
97 /// Requires you to pass an input filename and reader so that
98 /// it can scan the input text for comments and literals to
100 pub fn print_crate<'a>(cm: &'a CodeMap,
101 span_diagnostic: &errors::Handler,
107 is_expanded: bool) -> io::Result<()> {
108 let mut s = State::new_from_input(cm,
115 if is_expanded && !std_inject::no_std(krate) {
116 // We need to print `#![no_std]` (and its feature gate) so that
117 // compiling pretty-printed source won't inject libstd again.
118 // However we don't want these attributes in the AST because
119 // of the feature gate, so we fake them up here.
121 // #![feature(prelude_import)]
122 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
123 let list = attr::mk_list_item(InternedString::new("feature"),
124 vec![prelude_import_meta]);
125 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
126 try!(s.print_attribute(&fake_attr));
129 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
130 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
131 try!(s.print_attribute(&fake_attr));
134 try!(s.print_mod(&krate.module, &krate.attrs));
135 try!(s.print_remaining_comments());
140 pub fn new_from_input(cm: &'a CodeMap,
141 span_diagnostic: &errors::Handler,
146 is_expanded: bool) -> State<'a> {
147 let (cmnts, lits) = comments::gather_comments_and_literals(
157 // If the code is post expansion, don't use the table of
158 // literals, since it doesn't correspond with the literals
159 // in the AST anymore.
160 if is_expanded { None } else { Some(lits) })
163 pub fn new(cm: &'a CodeMap,
166 comments: Option<Vec<comments::Comment>>,
167 literals: Option<Vec<comments::Literal>>) -> State<'a> {
169 s: pp::mk_printer(out, DEFAULT_COLUMNS),
173 cur_cmnt_and_lit: CurrentCommentAndLiteral {
183 pub fn to_string<F>(f: F) -> String where
184 F: FnOnce(&mut State) -> io::Result<()>,
186 let mut wr = Vec::new();
188 let mut printer = rust_printer(Box::new(&mut wr));
189 f(&mut printer).unwrap();
190 eof(&mut printer.s).unwrap();
192 String::from_utf8(wr).unwrap()
195 pub fn binop_to_string(op: BinOpToken) -> &'static str {
201 token::Percent => "%",
210 pub fn token_to_string(tok: &Token) -> String {
212 token::Eq => "=".to_string(),
213 token::Lt => "<".to_string(),
214 token::Le => "<=".to_string(),
215 token::EqEq => "==".to_string(),
216 token::Ne => "!=".to_string(),
217 token::Ge => ">=".to_string(),
218 token::Gt => ">".to_string(),
219 token::Not => "!".to_string(),
220 token::Tilde => "~".to_string(),
221 token::OrOr => "||".to_string(),
222 token::AndAnd => "&&".to_string(),
223 token::BinOp(op) => binop_to_string(op).to_string(),
224 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
226 /* Structural symbols */
227 token::At => "@".to_string(),
228 token::Dot => ".".to_string(),
229 token::DotDot => "..".to_string(),
230 token::DotDotDot => "...".to_string(),
231 token::Comma => ",".to_string(),
232 token::Semi => ";".to_string(),
233 token::Colon => ":".to_string(),
234 token::ModSep => "::".to_string(),
235 token::RArrow => "->".to_string(),
236 token::LArrow => "<-".to_string(),
237 token::FatArrow => "=>".to_string(),
238 token::OpenDelim(token::Paren) => "(".to_string(),
239 token::CloseDelim(token::Paren) => ")".to_string(),
240 token::OpenDelim(token::Bracket) => "[".to_string(),
241 token::CloseDelim(token::Bracket) => "]".to_string(),
242 token::OpenDelim(token::Brace) => "{".to_string(),
243 token::CloseDelim(token::Brace) => "}".to_string(),
244 token::Pound => "#".to_string(),
245 token::Dollar => "$".to_string(),
246 token::Question => "?".to_string(),
249 token::Literal(lit, suf) => {
250 let mut out = match lit {
251 token::Byte(b) => format!("b'{}'", b),
252 token::Char(c) => format!("'{}'", c),
253 token::Float(c) => c.to_string(),
254 token::Integer(c) => c.to_string(),
255 token::Str_(s) => format!("\"{}\"", s),
256 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
257 delim=repeat("#", n),
259 token::ByteStr(v) => format!("b\"{}\"", v),
260 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
261 delim=repeat("#", n),
265 if let Some(s) = suf {
266 out.push_str(&s.as_str())
272 /* Name components */
273 token::Ident(s, _) => s.to_string(),
274 token::Lifetime(s) => s.to_string(),
275 token::Underscore => "_".to_string(),
278 token::DocComment(s) => s.to_string(),
279 token::SubstNt(s, _) => format!("${}", s),
280 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
281 token::Eof => "<eof>".to_string(),
282 token::Whitespace => " ".to_string(),
283 token::Comment => "/* */".to_string(),
284 token::Shebang(s) => format!("/* shebang: {}*/", s),
286 token::SpecialVarNt(var) => format!("${}", var.as_str()),
288 token::Interpolated(ref nt) => match *nt {
289 token::NtExpr(ref e) => expr_to_string(&e),
290 token::NtMeta(ref e) => meta_item_to_string(&e),
291 token::NtTy(ref e) => ty_to_string(&e),
292 token::NtPath(ref e) => path_to_string(&e),
293 token::NtItem(ref e) => item_to_string(&e),
294 token::NtBlock(ref e) => block_to_string(&e),
295 token::NtStmt(ref e) => stmt_to_string(&e),
296 token::NtPat(ref e) => pat_to_string(&e),
297 token::NtIdent(ref e, _) => ident_to_string(e.node),
298 token::NtTT(ref e) => tt_to_string(&e),
299 token::NtArm(ref e) => arm_to_string(&e),
300 token::NtImplItem(ref e) => impl_item_to_string(&e),
301 token::NtTraitItem(ref e) => trait_item_to_string(&e),
302 token::NtGenerics(ref e) => generics_to_string(&e),
303 token::NtWhereClause(ref e) => where_clause_to_string(&e),
304 token::NtArg(ref e) => arg_to_string(&e),
309 pub fn ty_to_string(ty: &ast::Ty) -> String {
310 to_string(|s| s.print_type(ty))
313 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
314 to_string(|s| s.print_bounds("", bounds))
317 pub fn pat_to_string(pat: &ast::Pat) -> String {
318 to_string(|s| s.print_pat(pat))
321 pub fn arm_to_string(arm: &ast::Arm) -> String {
322 to_string(|s| s.print_arm(arm))
325 pub fn expr_to_string(e: &ast::Expr) -> String {
326 to_string(|s| s.print_expr(e))
329 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
330 to_string(|s| s.print_lifetime(e))
333 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
334 to_string(|s| s.print_tt(tt))
337 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
338 to_string(|s| s.print_tts(tts))
341 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
342 to_string(|s| s.print_stmt(stmt))
345 pub fn attr_to_string(attr: &ast::Attribute) -> String {
346 to_string(|s| s.print_attribute(attr))
349 pub fn item_to_string(i: &ast::Item) -> String {
350 to_string(|s| s.print_item(i))
353 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
354 to_string(|s| s.print_impl_item(i))
357 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
358 to_string(|s| s.print_trait_item(i))
361 pub fn generics_to_string(generics: &ast::Generics) -> String {
362 to_string(|s| s.print_generics(generics))
365 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
366 to_string(|s| s.print_where_clause(i))
369 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
370 to_string(|s| s.print_fn_block_args(p))
373 pub fn path_to_string(p: &ast::Path) -> String {
374 to_string(|s| s.print_path(p, false, 0))
377 pub fn ident_to_string(id: ast::Ident) -> String {
378 to_string(|s| s.print_ident(id))
381 pub fn fun_to_string(decl: &ast::FnDecl,
382 unsafety: ast::Unsafety,
383 constness: ast::Constness,
385 opt_explicit_self: Option<&ast::SelfKind>,
386 generics: &ast::Generics)
390 try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
391 generics, opt_explicit_self, ast::Visibility::Inherited));
392 try!(s.end()); // Close the head box
393 s.end() // Close the outer box
397 pub fn block_to_string(blk: &ast::Block) -> String {
399 // containing cbox, will be closed by print-block at }
400 try!(s.cbox(INDENT_UNIT));
401 // head-ibox, will be closed by print-block after {
407 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
408 to_string(|s| s.print_meta_item(mi))
411 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
412 to_string(|s| s.print_attribute(attr))
415 pub fn lit_to_string(l: &ast::Lit) -> String {
416 to_string(|s| s.print_literal(l))
419 pub fn explicit_self_to_string(explicit_self: &ast::SelfKind) -> String {
420 to_string(|s| s.print_explicit_self(explicit_self, ast::Mutability::Immutable).map(|_| {}))
423 pub fn variant_to_string(var: &ast::Variant) -> String {
424 to_string(|s| s.print_variant(var))
427 pub fn arg_to_string(arg: &ast::Arg) -> String {
428 to_string(|s| s.print_arg(arg, false))
431 pub fn mac_to_string(arg: &ast::Mac) -> String {
432 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
435 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
437 ast::Visibility::Public => format!("pub {}", s),
438 ast::Visibility::Inherited => s.to_string()
442 fn needs_parentheses(expr: &ast::Expr) -> bool {
444 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
445 ast::ExprKind::Closure(..) |
446 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
447 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
452 pub trait PrintState<'a> {
453 fn writer(&mut self) -> &mut pp::Printer<'a>;
454 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
455 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
456 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
457 fn literals(&self) -> &Option<Vec<comments::Literal>>;
459 fn word_space(&mut self, w: &str) -> io::Result<()> {
460 try!(word(self.writer(), w));
464 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
466 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
468 fn is_begin(&mut self) -> bool {
469 match self.writer().last_token() {
470 pp::Token::Begin(_) => true,
475 fn is_end(&mut self) -> bool {
476 match self.writer().last_token() {
477 pp::Token::End => true,
482 // is this the beginning of a line?
483 fn is_bol(&mut self) -> bool {
484 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
487 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
489 try!(hardbreak(self.writer()))
495 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
496 self.boxes().push(b);
497 pp::rbox(self.writer(), u, b)
500 fn ibox(&mut self, u: usize) -> io::Result<()> {
501 self.boxes().push(pp::Breaks::Inconsistent);
502 pp::ibox(self.writer(), u)
505 fn end(&mut self) -> io::Result<()> {
506 self.boxes().pop().unwrap();
507 pp::end(self.writer())
510 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
511 where F: FnMut(&mut Self, &T) -> io::Result<()>,
513 try!(self.rbox(0, b));
514 let mut first = true;
516 if first { first = false; } else { try!(self.word_space(",")); }
522 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
523 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
525 let mut result = None;
527 if let &Some(ref lits) = self.literals()
529 while cur_lit < lits.len() {
530 let ltrl = (*lits)[cur_lit].clone();
531 if ltrl.pos > pos { break; }
540 self.cur_cmnt_and_lit().cur_lit = cur_lit;
544 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
546 match self.next_comment() {
548 if (*cmnt).pos < pos {
549 try!(self.print_comment(cmnt));
550 self.cur_cmnt_and_lit().cur_cmnt += 1;
559 fn print_comment(&mut self,
560 cmnt: &comments::Comment) -> io::Result<()> {
563 assert_eq!(cmnt.lines.len(), 1);
564 try!(zerobreak(self.writer()));
565 try!(word(self.writer(), &cmnt.lines[0]));
566 zerobreak(self.writer())
568 comments::Isolated => {
569 try!(self.hardbreak_if_not_bol());
570 for line in &cmnt.lines {
571 // Don't print empty lines because they will end up as trailing
573 if !line.is_empty() {
574 try!(word(self.writer(), &line[..]));
576 try!(hardbreak(self.writer()));
580 comments::Trailing => {
581 try!(word(self.writer(), " "));
582 if cmnt.lines.len() == 1 {
583 try!(word(self.writer(), &cmnt.lines[0]));
584 hardbreak(self.writer())
587 for line in &cmnt.lines {
588 if !line.is_empty() {
589 try!(word(self.writer(), &line[..]));
591 try!(hardbreak(self.writer()));
596 comments::BlankLine => {
597 // We need to do at least one, possibly two hardbreaks.
598 let is_semi = match self.writer().last_token() {
599 pp::Token::String(s, _) => ";" == s,
602 if is_semi || self.is_begin() || self.is_end() {
603 try!(hardbreak(self.writer()));
605 hardbreak(self.writer())
610 fn next_comment(&mut self) -> Option<comments::Comment> {
611 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
612 match *self.comments() {
614 if cur_cmnt < cmnts.len() {
615 Some(cmnts[cur_cmnt].clone())
624 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
625 try!(self.maybe_print_comment(lit.span.lo));
626 match self.next_lit(lit.span.lo) {
628 return word(self.writer(), &(*ltrl).lit);
633 ast::LitKind::Str(ref st, style) => self.print_string(&st, style),
634 ast::LitKind::Byte(byte) => {
635 let mut res = String::from("b'");
636 res.extend(ascii::escape_default(byte).map(|c| c as char));
638 word(self.writer(), &res[..])
640 ast::LitKind::Char(ch) => {
641 let mut res = String::from("'");
642 res.extend(ch.escape_default());
644 word(self.writer(), &res[..])
646 ast::LitKind::Int(i, t) => {
648 ast::LitIntType::Signed(st) => {
650 &st.val_to_string(i as i64))
652 ast::LitIntType::Unsigned(ut) => {
653 word(self.writer(), &ut.val_to_string(i))
655 ast::LitIntType::Unsuffixed => {
656 word(self.writer(), &format!("{}", i))
660 ast::LitKind::Float(ref f, t) => {
667 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
668 ast::LitKind::Bool(val) => {
669 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
671 ast::LitKind::ByteStr(ref v) => {
672 let mut escaped: String = String::new();
673 for &ch in v.iter() {
674 escaped.extend(ascii::escape_default(ch)
675 .map(|c| c as char));
677 word(self.writer(), &format!("b\"{}\"", escaped))
682 fn print_string(&mut self, st: &str,
683 style: ast::StrStyle) -> io::Result<()> {
684 let st = match style {
685 ast::StrStyle::Cooked => {
686 (format!("\"{}\"", st.escape_default()))
688 ast::StrStyle::Raw(n) => {
689 (format!("r{delim}\"{string}\"{delim}",
690 delim=repeat("#", n),
694 word(self.writer(), &st[..])
697 fn print_inner_attributes(&mut self,
698 attrs: &[ast::Attribute]) -> io::Result<()> {
699 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
702 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
703 attrs: &[ast::Attribute])
705 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
708 fn print_outer_attributes(&mut self,
709 attrs: &[ast::Attribute]) -> io::Result<()> {
710 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
713 fn print_inner_attributes_inline(&mut self,
714 attrs: &[ast::Attribute]) -> io::Result<()> {
715 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
718 fn print_outer_attributes_inline(&mut self,
719 attrs: &[ast::Attribute]) -> io::Result<()> {
720 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
723 fn print_either_attributes(&mut self,
724 attrs: &[ast::Attribute],
725 kind: ast::AttrStyle,
727 trailing_hardbreak: bool) -> io::Result<()> {
730 if attr.node.style == kind {
731 try!(self.print_attribute_inline(attr, is_inline));
738 if count > 0 && trailing_hardbreak && !is_inline {
739 try!(self.hardbreak_if_not_bol());
744 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
745 self.print_attribute_inline(attr, false)
748 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
749 is_inline: bool) -> io::Result<()> {
751 try!(self.hardbreak_if_not_bol());
753 try!(self.maybe_print_comment(attr.span.lo));
754 if attr.node.is_sugared_doc {
755 word(self.writer(), &attr.value_str().unwrap())
757 match attr.node.style {
758 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
759 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
761 try!(self.print_meta_item(&attr.meta()));
762 word(self.writer(), "]")
766 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
767 try!(self.ibox(INDENT_UNIT));
769 ast::MetaItemKind::Word(ref name) => {
770 try!(word(self.writer(), &name));
772 ast::MetaItemKind::NameValue(ref name, ref value) => {
773 try!(self.word_space(&name[..]));
774 try!(self.word_space("="));
775 try!(self.print_literal(value));
777 ast::MetaItemKind::List(ref name, ref items) => {
778 try!(word(self.writer(), &name));
780 try!(self.commasep(Consistent,
782 |s, i| s.print_meta_item(&i)));
789 fn space_if_not_bol(&mut self) -> io::Result<()> {
790 if !self.is_bol() { try!(space(self.writer())); }
794 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
797 impl<'a> PrintState<'a> for State<'a> {
798 fn writer(&mut self) -> &mut pp::Printer<'a> {
802 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
806 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
810 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
811 &mut self.cur_cmnt_and_lit
814 fn literals(&self) -> &Option<Vec<comments::Literal>> {
820 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
821 self.boxes.push(pp::Breaks::Consistent);
822 pp::cbox(&mut self.s, u)
825 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
826 try!(word(&mut self.s, w));
830 pub fn head(&mut self, w: &str) -> io::Result<()> {
831 // outer-box is consistent
832 try!(self.cbox(INDENT_UNIT));
833 // head-box is inconsistent
834 try!(self.ibox(w.len() + 1));
835 // keyword that starts the head
837 try!(self.word_nbsp(w));
842 pub fn bopen(&mut self) -> io::Result<()> {
843 try!(word(&mut self.s, "{"));
844 self.end() // close the head-box
847 pub fn bclose_(&mut self, span: codemap::Span,
848 indented: usize) -> io::Result<()> {
849 self.bclose_maybe_open(span, indented, true)
851 pub fn bclose_maybe_open(&mut self, span: codemap::Span,
852 indented: usize, close_box: bool) -> io::Result<()> {
853 try!(self.maybe_print_comment(span.hi));
854 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
855 try!(word(&mut self.s, "}"));
857 try!(self.end()); // close the outer-box
861 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
862 self.bclose_(span, INDENT_UNIT)
865 pub fn in_cbox(&self) -> bool {
866 match self.boxes.last() {
867 Some(&last_box) => last_box == pp::Breaks::Consistent,
872 pub fn break_offset_if_not_bol(&mut self, n: usize,
873 off: isize) -> io::Result<()> {
875 break_offset(&mut self.s, n, off)
877 if off != 0 && self.s.last_token().is_hardbreak_tok() {
878 // We do something pretty sketchy here: tuck the nonzero
879 // offset-adjustment we were going to deposit along with the
880 // break into the previous hardbreak.
881 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
887 // Synthesizes a comment that was not textually present in the original source
889 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
890 try!(word(&mut self.s, "/*"));
891 try!(space(&mut self.s));
892 try!(word(&mut self.s, &text[..]));
893 try!(space(&mut self.s));
894 word(&mut self.s, "*/")
899 pub fn commasep_cmnt<T, F, G>(&mut self,
903 mut get_span: G) -> io::Result<()> where
904 F: FnMut(&mut State, &T) -> io::Result<()>,
905 G: FnMut(&T) -> codemap::Span,
907 try!(self.rbox(0, b));
908 let len = elts.len();
911 try!(self.maybe_print_comment(get_span(elt).hi));
915 try!(word(&mut self.s, ","));
916 try!(self.maybe_print_trailing_comment(get_span(elt),
917 Some(get_span(&elts[i]).hi)));
918 try!(self.space_if_not_bol());
924 pub fn commasep_exprs(&mut self, b: Breaks,
925 exprs: &[P<ast::Expr>]) -> io::Result<()> {
926 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
929 pub fn print_mod(&mut self, _mod: &ast::Mod,
930 attrs: &[ast::Attribute]) -> io::Result<()> {
931 try!(self.print_inner_attributes(attrs));
932 for item in &_mod.items {
933 try!(self.print_item(&item));
938 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
939 attrs: &[ast::Attribute]) -> io::Result<()> {
940 try!(self.print_inner_attributes(attrs));
941 for item in &nmod.items {
942 try!(self.print_foreign_item(item));
947 pub fn print_opt_lifetime(&mut self,
948 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
949 if let Some(l) = *lifetime {
950 try!(self.print_lifetime(&l));
956 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
957 try!(self.maybe_print_comment(ty.span.lo));
960 ast::TyKind::Vec(ref ty) => {
961 try!(word(&mut self.s, "["));
962 try!(self.print_type(&ty));
963 try!(word(&mut self.s, "]"));
965 ast::TyKind::Ptr(ref mt) => {
966 try!(word(&mut self.s, "*"));
968 ast::Mutability::Mutable => try!(self.word_nbsp("mut")),
969 ast::Mutability::Immutable => try!(self.word_nbsp("const")),
971 try!(self.print_type(&mt.ty));
973 ast::TyKind::Rptr(ref lifetime, ref mt) => {
974 try!(word(&mut self.s, "&"));
975 try!(self.print_opt_lifetime(lifetime));
976 try!(self.print_mt(mt));
978 ast::TyKind::Tup(ref elts) => {
980 try!(self.commasep(Inconsistent, &elts[..],
981 |s, ty| s.print_type(&ty)));
983 try!(word(&mut self.s, ","));
987 ast::TyKind::Paren(ref typ) => {
989 try!(self.print_type(&typ));
992 ast::TyKind::BareFn(ref f) => {
993 let generics = ast::Generics {
994 lifetimes: f.lifetimes.clone(),
995 ty_params: P::empty(),
996 where_clause: ast::WhereClause {
997 id: ast::DUMMY_NODE_ID,
998 predicates: Vec::new(),
1001 try!(self.print_ty_fn(f.abi,
1008 ast::TyKind::Path(None, ref path) => {
1009 try!(self.print_path(path, false, 0));
1011 ast::TyKind::Path(Some(ref qself), ref path) => {
1012 try!(self.print_qpath(path, qself, false))
1014 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1015 try!(self.print_type(&ty));
1016 try!(self.print_bounds("+", &bounds[..]));
1018 ast::TyKind::PolyTraitRef(ref bounds) => {
1019 try!(self.print_bounds("", &bounds[..]));
1021 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1022 try!(word(&mut self.s, "["));
1023 try!(self.print_type(&ty));
1024 try!(word(&mut self.s, "; "));
1025 try!(self.print_expr(&v));
1026 try!(word(&mut self.s, "]"));
1028 ast::TyKind::Typeof(ref e) => {
1029 try!(word(&mut self.s, "typeof("));
1030 try!(self.print_expr(&e));
1031 try!(word(&mut self.s, ")"));
1033 ast::TyKind::Infer => {
1034 try!(word(&mut self.s, "_"));
1036 ast::TyKind::Mac(ref m) => {
1037 try!(self.print_mac(m, token::Paren));
1043 pub fn print_foreign_item(&mut self,
1044 item: &ast::ForeignItem) -> io::Result<()> {
1045 try!(self.hardbreak_if_not_bol());
1046 try!(self.maybe_print_comment(item.span.lo));
1047 try!(self.print_outer_attributes(&item.attrs));
1049 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1050 try!(self.head(""));
1051 try!(self.print_fn(decl, ast::Unsafety::Normal,
1052 ast::Constness::NotConst,
1053 Abi::Rust, Some(item.ident),
1054 generics, None, item.vis));
1055 try!(self.end()); // end head-ibox
1056 try!(word(&mut self.s, ";"));
1057 self.end() // end the outer fn box
1059 ast::ForeignItemKind::Static(ref t, m) => {
1060 try!(self.head(&visibility_qualified(item.vis,
1063 try!(self.word_space("mut"));
1065 try!(self.print_ident(item.ident));
1066 try!(self.word_space(":"));
1067 try!(self.print_type(&t));
1068 try!(word(&mut self.s, ";"));
1069 try!(self.end()); // end the head-ibox
1070 self.end() // end the outer cbox
1075 fn print_associated_const(&mut self,
1078 default: Option<&ast::Expr>,
1079 vis: ast::Visibility)
1082 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1083 try!(self.word_space("const"));
1084 try!(self.print_ident(ident));
1085 try!(self.word_space(":"));
1086 try!(self.print_type(ty));
1087 if let Some(expr) = default {
1088 try!(space(&mut self.s));
1089 try!(self.word_space("="));
1090 try!(self.print_expr(expr));
1092 word(&mut self.s, ";")
1095 fn print_associated_type(&mut self,
1097 bounds: Option<&ast::TyParamBounds>,
1098 ty: Option<&ast::Ty>)
1100 try!(self.word_space("type"));
1101 try!(self.print_ident(ident));
1102 if let Some(bounds) = bounds {
1103 try!(self.print_bounds(":", bounds));
1105 if let Some(ty) = ty {
1106 try!(space(&mut self.s));
1107 try!(self.word_space("="));
1108 try!(self.print_type(ty));
1110 word(&mut self.s, ";")
1113 /// Pretty-print an item
1114 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1115 try!(self.hardbreak_if_not_bol());
1116 try!(self.maybe_print_comment(item.span.lo));
1117 try!(self.print_outer_attributes(&item.attrs));
1118 try!(self.ann.pre(self, NodeItem(item)));
1120 ast::ItemKind::ExternCrate(ref optional_path) => {
1121 try!(self.head(&visibility_qualified(item.vis,
1123 if let Some(p) = *optional_path {
1124 let val = p.as_str();
1125 if val.contains("-") {
1126 try!(self.print_string(&val, ast::StrStyle::Cooked));
1128 try!(self.print_name(p));
1130 try!(space(&mut self.s));
1131 try!(word(&mut self.s, "as"));
1132 try!(space(&mut self.s));
1134 try!(self.print_ident(item.ident));
1135 try!(word(&mut self.s, ";"));
1136 try!(self.end()); // end inner head-block
1137 try!(self.end()); // end outer head-block
1139 ast::ItemKind::Use(ref vp) => {
1140 try!(self.head(&visibility_qualified(item.vis,
1142 try!(self.print_view_path(&vp));
1143 try!(word(&mut self.s, ";"));
1144 try!(self.end()); // end inner head-block
1145 try!(self.end()); // end outer head-block
1147 ast::ItemKind::Static(ref ty, m, ref expr) => {
1148 try!(self.head(&visibility_qualified(item.vis,
1150 if m == ast::Mutability::Mutable {
1151 try!(self.word_space("mut"));
1153 try!(self.print_ident(item.ident));
1154 try!(self.word_space(":"));
1155 try!(self.print_type(&ty));
1156 try!(space(&mut self.s));
1157 try!(self.end()); // end the head-ibox
1159 try!(self.word_space("="));
1160 try!(self.print_expr(&expr));
1161 try!(word(&mut self.s, ";"));
1162 try!(self.end()); // end the outer cbox
1164 ast::ItemKind::Const(ref ty, ref expr) => {
1165 try!(self.head(&visibility_qualified(item.vis,
1167 try!(self.print_ident(item.ident));
1168 try!(self.word_space(":"));
1169 try!(self.print_type(&ty));
1170 try!(space(&mut self.s));
1171 try!(self.end()); // end the head-ibox
1173 try!(self.word_space("="));
1174 try!(self.print_expr(&expr));
1175 try!(word(&mut self.s, ";"));
1176 try!(self.end()); // end the outer cbox
1178 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1179 try!(self.head(""));
1190 try!(word(&mut self.s, " "));
1191 try!(self.print_block_with_attrs(&body, &item.attrs));
1193 ast::ItemKind::Mod(ref _mod) => {
1194 try!(self.head(&visibility_qualified(item.vis,
1196 try!(self.print_ident(item.ident));
1199 try!(self.print_mod(_mod, &item.attrs));
1200 try!(self.bclose(item.span));
1202 ast::ItemKind::ForeignMod(ref nmod) => {
1203 try!(self.head("extern"));
1204 try!(self.word_nbsp(&nmod.abi.to_string()));
1206 try!(self.print_foreign_mod(nmod, &item.attrs));
1207 try!(self.bclose(item.span));
1209 ast::ItemKind::Ty(ref ty, ref params) => {
1210 try!(self.ibox(INDENT_UNIT));
1212 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
1213 try!(self.print_ident(item.ident));
1214 try!(self.print_generics(params));
1215 try!(self.end()); // end the inner ibox
1217 try!(self.print_where_clause(¶ms.where_clause));
1218 try!(space(&mut self.s));
1219 try!(self.word_space("="));
1220 try!(self.print_type(&ty));
1221 try!(word(&mut self.s, ";"));
1222 try!(self.end()); // end the outer ibox
1224 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1225 try!(self.print_enum_def(
1233 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1234 try!(self.head(&visibility_qualified(item.vis,"struct")));
1235 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1238 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1239 try!(self.head(""));
1240 try!(self.print_visibility(item.vis));
1241 try!(self.print_unsafety(unsafety));
1242 try!(self.word_nbsp("impl"));
1243 try!(self.print_trait_ref(trait_ref));
1244 try!(space(&mut self.s));
1245 try!(self.word_space("for"));
1246 try!(self.word_space(".."));
1248 try!(self.bclose(item.span));
1250 ast::ItemKind::Impl(unsafety,
1255 ref impl_items) => {
1256 try!(self.head(""));
1257 try!(self.print_visibility(item.vis));
1258 try!(self.print_unsafety(unsafety));
1259 try!(self.word_nbsp("impl"));
1261 if generics.is_parameterized() {
1262 try!(self.print_generics(generics));
1263 try!(space(&mut self.s));
1267 ast::ImplPolarity::Negative => {
1268 try!(word(&mut self.s, "!"));
1275 try!(self.print_trait_ref(t));
1276 try!(space(&mut self.s));
1277 try!(self.word_space("for"));
1282 try!(self.print_type(&ty));
1283 try!(self.print_where_clause(&generics.where_clause));
1285 try!(space(&mut self.s));
1287 try!(self.print_inner_attributes(&item.attrs));
1288 for impl_item in impl_items {
1289 try!(self.print_impl_item(impl_item));
1291 try!(self.bclose(item.span));
1293 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1294 try!(self.head(""));
1295 try!(self.print_visibility(item.vis));
1296 try!(self.print_unsafety(unsafety));
1297 try!(self.word_nbsp("trait"));
1298 try!(self.print_ident(item.ident));
1299 try!(self.print_generics(generics));
1300 let mut real_bounds = Vec::with_capacity(bounds.len());
1301 for b in bounds.iter() {
1302 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1303 try!(space(&mut self.s));
1304 try!(self.word_space("for ?"));
1305 try!(self.print_trait_ref(&ptr.trait_ref));
1307 real_bounds.push(b.clone());
1310 try!(self.print_bounds(":", &real_bounds[..]));
1311 try!(self.print_where_clause(&generics.where_clause));
1312 try!(word(&mut self.s, " "));
1314 for trait_item in trait_items {
1315 try!(self.print_trait_item(trait_item));
1317 try!(self.bclose(item.span));
1319 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1320 try!(self.print_visibility(item.vis));
1321 try!(self.print_path(&node.path, false, 0));
1322 try!(word(&mut self.s, "! "));
1323 try!(self.print_ident(item.ident));
1324 try!(self.cbox(INDENT_UNIT));
1326 try!(self.print_tts(&node.tts[..]));
1327 try!(self.pclose());
1328 try!(word(&mut self.s, ";"));
1332 self.ann.post(self, NodeItem(item))
1335 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1336 self.print_path(&t.path, false, 0)
1339 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1340 if !lifetimes.is_empty() {
1341 try!(word(&mut self.s, "for<"));
1342 let mut comma = false;
1343 for lifetime_def in lifetimes {
1345 try!(self.word_space(","))
1347 try!(self.print_lifetime_def(lifetime_def));
1350 try!(word(&mut self.s, ">"));
1355 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1356 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1357 self.print_trait_ref(&t.trait_ref)
1360 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1361 generics: &ast::Generics, ident: ast::Ident,
1362 span: codemap::Span,
1363 visibility: ast::Visibility) -> io::Result<()> {
1364 try!(self.head(&visibility_qualified(visibility, "enum")));
1365 try!(self.print_ident(ident));
1366 try!(self.print_generics(generics));
1367 try!(self.print_where_clause(&generics.where_clause));
1368 try!(space(&mut self.s));
1369 self.print_variants(&enum_definition.variants, span)
1372 pub fn print_variants(&mut self,
1373 variants: &[ast::Variant],
1374 span: codemap::Span) -> io::Result<()> {
1377 try!(self.space_if_not_bol());
1378 try!(self.maybe_print_comment(v.span.lo));
1379 try!(self.print_outer_attributes(&v.node.attrs));
1380 try!(self.ibox(INDENT_UNIT));
1381 try!(self.print_variant(v));
1382 try!(word(&mut self.s, ","));
1384 try!(self.maybe_print_trailing_comment(v.span, None));
1389 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1391 ast::Visibility::Public => self.word_nbsp("pub"),
1392 ast::Visibility::Inherited => Ok(())
1396 pub fn print_struct(&mut self,
1397 struct_def: &ast::VariantData,
1398 generics: &ast::Generics,
1400 span: codemap::Span,
1401 print_finalizer: bool) -> io::Result<()> {
1402 try!(self.print_ident(ident));
1403 try!(self.print_generics(generics));
1404 if !struct_def.is_struct() {
1405 if struct_def.is_tuple() {
1408 Inconsistent, struct_def.fields(),
1410 match field.node.kind {
1411 ast::NamedField(..) => panic!("unexpected named field"),
1412 ast::UnnamedField(vis) => {
1413 try!(s.print_visibility(vis));
1414 try!(s.maybe_print_comment(field.span.lo));
1415 s.print_type(&field.node.ty)
1420 try!(self.pclose());
1422 try!(self.print_where_clause(&generics.where_clause));
1423 if print_finalizer {
1424 try!(word(&mut self.s, ";"));
1427 self.end() // close the outer-box
1429 try!(self.print_where_clause(&generics.where_clause));
1432 try!(self.hardbreak_if_not_bol());
1434 for field in struct_def.fields() {
1435 match field.node.kind {
1436 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1437 ast::NamedField(ident, visibility) => {
1438 try!(self.hardbreak_if_not_bol());
1439 try!(self.maybe_print_comment(field.span.lo));
1440 try!(self.print_outer_attributes(&field.node.attrs));
1441 try!(self.print_visibility(visibility));
1442 try!(self.print_ident(ident));
1443 try!(self.word_nbsp(":"));
1444 try!(self.print_type(&field.node.ty));
1445 try!(word(&mut self.s, ","));
1454 /// This doesn't deserve to be called "pretty" printing, but it should be
1455 /// meaning-preserving. A quick hack that might help would be to look at the
1456 /// spans embedded in the TTs to decide where to put spaces and newlines.
1457 /// But it'd be better to parse these according to the grammar of the
1458 /// appropriate macro, transcribe back into the grammar we just parsed from,
1459 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1460 /// expression arguments as expressions). It can be done! I think.
1461 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1463 TokenTree::Token(_, ref tk) => {
1464 try!(word(&mut self.s, &token_to_string(tk)));
1466 parse::token::DocComment(..) => {
1467 hardbreak(&mut self.s)
1472 TokenTree::Delimited(_, ref delimed) => {
1473 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1474 try!(space(&mut self.s));
1475 try!(self.print_tts(&delimed.tts));
1476 try!(space(&mut self.s));
1477 word(&mut self.s, &token_to_string(&delimed.close_token()))
1479 TokenTree::Sequence(_, ref seq) => {
1480 try!(word(&mut self.s, "$("));
1481 for tt_elt in &seq.tts {
1482 try!(self.print_tt(tt_elt));
1484 try!(word(&mut self.s, ")"));
1485 match seq.separator {
1487 try!(word(&mut self.s, &token_to_string(tk)));
1492 ast::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1493 ast::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1499 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1501 let mut suppress_space = false;
1502 for (i, tt) in tts.iter().enumerate() {
1503 if i != 0 && !suppress_space {
1504 try!(space(&mut self.s));
1506 try!(self.print_tt(tt));
1507 // There should be no space between the module name and the following `::` in paths,
1508 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1509 suppress_space = match *tt {
1510 TokenTree::Token(_, token::Ident(_, token::ModName)) |
1511 TokenTree::Token(_, token::MatchNt(_, _, _, token::ModName)) |
1512 TokenTree::Token(_, token::SubstNt(_, token::ModName)) => true,
1519 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1520 try!(self.head(""));
1521 let generics = ast::Generics::default();
1522 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1523 match v.node.disr_expr {
1525 try!(space(&mut self.s));
1526 try!(self.word_space("="));
1533 pub fn print_method_sig(&mut self,
1536 vis: ast::Visibility)
1538 self.print_fn(&m.decl,
1544 Some(&m.explicit_self.node),
1548 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1550 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1551 try!(self.hardbreak_if_not_bol());
1552 try!(self.maybe_print_comment(ti.span.lo));
1553 try!(self.print_outer_attributes(&ti.attrs));
1555 ast::TraitItemKind::Const(ref ty, ref default) => {
1556 try!(self.print_associated_const(ti.ident, &ty,
1557 default.as_ref().map(|expr| &**expr),
1558 ast::Visibility::Inherited));
1560 ast::TraitItemKind::Method(ref sig, ref body) => {
1562 try!(self.head(""));
1564 try!(self.print_method_sig(ti.ident, sig, ast::Visibility::Inherited));
1565 if let Some(ref body) = *body {
1567 try!(self.print_block_with_attrs(body, &ti.attrs));
1569 try!(word(&mut self.s, ";"));
1572 ast::TraitItemKind::Type(ref bounds, ref default) => {
1573 try!(self.print_associated_type(ti.ident, Some(bounds),
1574 default.as_ref().map(|ty| &**ty)));
1577 self.ann.post(self, NodeSubItem(ti.id))
1580 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1581 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1582 try!(self.hardbreak_if_not_bol());
1583 try!(self.maybe_print_comment(ii.span.lo));
1584 try!(self.print_outer_attributes(&ii.attrs));
1586 ast::ImplItemKind::Const(ref ty, ref expr) => {
1587 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1589 ast::ImplItemKind::Method(ref sig, ref body) => {
1590 try!(self.head(""));
1591 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1593 try!(self.print_block_with_attrs(body, &ii.attrs));
1595 ast::ImplItemKind::Type(ref ty) => {
1596 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1598 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1599 // code copied from ItemKind::Mac:
1600 try!(self.print_path(&node.path, false, 0));
1601 try!(word(&mut self.s, "! "));
1602 try!(self.cbox(INDENT_UNIT));
1604 try!(self.print_tts(&node.tts[..]));
1605 try!(self.pclose());
1606 try!(word(&mut self.s, ";"));
1610 self.ann.post(self, NodeSubItem(ii.id))
1613 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1614 try!(self.maybe_print_comment(st.span.lo));
1616 ast::StmtKind::Decl(ref decl, _) => {
1617 try!(self.print_decl(&decl));
1619 ast::StmtKind::Expr(ref expr, _) => {
1620 try!(self.space_if_not_bol());
1621 try!(self.print_expr_outer_attr_style(&expr, false));
1623 ast::StmtKind::Semi(ref expr, _) => {
1624 try!(self.space_if_not_bol());
1625 try!(self.print_expr_outer_attr_style(&expr, false));
1626 try!(word(&mut self.s, ";"));
1628 ast::StmtKind::Mac(ref mac, style, ref attrs) => {
1629 try!(self.space_if_not_bol());
1630 try!(self.print_outer_attributes(attrs.as_attr_slice()));
1631 let delim = match style {
1632 ast::MacStmtStyle::Braces => token::Brace,
1635 try!(self.print_mac(&mac, delim));
1637 ast::MacStmtStyle::Braces => {}
1638 _ => try!(word(&mut self.s, ";")),
1642 if parse::classify::stmt_ends_with_semi(&st.node) {
1643 try!(word(&mut self.s, ";"));
1645 self.maybe_print_trailing_comment(st.span, None)
1648 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1649 self.print_block_with_attrs(blk, &[])
1652 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1653 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1656 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1657 attrs: &[ast::Attribute])
1659 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1662 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1663 indented: usize) -> io::Result<()> {
1664 self.print_block_maybe_unclosed(blk, indented, &[], false)
1667 pub fn print_block_with_attrs(&mut self,
1669 attrs: &[ast::Attribute]) -> io::Result<()> {
1670 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1673 pub fn print_block_maybe_unclosed(&mut self,
1676 attrs: &[ast::Attribute],
1677 close_box: bool) -> io::Result<()> {
1679 BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")),
1680 BlockCheckMode::Default => ()
1682 try!(self.maybe_print_comment(blk.span.lo));
1683 try!(self.ann.pre(self, NodeBlock(blk)));
1686 try!(self.print_inner_attributes(attrs));
1688 for st in &blk.stmts {
1689 try!(self.print_stmt(st));
1693 try!(self.space_if_not_bol());
1694 try!(self.print_expr_outer_attr_style(&expr, false));
1695 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1699 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1700 self.ann.post(self, NodeBlock(blk))
1703 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1707 // "another else-if"
1708 ast::ExprKind::If(ref i, ref then, ref e) => {
1709 try!(self.cbox(INDENT_UNIT - 1));
1711 try!(word(&mut self.s, " else if "));
1712 try!(self.print_expr(&i));
1713 try!(space(&mut self.s));
1714 try!(self.print_block(&then));
1715 self.print_else(e.as_ref().map(|e| &**e))
1717 // "another else-if-let"
1718 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1719 try!(self.cbox(INDENT_UNIT - 1));
1721 try!(word(&mut self.s, " else if let "));
1722 try!(self.print_pat(&pat));
1723 try!(space(&mut self.s));
1724 try!(self.word_space("="));
1725 try!(self.print_expr(&expr));
1726 try!(space(&mut self.s));
1727 try!(self.print_block(&then));
1728 self.print_else(e.as_ref().map(|e| &**e))
1731 ast::ExprKind::Block(ref b) => {
1732 try!(self.cbox(INDENT_UNIT - 1));
1734 try!(word(&mut self.s, " else "));
1735 self.print_block(&b)
1737 // BLEAH, constraints would be great here
1739 panic!("print_if saw if with weird alternative");
1747 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1748 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1749 try!(self.head("if"));
1750 try!(self.print_expr(test));
1751 try!(space(&mut self.s));
1752 try!(self.print_block(blk));
1753 self.print_else(elseopt)
1756 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1757 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1758 try!(self.head("if let"));
1759 try!(self.print_pat(pat));
1760 try!(space(&mut self.s));
1761 try!(self.word_space("="));
1762 try!(self.print_expr(expr));
1763 try!(space(&mut self.s));
1764 try!(self.print_block(blk));
1765 self.print_else(elseopt)
1768 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1770 try!(self.print_path(&m.node.path, false, 0));
1771 try!(word(&mut self.s, "!"));
1773 token::Paren => try!(self.popen()),
1774 token::Bracket => try!(word(&mut self.s, "[")),
1776 try!(self.head(""));
1780 try!(self.print_tts(&m.node.tts));
1782 token::Paren => self.pclose(),
1783 token::Bracket => word(&mut self.s, "]"),
1784 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::ExprKind::Binary(ref sub_op, _, _) => {
1799 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1800 AssocOp::from_ast_binop(binop.node).precedence() {
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_in_place(&mut self,
1824 expr: &ast::Expr) -> io::Result<()> {
1825 try!(self.print_expr_maybe_paren(place));
1826 try!(space(&mut self.s));
1827 try!(self.word_space("<-"));
1828 self.print_expr_maybe_paren(expr)
1831 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1832 attrs: &[Attribute]) -> io::Result<()> {
1833 try!(self.ibox(INDENT_UNIT));
1834 try!(word(&mut self.s, "["));
1835 try!(self.print_inner_attributes_inline(attrs));
1836 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1837 try!(word(&mut self.s, "]"));
1841 fn print_expr_repeat(&mut self,
1842 element: &ast::Expr,
1844 attrs: &[Attribute]) -> io::Result<()> {
1845 try!(self.ibox(INDENT_UNIT));
1846 try!(word(&mut self.s, "["));
1847 try!(self.print_inner_attributes_inline(attrs));
1848 try!(self.print_expr(element));
1849 try!(self.word_space(";"));
1850 try!(self.print_expr(count));
1851 try!(word(&mut self.s, "]"));
1855 fn print_expr_struct(&mut self,
1857 fields: &[ast::Field],
1858 wth: &Option<P<ast::Expr>>,
1859 attrs: &[Attribute]) -> io::Result<()> {
1860 try!(self.print_path(path, true, 0));
1861 try!(word(&mut self.s, "{"));
1862 try!(self.print_inner_attributes_inline(attrs));
1863 try!(self.commasep_cmnt(
1867 try!(s.ibox(INDENT_UNIT));
1868 try!(s.print_ident(field.ident.node));
1869 try!(s.word_space(":"));
1870 try!(s.print_expr(&field.expr));
1876 try!(self.ibox(INDENT_UNIT));
1877 if !fields.is_empty() {
1878 try!(word(&mut self.s, ","));
1879 try!(space(&mut self.s));
1881 try!(word(&mut self.s, ".."));
1882 try!(self.print_expr(&expr));
1885 _ => if !fields.is_empty() {
1886 try!(word(&mut self.s, ","))
1889 try!(word(&mut self.s, "}"));
1893 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1894 attrs: &[Attribute]) -> io::Result<()> {
1896 try!(self.print_inner_attributes_inline(attrs));
1897 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1898 if exprs.len() == 1 {
1899 try!(word(&mut self.s, ","));
1904 fn print_expr_call(&mut self,
1906 args: &[P<ast::Expr>]) -> io::Result<()> {
1907 try!(self.print_expr_maybe_paren(func));
1908 self.print_call_post(args)
1911 fn print_expr_method_call(&mut self,
1912 ident: ast::SpannedIdent,
1914 args: &[P<ast::Expr>]) -> io::Result<()> {
1915 let base_args = &args[1..];
1916 try!(self.print_expr(&args[0]));
1917 try!(word(&mut self.s, "."));
1918 try!(self.print_ident(ident.node));
1919 if !tys.is_empty() {
1920 try!(word(&mut self.s, "::<"));
1921 try!(self.commasep(Inconsistent, tys,
1922 |s, ty| s.print_type(&ty)));
1923 try!(word(&mut self.s, ">"));
1925 self.print_call_post(base_args)
1928 fn print_expr_binary(&mut self,
1931 rhs: &ast::Expr) -> io::Result<()> {
1932 if self.check_expr_bin_needs_paren(lhs, op) {
1933 try!(self.print_expr_maybe_paren(lhs));
1935 try!(self.print_expr(lhs));
1937 try!(space(&mut self.s));
1938 try!(self.word_space(op.node.to_string()));
1939 if self.check_expr_bin_needs_paren(rhs, op) {
1940 self.print_expr_maybe_paren(rhs)
1942 self.print_expr(rhs)
1946 fn print_expr_unary(&mut self,
1948 expr: &ast::Expr) -> io::Result<()> {
1949 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1950 self.print_expr_maybe_paren(expr)
1953 fn print_expr_addr_of(&mut self,
1954 mutability: ast::Mutability,
1955 expr: &ast::Expr) -> io::Result<()> {
1956 try!(word(&mut self.s, "&"));
1957 try!(self.print_mutability(mutability));
1958 self.print_expr_maybe_paren(expr)
1961 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1962 self.print_expr_outer_attr_style(expr, true)
1965 fn print_expr_outer_attr_style(&mut self,
1967 is_inline: bool) -> io::Result<()> {
1968 try!(self.maybe_print_comment(expr.span.lo));
1970 let attrs = expr.attrs.as_attr_slice();
1972 try!(self.print_outer_attributes_inline(attrs));
1974 try!(self.print_outer_attributes(attrs));
1977 try!(self.ibox(INDENT_UNIT));
1978 try!(self.ann.pre(self, NodeExpr(expr)));
1980 ast::ExprKind::Box(ref expr) => {
1981 try!(self.word_space("box"));
1982 try!(self.print_expr(expr));
1984 ast::ExprKind::InPlace(ref place, ref expr) => {
1985 try!(self.print_expr_in_place(place, expr));
1987 ast::ExprKind::Vec(ref exprs) => {
1988 try!(self.print_expr_vec(&exprs[..], attrs));
1990 ast::ExprKind::Repeat(ref element, ref count) => {
1991 try!(self.print_expr_repeat(&element, &count, attrs));
1993 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1994 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
1996 ast::ExprKind::Tup(ref exprs) => {
1997 try!(self.print_expr_tup(&exprs[..], attrs));
1999 ast::ExprKind::Call(ref func, ref args) => {
2000 try!(self.print_expr_call(&func, &args[..]));
2002 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2003 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
2005 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2006 try!(self.print_expr_binary(op, &lhs, &rhs));
2008 ast::ExprKind::Unary(op, ref expr) => {
2009 try!(self.print_expr_unary(op, &expr));
2011 ast::ExprKind::AddrOf(m, ref expr) => {
2012 try!(self.print_expr_addr_of(m, &expr));
2014 ast::ExprKind::Lit(ref lit) => {
2015 try!(self.print_literal(&lit));
2017 ast::ExprKind::Cast(ref expr, ref ty) => {
2018 if let ast::ExprKind::Cast(..) = expr.node {
2019 try!(self.print_expr(&expr));
2021 try!(self.print_expr_maybe_paren(&expr));
2023 try!(space(&mut self.s));
2024 try!(self.word_space("as"));
2025 try!(self.print_type(&ty));
2027 ast::ExprKind::Type(ref expr, ref ty) => {
2028 try!(self.print_expr(&expr));
2029 try!(self.word_space(":"));
2030 try!(self.print_type(&ty));
2032 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2033 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
2035 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2036 try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e)));
2038 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2039 if let Some(ident) = opt_ident {
2040 try!(self.print_ident(ident));
2041 try!(self.word_space(":"));
2043 try!(self.head("while"));
2044 try!(self.print_expr(&test));
2045 try!(space(&mut self.s));
2046 try!(self.print_block_with_attrs(&blk, attrs));
2048 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2049 if let Some(ident) = opt_ident {
2050 try!(self.print_ident(ident));
2051 try!(self.word_space(":"));
2053 try!(self.head("while let"));
2054 try!(self.print_pat(&pat));
2055 try!(space(&mut self.s));
2056 try!(self.word_space("="));
2057 try!(self.print_expr(&expr));
2058 try!(space(&mut self.s));
2059 try!(self.print_block_with_attrs(&blk, attrs));
2061 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2062 if let Some(ident) = opt_ident {
2063 try!(self.print_ident(ident));
2064 try!(self.word_space(":"));
2066 try!(self.head("for"));
2067 try!(self.print_pat(&pat));
2068 try!(space(&mut self.s));
2069 try!(self.word_space("in"));
2070 try!(self.print_expr(&iter));
2071 try!(space(&mut self.s));
2072 try!(self.print_block_with_attrs(&blk, attrs));
2074 ast::ExprKind::Loop(ref blk, opt_ident) => {
2075 if let Some(ident) = opt_ident {
2076 try!(self.print_ident(ident));
2077 try!(self.word_space(":"));
2079 try!(self.head("loop"));
2080 try!(space(&mut self.s));
2081 try!(self.print_block_with_attrs(&blk, attrs));
2083 ast::ExprKind::Match(ref expr, ref arms) => {
2084 try!(self.cbox(INDENT_UNIT));
2086 try!(self.word_nbsp("match"));
2087 try!(self.print_expr(&expr));
2088 try!(space(&mut self.s));
2090 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2092 try!(self.print_arm(arm));
2094 try!(self.bclose_(expr.span, INDENT_UNIT));
2096 ast::ExprKind::Closure(capture_clause, ref decl, ref body) => {
2097 try!(self.print_capture_clause(capture_clause));
2099 try!(self.print_fn_block_args(&decl));
2100 try!(space(&mut self.s));
2102 let default_return = match decl.output {
2103 ast::FunctionRetTy::Default(..) => true,
2107 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2108 try!(self.print_block_unclosed(&body));
2110 // we extract the block, so as not to create another set of boxes
2111 let i_expr = body.expr.as_ref().unwrap();
2113 ast::ExprKind::Block(ref blk) => {
2114 try!(self.print_block_unclosed_with_attrs(
2116 i_expr.attrs.as_attr_slice()));
2119 // this is a bare expression
2120 try!(self.print_expr(&i_expr));
2121 try!(self.end()); // need to close a box
2125 // a box will be closed by print_expr, but we didn't want an overall
2126 // wrapper so we closed the corresponding opening. so create an
2127 // empty box to satisfy the close.
2130 ast::ExprKind::Block(ref blk) => {
2131 // containing cbox, will be closed by print-block at }
2132 try!(self.cbox(INDENT_UNIT));
2133 // head-box, will be closed by print-block after {
2135 try!(self.print_block_with_attrs(&blk, attrs));
2137 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2138 try!(self.print_expr(&lhs));
2139 try!(space(&mut self.s));
2140 try!(self.word_space("="));
2141 try!(self.print_expr(&rhs));
2143 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2144 try!(self.print_expr(&lhs));
2145 try!(space(&mut self.s));
2146 try!(word(&mut self.s, op.node.to_string()));
2147 try!(self.word_space("="));
2148 try!(self.print_expr(&rhs));
2150 ast::ExprKind::Field(ref expr, id) => {
2151 try!(self.print_expr(&expr));
2152 try!(word(&mut self.s, "."));
2153 try!(self.print_ident(id.node));
2155 ast::ExprKind::TupField(ref expr, id) => {
2156 try!(self.print_expr(&expr));
2157 try!(word(&mut self.s, "."));
2158 try!(self.print_usize(id.node));
2160 ast::ExprKind::Index(ref expr, ref index) => {
2161 try!(self.print_expr(&expr));
2162 try!(word(&mut self.s, "["));
2163 try!(self.print_expr(&index));
2164 try!(word(&mut self.s, "]"));
2166 ast::ExprKind::Range(ref start, ref end) => {
2167 if let &Some(ref e) = start {
2168 try!(self.print_expr(&e));
2170 try!(word(&mut self.s, ".."));
2171 if let &Some(ref e) = end {
2172 try!(self.print_expr(&e));
2175 ast::ExprKind::Path(None, ref path) => {
2176 try!(self.print_path(path, true, 0))
2178 ast::ExprKind::Path(Some(ref qself), ref path) => {
2179 try!(self.print_qpath(path, qself, true))
2181 ast::ExprKind::Break(opt_ident) => {
2182 try!(word(&mut self.s, "break"));
2183 try!(space(&mut self.s));
2184 if let Some(ident) = opt_ident {
2185 try!(self.print_ident(ident.node));
2186 try!(space(&mut self.s));
2189 ast::ExprKind::Again(opt_ident) => {
2190 try!(word(&mut self.s, "continue"));
2191 try!(space(&mut self.s));
2192 if let Some(ident) = opt_ident {
2193 try!(self.print_ident(ident.node));
2194 try!(space(&mut self.s))
2197 ast::ExprKind::Ret(ref result) => {
2198 try!(word(&mut self.s, "return"));
2201 try!(word(&mut self.s, " "));
2202 try!(self.print_expr(&expr));
2207 ast::ExprKind::InlineAsm(ref a) => {
2208 try!(word(&mut self.s, "asm!"));
2210 try!(self.print_string(&a.asm, a.asm_str_style));
2211 try!(self.word_space(":"));
2213 try!(self.commasep(Inconsistent, &a.outputs,
2215 match out.constraint.slice_shift_char() {
2216 Some(('=', operand)) if out.is_rw => {
2217 try!(s.print_string(&format!("+{}", operand),
2218 ast::StrStyle::Cooked))
2220 _ => try!(s.print_string(&out.constraint, ast::StrStyle::Cooked))
2223 try!(s.print_expr(&out.expr));
2227 try!(space(&mut self.s));
2228 try!(self.word_space(":"));
2230 try!(self.commasep(Inconsistent, &a.inputs,
2231 |s, &(ref co, ref o)| {
2232 try!(s.print_string(&co, ast::StrStyle::Cooked));
2234 try!(s.print_expr(&o));
2238 try!(space(&mut self.s));
2239 try!(self.word_space(":"));
2241 try!(self.commasep(Inconsistent, &a.clobbers,
2243 try!(s.print_string(&co, ast::StrStyle::Cooked));
2247 let mut options = vec!();
2249 options.push("volatile");
2252 options.push("alignstack");
2254 if a.dialect == ast::AsmDialect::Intel {
2255 options.push("intel");
2258 if !options.is_empty() {
2259 try!(space(&mut self.s));
2260 try!(self.word_space(":"));
2261 try!(self.commasep(Inconsistent, &options,
2263 try!(s.print_string(co, ast::StrStyle::Cooked));
2268 try!(self.pclose());
2270 ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2271 ast::ExprKind::Paren(ref e) => {
2273 try!(self.print_inner_attributes_inline(attrs));
2274 try!(self.print_expr(&e));
2275 try!(self.pclose());
2278 try!(self.ann.post(self, NodeExpr(expr)));
2282 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2283 try!(self.print_pat(&loc.pat));
2284 if let Some(ref ty) = loc.ty {
2285 try!(self.word_space(":"));
2286 try!(self.print_type(&ty));
2291 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2292 try!(self.maybe_print_comment(decl.span.lo));
2294 ast::DeclKind::Local(ref loc) => {
2295 try!(self.print_outer_attributes(loc.attrs.as_attr_slice()));
2296 try!(self.space_if_not_bol());
2297 try!(self.ibox(INDENT_UNIT));
2298 try!(self.word_nbsp("let"));
2300 try!(self.ibox(INDENT_UNIT));
2301 try!(self.print_local_decl(&loc));
2303 if let Some(ref init) = loc.init {
2305 try!(self.word_space("="));
2306 try!(self.print_expr(&init));
2310 ast::DeclKind::Item(ref item) => self.print_item(&item)
2314 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2315 try!(word(&mut self.s, &ident.name.as_str()));
2316 self.ann.post(self, NodeIdent(&ident))
2319 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2320 word(&mut self.s, &i.to_string())
2323 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2324 try!(word(&mut self.s, &name.as_str()));
2325 self.ann.post(self, NodeName(&name))
2328 pub fn print_for_decl(&mut self, loc: &ast::Local,
2329 coll: &ast::Expr) -> io::Result<()> {
2330 try!(self.print_local_decl(loc));
2331 try!(space(&mut self.s));
2332 try!(self.word_space("in"));
2333 self.print_expr(coll)
2336 fn print_path(&mut self,
2338 colons_before_params: bool,
2342 try!(self.maybe_print_comment(path.span.lo));
2344 let mut first = !path.global;
2345 for segment in &path.segments[..path.segments.len()-depth] {
2349 try!(word(&mut self.s, "::"))
2352 try!(self.print_ident(segment.identifier));
2354 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2360 fn print_qpath(&mut self,
2363 colons_before_params: bool)
2366 try!(word(&mut self.s, "<"));
2367 try!(self.print_type(&qself.ty));
2368 if qself.position > 0 {
2369 try!(space(&mut self.s));
2370 try!(self.word_space("as"));
2371 let depth = path.segments.len() - qself.position;
2372 try!(self.print_path(&path, false, depth));
2374 try!(word(&mut self.s, ">"));
2375 try!(word(&mut self.s, "::"));
2376 let item_segment = path.segments.last().unwrap();
2377 try!(self.print_ident(item_segment.identifier));
2378 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2381 fn print_path_parameters(&mut self,
2382 parameters: &ast::PathParameters,
2383 colons_before_params: bool)
2386 if parameters.is_empty() {
2390 if colons_before_params {
2391 try!(word(&mut self.s, "::"))
2395 ast::PathParameters::AngleBracketed(ref data) => {
2396 try!(word(&mut self.s, "<"));
2398 let mut comma = false;
2399 for lifetime in &data.lifetimes {
2401 try!(self.word_space(","))
2403 try!(self.print_lifetime(lifetime));
2407 if !data.types.is_empty() {
2409 try!(self.word_space(","))
2414 |s, ty| s.print_type(&ty)));
2418 for binding in data.bindings.iter() {
2420 try!(self.word_space(","))
2422 try!(self.print_ident(binding.ident));
2423 try!(space(&mut self.s));
2424 try!(self.word_space("="));
2425 try!(self.print_type(&binding.ty));
2429 try!(word(&mut self.s, ">"))
2432 ast::PathParameters::Parenthesized(ref data) => {
2433 try!(word(&mut self.s, "("));
2437 |s, ty| s.print_type(&ty)));
2438 try!(word(&mut self.s, ")"));
2443 try!(self.space_if_not_bol());
2444 try!(self.word_space("->"));
2445 try!(self.print_type(&ty));
2454 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2455 try!(self.maybe_print_comment(pat.span.lo));
2456 try!(self.ann.pre(self, NodePat(pat)));
2457 /* Pat isn't normalized, but the beauty of it
2458 is that it doesn't matter */
2460 ast::PatWild => try!(word(&mut self.s, "_")),
2461 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2462 match binding_mode {
2463 ast::BindingMode::ByRef(mutbl) => {
2464 try!(self.word_nbsp("ref"));
2465 try!(self.print_mutability(mutbl));
2467 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2468 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2469 try!(self.word_nbsp("mut"));
2472 try!(self.print_ident(path1.node));
2475 try!(word(&mut self.s, "@"));
2476 try!(self.print_pat(&p));
2481 ast::PatEnum(ref path, ref args_) => {
2482 try!(self.print_path(path, true, 0));
2484 None => try!(word(&mut self.s, "(..)")),
2486 if !args.is_empty() {
2488 try!(self.commasep(Inconsistent, &args[..],
2489 |s, p| s.print_pat(&p)));
2490 try!(self.pclose());
2495 ast::PatQPath(ref qself, ref path) => {
2496 try!(self.print_qpath(path, qself, false));
2498 ast::PatStruct(ref path, ref fields, etc) => {
2499 try!(self.print_path(path, true, 0));
2501 try!(self.word_space("{"));
2502 try!(self.commasep_cmnt(
2503 Consistent, &fields[..],
2505 try!(s.cbox(INDENT_UNIT));
2506 if !f.node.is_shorthand {
2507 try!(s.print_ident(f.node.ident));
2508 try!(s.word_nbsp(":"));
2510 try!(s.print_pat(&f.node.pat));
2513 |f| f.node.pat.span));
2515 if !fields.is_empty() { try!(self.word_space(",")); }
2516 try!(word(&mut self.s, ".."));
2518 try!(space(&mut self.s));
2519 try!(word(&mut self.s, "}"));
2521 ast::PatTup(ref elts) => {
2523 try!(self.commasep(Inconsistent,
2525 |s, p| s.print_pat(&p)));
2526 if elts.len() == 1 {
2527 try!(word(&mut self.s, ","));
2529 try!(self.pclose());
2531 ast::PatBox(ref inner) => {
2532 try!(word(&mut self.s, "box "));
2533 try!(self.print_pat(&inner));
2535 ast::PatRegion(ref inner, mutbl) => {
2536 try!(word(&mut self.s, "&"));
2537 if mutbl == ast::Mutability::Mutable {
2538 try!(word(&mut self.s, "mut "));
2540 try!(self.print_pat(&inner));
2542 ast::PatLit(ref e) => try!(self.print_expr(&e)),
2543 ast::PatRange(ref begin, ref end) => {
2544 try!(self.print_expr(&begin));
2545 try!(space(&mut self.s));
2546 try!(word(&mut self.s, "..."));
2547 try!(self.print_expr(&end));
2549 ast::PatVec(ref before, ref slice, ref after) => {
2550 try!(word(&mut self.s, "["));
2551 try!(self.commasep(Inconsistent,
2553 |s, p| s.print_pat(&p)));
2554 if let Some(ref p) = *slice {
2555 if !before.is_empty() { try!(self.word_space(",")); }
2556 if p.node != ast::PatWild {
2557 try!(self.print_pat(&p));
2559 try!(word(&mut self.s, ".."));
2560 if !after.is_empty() { try!(self.word_space(",")); }
2562 try!(self.commasep(Inconsistent,
2564 |s, p| s.print_pat(&p)));
2565 try!(word(&mut self.s, "]"));
2567 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2569 self.ann.post(self, NodePat(pat))
2572 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2573 // I have no idea why this check is necessary, but here it
2575 if arm.attrs.is_empty() {
2576 try!(space(&mut self.s));
2578 try!(self.cbox(INDENT_UNIT));
2580 try!(self.print_outer_attributes(&arm.attrs));
2581 let mut first = true;
2582 for p in &arm.pats {
2586 try!(space(&mut self.s));
2587 try!(self.word_space("|"));
2589 try!(self.print_pat(&p));
2591 try!(space(&mut self.s));
2592 if let Some(ref e) = arm.guard {
2593 try!(self.word_space("if"));
2594 try!(self.print_expr(&e));
2595 try!(space(&mut self.s));
2597 try!(self.word_space("=>"));
2599 match arm.body.node {
2600 ast::ExprKind::Block(ref blk) => {
2601 // the block will close the pattern's ibox
2602 try!(self.print_block_unclosed_indent(&blk, INDENT_UNIT));
2604 // If it is a user-provided unsafe block, print a comma after it
2605 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2606 try!(word(&mut self.s, ","));
2610 try!(self.end()); // close the ibox for the pattern
2611 try!(self.print_expr(&arm.body));
2612 try!(word(&mut self.s, ","));
2615 self.end() // close enclosing cbox
2618 // Returns whether it printed anything
2619 fn print_explicit_self(&mut self,
2620 explicit_self: &ast::SelfKind,
2621 mutbl: ast::Mutability) -> io::Result<bool> {
2622 try!(self.print_mutability(mutbl));
2623 match *explicit_self {
2624 ast::SelfKind::Static => { return Ok(false); }
2625 ast::SelfKind::Value(_) => {
2626 try!(word(&mut self.s, "self"));
2628 ast::SelfKind::Region(ref lt, m, _) => {
2629 try!(word(&mut self.s, "&"));
2630 try!(self.print_opt_lifetime(lt));
2631 try!(self.print_mutability(m));
2632 try!(word(&mut self.s, "self"));
2634 ast::SelfKind::Explicit(ref typ, _) => {
2635 try!(word(&mut self.s, "self"));
2636 try!(self.word_space(":"));
2637 try!(self.print_type(&typ));
2643 pub fn print_fn(&mut self,
2645 unsafety: ast::Unsafety,
2646 constness: ast::Constness,
2648 name: Option<ast::Ident>,
2649 generics: &ast::Generics,
2650 opt_explicit_self: Option<&ast::SelfKind>,
2651 vis: ast::Visibility) -> io::Result<()> {
2652 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2654 if let Some(name) = name {
2656 try!(self.print_ident(name));
2658 try!(self.print_generics(generics));
2659 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2660 self.print_where_clause(&generics.where_clause)
2663 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2664 opt_explicit_self: Option<&ast::SelfKind>,
2665 is_closure: bool) -> io::Result<()> {
2666 // It is unfortunate to duplicate the commasep logic, but we want the
2667 // self type and the args all in the same box.
2668 try!(self.rbox(0, Inconsistent));
2669 let mut first = true;
2670 if let Some(explicit_self) = opt_explicit_self {
2671 let m = match *explicit_self {
2672 ast::SelfKind::Static => ast::Mutability::Immutable,
2673 _ => match decl.inputs[0].pat.node {
2674 ast::PatIdent(ast::BindingMode::ByValue(m), _, _) => m,
2675 _ => ast::Mutability::Immutable
2678 first = !try!(self.print_explicit_self(explicit_self, m));
2681 // HACK(eddyb) ignore the separately printed self argument.
2682 let args = if first {
2689 if first { first = false; } else { try!(self.word_space(",")); }
2690 try!(self.print_arg(arg, is_closure));
2696 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2697 opt_explicit_self: Option<&ast::SelfKind>)
2700 try!(self.print_fn_args(decl, opt_explicit_self, false));
2702 try!(word(&mut self.s, ", ..."));
2704 try!(self.pclose());
2706 self.print_fn_output(decl)
2709 pub fn print_fn_block_args(
2713 try!(word(&mut self.s, "|"));
2714 try!(self.print_fn_args(decl, None, true));
2715 try!(word(&mut self.s, "|"));
2717 if let ast::FunctionRetTy::Default(..) = decl.output {
2721 try!(self.space_if_not_bol());
2722 try!(self.word_space("->"));
2724 ast::FunctionRetTy::Ty(ref ty) => {
2725 try!(self.print_type(&ty));
2726 self.maybe_print_comment(ty.span.lo)
2728 ast::FunctionRetTy::Default(..) => unreachable!(),
2729 ast::FunctionRetTy::None(span) => {
2730 try!(self.word_nbsp("!"));
2731 self.maybe_print_comment(span.lo)
2736 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2738 match capture_clause {
2739 ast::CaptureBy::Value => self.word_space("move"),
2740 ast::CaptureBy::Ref => Ok(()),
2744 pub fn print_bounds(&mut self,
2746 bounds: &[ast::TyParamBound])
2748 if !bounds.is_empty() {
2749 try!(word(&mut self.s, prefix));
2750 let mut first = true;
2751 for bound in bounds {
2756 try!(self.word_space("+"));
2760 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2761 self.print_poly_trait_ref(tref)
2763 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2764 try!(word(&mut self.s, "?"));
2765 self.print_poly_trait_ref(tref)
2767 RegionTyParamBound(ref lt) => {
2768 self.print_lifetime(lt)
2778 pub fn print_lifetime(&mut self,
2779 lifetime: &ast::Lifetime)
2782 self.print_name(lifetime.name)
2785 pub fn print_lifetime_def(&mut self,
2786 lifetime: &ast::LifetimeDef)
2789 try!(self.print_lifetime(&lifetime.lifetime));
2791 for v in &lifetime.bounds {
2792 try!(word(&mut self.s, sep));
2793 try!(self.print_lifetime(v));
2799 pub fn print_generics(&mut self,
2800 generics: &ast::Generics)
2803 let total = generics.lifetimes.len() + generics.ty_params.len();
2808 try!(word(&mut self.s, "<"));
2810 let mut ints = Vec::new();
2815 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2816 if idx < generics.lifetimes.len() {
2817 let lifetime = &generics.lifetimes[idx];
2818 s.print_lifetime_def(lifetime)
2820 let idx = idx - generics.lifetimes.len();
2821 let param = &generics.ty_params[idx];
2822 s.print_ty_param(param)
2826 try!(word(&mut self.s, ">"));
2830 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2831 try!(self.print_ident(param.ident));
2832 try!(self.print_bounds(":", ¶m.bounds));
2833 match param.default {
2834 Some(ref default) => {
2835 try!(space(&mut self.s));
2836 try!(self.word_space("="));
2837 self.print_type(&default)
2843 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2845 if where_clause.predicates.is_empty() {
2849 try!(space(&mut self.s));
2850 try!(self.word_space("where"));
2852 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2854 try!(self.word_space(","));
2858 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2862 try!(self.print_formal_lifetime_list(bound_lifetimes));
2863 try!(self.print_type(&bounded_ty));
2864 try!(self.print_bounds(":", bounds));
2866 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2869 try!(self.print_lifetime(lifetime));
2870 try!(word(&mut self.s, ":"));
2872 for (i, bound) in bounds.iter().enumerate() {
2873 try!(self.print_lifetime(bound));
2876 try!(word(&mut self.s, ":"));
2880 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2881 try!(self.print_path(path, false, 0));
2882 try!(space(&mut self.s));
2883 try!(self.word_space("="));
2884 try!(self.print_type(&ty));
2892 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2894 ast::ViewPathSimple(ident, ref path) => {
2895 try!(self.print_path(path, false, 0));
2897 if path.segments.last().unwrap().identifier.name !=
2899 try!(space(&mut self.s));
2900 try!(self.word_space("as"));
2901 try!(self.print_ident(ident));
2907 ast::ViewPathGlob(ref path) => {
2908 try!(self.print_path(path, false, 0));
2909 word(&mut self.s, "::*")
2912 ast::ViewPathList(ref path, ref idents) => {
2913 if path.segments.is_empty() {
2914 try!(word(&mut self.s, "{"));
2916 try!(self.print_path(path, false, 0));
2917 try!(word(&mut self.s, "::{"));
2919 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2921 ast::PathListItemKind::Ident { name, rename, .. } => {
2922 try!(s.print_ident(name));
2923 if let Some(ident) = rename {
2924 try!(space(&mut s.s));
2925 try!(s.word_space("as"));
2926 try!(s.print_ident(ident));
2930 ast::PathListItemKind::Mod { rename, .. } => {
2931 try!(word(&mut s.s, "self"));
2932 if let Some(ident) = rename {
2933 try!(space(&mut s.s));
2934 try!(s.word_space("as"));
2935 try!(s.print_ident(ident));
2941 word(&mut self.s, "}")
2946 pub fn print_mutability(&mut self,
2947 mutbl: ast::Mutability) -> io::Result<()> {
2949 ast::Mutability::Mutable => self.word_nbsp("mut"),
2950 ast::Mutability::Immutable => Ok(()),
2954 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2955 try!(self.print_mutability(mt.mutbl));
2956 self.print_type(&mt.ty)
2959 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2960 try!(self.ibox(INDENT_UNIT));
2961 match input.ty.node {
2962 ast::TyKind::Infer if is_closure => try!(self.print_pat(&input.pat)),
2964 match input.pat.node {
2965 ast::PatIdent(_, ref path1, _) if
2967 parse::token::special_idents::invalid.name => {
2971 try!(self.print_pat(&input.pat));
2972 try!(word(&mut self.s, ":"));
2973 try!(space(&mut self.s));
2976 try!(self.print_type(&input.ty));
2982 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2983 if let ast::FunctionRetTy::Default(..) = decl.output {
2987 try!(self.space_if_not_bol());
2988 try!(self.ibox(INDENT_UNIT));
2989 try!(self.word_space("->"));
2991 ast::FunctionRetTy::None(_) =>
2992 try!(self.word_nbsp("!")),
2993 ast::FunctionRetTy::Default(..) => unreachable!(),
2994 ast::FunctionRetTy::Ty(ref ty) =>
2995 try!(self.print_type(&ty))
3000 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
3005 pub fn print_ty_fn(&mut self,
3007 unsafety: ast::Unsafety,
3009 name: Option<ast::Ident>,
3010 generics: &ast::Generics,
3011 opt_explicit_self: Option<&ast::SelfKind>)
3013 try!(self.ibox(INDENT_UNIT));
3014 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
3015 try!(word(&mut self.s, "for"));
3016 try!(self.print_generics(generics));
3018 let generics = ast::Generics {
3019 lifetimes: Vec::new(),
3020 ty_params: P::empty(),
3021 where_clause: ast::WhereClause {
3022 id: ast::DUMMY_NODE_ID,
3023 predicates: Vec::new(),
3026 try!(self.print_fn(decl,
3028 ast::Constness::NotConst,
3033 ast::Visibility::Inherited));
3037 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
3038 next_pos: Option<BytePos>)
3040 let cm = match self.cm {
3044 match self.next_comment() {
3046 if (*cmnt).style != comments::Trailing { return Ok(()) }
3047 let span_line = cm.lookup_char_pos(span.hi);
3048 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3049 let mut next = (*cmnt).pos + BytePos(1);
3050 match next_pos { None => (), Some(p) => next = p }
3051 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3052 span_line.line == comment_line.line {
3053 try!(self.print_comment(cmnt));
3054 self.cur_cmnt_and_lit.cur_cmnt += 1;
3062 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3063 // If there aren't any remaining comments, then we need to manually
3064 // make sure there is a line break at the end.
3065 if self.next_comment().is_none() {
3066 try!(hardbreak(&mut self.s));
3069 match self.next_comment() {
3071 try!(self.print_comment(cmnt));
3072 self.cur_cmnt_and_lit.cur_cmnt += 1;
3080 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3081 opt_abi: Option<Abi>)
3084 Some(Abi::Rust) => Ok(()),
3086 try!(self.word_nbsp("extern"));
3087 self.word_nbsp(&abi.to_string())
3093 pub fn print_extern_opt_abi(&mut self,
3094 opt_abi: Option<Abi>) -> io::Result<()> {
3097 try!(self.word_nbsp("extern"));
3098 self.word_nbsp(&abi.to_string())
3104 pub fn print_fn_header_info(&mut self,
3105 unsafety: ast::Unsafety,
3106 constness: ast::Constness,
3108 vis: ast::Visibility) -> io::Result<()> {
3109 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3112 ast::Constness::NotConst => {}
3113 ast::Constness::Const => try!(self.word_nbsp("const"))
3116 try!(self.print_unsafety(unsafety));
3118 if abi != Abi::Rust {
3119 try!(self.word_nbsp("extern"));
3120 try!(self.word_nbsp(&abi.to_string()));
3123 word(&mut self.s, "fn")
3126 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3128 ast::Unsafety::Normal => Ok(()),
3129 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3134 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3145 fn test_fun_to_string() {
3146 let abba_ident = token::str_to_ident("abba");
3148 let decl = ast::FnDecl {
3150 output: ast::FunctionRetTy::Default(codemap::DUMMY_SP),
3153 let generics = ast::Generics::default();
3154 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3155 ast::Constness::NotConst,
3162 fn test_variant_to_string() {
3163 let ident = token::str_to_ident("principal_skinner");
3165 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3168 // making this up as I go.... ?
3169 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3173 let varstr = variant_to_string(&var);
3174 assert_eq!(varstr, "principal_skinner");