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, PatKind};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{self, CodeMap, BytePos};
22 use parse::token::{self, keywords, 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 pub const INDENT_UNIT: usize = 4;
94 pub const DEFAULT_COLUMNS: usize = 78;
96 /// Requires you to pass an input filename and reader so that
97 /// it can scan the input text for comments and literals to
99 pub fn print_crate<'a>(cm: &'a CodeMap,
100 span_diagnostic: &errors::Handler,
106 is_expanded: bool) -> io::Result<()> {
107 let mut s = State::new_from_input(cm,
114 if is_expanded && !std_inject::no_std(krate) {
115 // We need to print `#![no_std]` (and its feature gate) so that
116 // compiling pretty-printed source won't inject libstd again.
117 // However we don't want these attributes in the AST because
118 // of the feature gate, so we fake them up here.
120 // #![feature(prelude_import)]
121 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
122 let list = attr::mk_list_item(InternedString::new("feature"),
123 vec![prelude_import_meta]);
124 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
125 try!(s.print_attribute(&fake_attr));
128 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
129 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
130 try!(s.print_attribute(&fake_attr));
133 try!(s.print_mod(&krate.module, &krate.attrs));
134 try!(s.print_remaining_comments());
139 pub fn new_from_input(cm: &'a CodeMap,
140 span_diagnostic: &errors::Handler,
145 is_expanded: bool) -> State<'a> {
146 let (cmnts, lits) = comments::gather_comments_and_literals(
156 // If the code is post expansion, don't use the table of
157 // literals, since it doesn't correspond with the literals
158 // in the AST anymore.
159 if is_expanded { None } else { Some(lits) })
162 pub fn new(cm: &'a CodeMap,
165 comments: Option<Vec<comments::Comment>>,
166 literals: Option<Vec<comments::Literal>>) -> State<'a> {
168 s: pp::mk_printer(out, DEFAULT_COLUMNS),
172 cur_cmnt_and_lit: CurrentCommentAndLiteral {
182 pub fn to_string<F>(f: F) -> String where
183 F: FnOnce(&mut State) -> io::Result<()>,
185 let mut wr = Vec::new();
187 let mut printer = rust_printer(Box::new(&mut wr));
188 f(&mut printer).unwrap();
189 eof(&mut printer.s).unwrap();
191 String::from_utf8(wr).unwrap()
194 pub fn binop_to_string(op: BinOpToken) -> &'static str {
200 token::Percent => "%",
209 pub fn token_to_string(tok: &Token) -> String {
211 token::Eq => "=".to_string(),
212 token::Lt => "<".to_string(),
213 token::Le => "<=".to_string(),
214 token::EqEq => "==".to_string(),
215 token::Ne => "!=".to_string(),
216 token::Ge => ">=".to_string(),
217 token::Gt => ">".to_string(),
218 token::Not => "!".to_string(),
219 token::Tilde => "~".to_string(),
220 token::OrOr => "||".to_string(),
221 token::AndAnd => "&&".to_string(),
222 token::BinOp(op) => binop_to_string(op).to_string(),
223 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
225 /* Structural symbols */
226 token::At => "@".to_string(),
227 token::Dot => ".".to_string(),
228 token::DotDot => "..".to_string(),
229 token::DotDotDot => "...".to_string(),
230 token::Comma => ",".to_string(),
231 token::Semi => ";".to_string(),
232 token::Colon => ":".to_string(),
233 token::ModSep => "::".to_string(),
234 token::RArrow => "->".to_string(),
235 token::LArrow => "<-".to_string(),
236 token::FatArrow => "=>".to_string(),
237 token::OpenDelim(token::Paren) => "(".to_string(),
238 token::CloseDelim(token::Paren) => ")".to_string(),
239 token::OpenDelim(token::Bracket) => "[".to_string(),
240 token::CloseDelim(token::Bracket) => "]".to_string(),
241 token::OpenDelim(token::Brace) => "{".to_string(),
242 token::CloseDelim(token::Brace) => "}".to_string(),
243 token::Pound => "#".to_string(),
244 token::Dollar => "$".to_string(),
245 token::Question => "?".to_string(),
248 token::Literal(lit, suf) => {
249 let mut out = match lit {
250 token::Byte(b) => format!("b'{}'", b),
251 token::Char(c) => format!("'{}'", c),
252 token::Float(c) => c.to_string(),
253 token::Integer(c) => c.to_string(),
254 token::Str_(s) => format!("\"{}\"", s),
255 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
256 delim=repeat("#", n),
258 token::ByteStr(v) => format!("b\"{}\"", v),
259 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
260 delim=repeat("#", n),
264 if let Some(s) = suf {
265 out.push_str(&s.as_str())
271 /* Name components */
272 token::Ident(s) => s.to_string(),
273 token::Lifetime(s) => s.to_string(),
274 token::Underscore => "_".to_string(),
277 token::DocComment(s) => s.to_string(),
278 token::SubstNt(s) => format!("${}", s),
279 token::MatchNt(s, t) => format!("${}:{}", s, t),
280 token::Eof => "<eof>".to_string(),
281 token::Whitespace => " ".to_string(),
282 token::Comment => "/* */".to_string(),
283 token::Shebang(s) => format!("/* shebang: {}*/", s),
285 token::SpecialVarNt(var) => format!("${}", var.as_str()),
287 token::Interpolated(ref nt) => match *nt {
288 token::NtExpr(ref e) => expr_to_string(&e),
289 token::NtMeta(ref e) => meta_item_to_string(&e),
290 token::NtTy(ref e) => ty_to_string(&e),
291 token::NtPath(ref e) => path_to_string(&e),
292 token::NtItem(ref e) => item_to_string(&e),
293 token::NtBlock(ref e) => block_to_string(&e),
294 token::NtStmt(ref e) => stmt_to_string(&e),
295 token::NtPat(ref e) => pat_to_string(&e),
296 token::NtIdent(ref e) => ident_to_string(e.node),
297 token::NtTT(ref e) => tt_to_string(&e),
298 token::NtArm(ref e) => arm_to_string(&e),
299 token::NtImplItem(ref e) => impl_item_to_string(&e),
300 token::NtTraitItem(ref e) => trait_item_to_string(&e),
301 token::NtGenerics(ref e) => generics_to_string(&e),
302 token::NtWhereClause(ref e) => where_clause_to_string(&e),
303 token::NtArg(ref e) => arg_to_string(&e),
308 pub fn ty_to_string(ty: &ast::Ty) -> String {
309 to_string(|s| s.print_type(ty))
312 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
313 to_string(|s| s.print_bounds("", bounds))
316 pub fn pat_to_string(pat: &ast::Pat) -> String {
317 to_string(|s| s.print_pat(pat))
320 pub fn arm_to_string(arm: &ast::Arm) -> String {
321 to_string(|s| s.print_arm(arm))
324 pub fn expr_to_string(e: &ast::Expr) -> String {
325 to_string(|s| s.print_expr(e))
328 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
329 to_string(|s| s.print_lifetime(e))
332 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
333 to_string(|s| s.print_tt(tt))
336 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
337 to_string(|s| s.print_tts(tts))
340 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
341 to_string(|s| s.print_stmt(stmt))
344 pub fn attr_to_string(attr: &ast::Attribute) -> String {
345 to_string(|s| s.print_attribute(attr))
348 pub fn item_to_string(i: &ast::Item) -> String {
349 to_string(|s| s.print_item(i))
352 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
353 to_string(|s| s.print_impl_item(i))
356 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
357 to_string(|s| s.print_trait_item(i))
360 pub fn generics_to_string(generics: &ast::Generics) -> String {
361 to_string(|s| s.print_generics(generics))
364 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
365 to_string(|s| s.print_where_clause(i))
368 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
369 to_string(|s| s.print_fn_block_args(p))
372 pub fn path_to_string(p: &ast::Path) -> String {
373 to_string(|s| s.print_path(p, false, 0))
376 pub fn ident_to_string(id: ast::Ident) -> String {
377 to_string(|s| s.print_ident(id))
380 pub fn fun_to_string(decl: &ast::FnDecl,
381 unsafety: ast::Unsafety,
382 constness: ast::Constness,
384 generics: &ast::Generics)
388 try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
389 generics, &ast::Visibility::Inherited));
390 try!(s.end()); // Close the head box
391 s.end() // Close the outer box
395 pub fn block_to_string(blk: &ast::Block) -> String {
397 // containing cbox, will be closed by print-block at }
398 try!(s.cbox(INDENT_UNIT));
399 // head-ibox, will be closed by print-block after {
405 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
406 to_string(|s| s.print_meta_item(mi))
409 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
410 to_string(|s| s.print_attribute(attr))
413 pub fn lit_to_string(l: &ast::Lit) -> String {
414 to_string(|s| s.print_literal(l))
417 pub fn variant_to_string(var: &ast::Variant) -> String {
418 to_string(|s| s.print_variant(var))
421 pub fn arg_to_string(arg: &ast::Arg) -> String {
422 to_string(|s| s.print_arg(arg, false))
425 pub fn mac_to_string(arg: &ast::Mac) -> String {
426 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
429 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 ast::Visibility::Public => format!("pub {}", s),
432 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
433 ast::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
434 ast::Visibility::Inherited => s.to_string()
438 fn needs_parentheses(expr: &ast::Expr) -> bool {
440 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
441 ast::ExprKind::Closure(..) |
442 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
443 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
448 pub trait PrintState<'a> {
449 fn writer(&mut self) -> &mut pp::Printer<'a>;
450 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
451 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
452 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
453 fn literals(&self) -> &Option<Vec<comments::Literal>>;
455 fn word_space(&mut self, w: &str) -> io::Result<()> {
456 try!(word(self.writer(), w));
460 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
462 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
464 fn is_begin(&mut self) -> bool {
465 match self.writer().last_token() {
466 pp::Token::Begin(_) => true,
471 fn is_end(&mut self) -> bool {
472 match self.writer().last_token() {
473 pp::Token::End => true,
478 // is this the beginning of a line?
479 fn is_bol(&mut self) -> bool {
480 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
483 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
485 try!(hardbreak(self.writer()))
491 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
492 self.boxes().push(b);
493 pp::rbox(self.writer(), u, b)
496 fn ibox(&mut self, u: usize) -> io::Result<()> {
497 self.boxes().push(pp::Breaks::Inconsistent);
498 pp::ibox(self.writer(), u)
501 fn end(&mut self) -> io::Result<()> {
502 self.boxes().pop().unwrap();
503 pp::end(self.writer())
506 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
507 where F: FnMut(&mut Self, &T) -> io::Result<()>,
509 try!(self.rbox(0, b));
510 let mut first = true;
512 if first { first = false; } else { try!(self.word_space(",")); }
518 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
519 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
521 let mut result = None;
523 if let &Some(ref lits) = self.literals()
525 while cur_lit < lits.len() {
526 let ltrl = (*lits)[cur_lit].clone();
527 if ltrl.pos > pos { break; }
536 self.cur_cmnt_and_lit().cur_lit = cur_lit;
540 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
542 match self.next_comment() {
544 if (*cmnt).pos < pos {
545 try!(self.print_comment(cmnt));
546 self.cur_cmnt_and_lit().cur_cmnt += 1;
555 fn print_comment(&mut self,
556 cmnt: &comments::Comment) -> io::Result<()> {
559 assert_eq!(cmnt.lines.len(), 1);
560 try!(zerobreak(self.writer()));
561 try!(word(self.writer(), &cmnt.lines[0]));
562 zerobreak(self.writer())
564 comments::Isolated => {
565 try!(self.hardbreak_if_not_bol());
566 for line in &cmnt.lines {
567 // Don't print empty lines because they will end up as trailing
569 if !line.is_empty() {
570 try!(word(self.writer(), &line[..]));
572 try!(hardbreak(self.writer()));
576 comments::Trailing => {
577 try!(word(self.writer(), " "));
578 if cmnt.lines.len() == 1 {
579 try!(word(self.writer(), &cmnt.lines[0]));
580 hardbreak(self.writer())
583 for line in &cmnt.lines {
584 if !line.is_empty() {
585 try!(word(self.writer(), &line[..]));
587 try!(hardbreak(self.writer()));
592 comments::BlankLine => {
593 // We need to do at least one, possibly two hardbreaks.
594 let is_semi = match self.writer().last_token() {
595 pp::Token::String(s, _) => ";" == s,
598 if is_semi || self.is_begin() || self.is_end() {
599 try!(hardbreak(self.writer()));
601 hardbreak(self.writer())
606 fn next_comment(&mut self) -> Option<comments::Comment> {
607 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
608 match *self.comments() {
610 if cur_cmnt < cmnts.len() {
611 Some(cmnts[cur_cmnt].clone())
620 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
621 try!(self.maybe_print_comment(lit.span.lo));
622 match self.next_lit(lit.span.lo) {
624 return word(self.writer(), &(*ltrl).lit);
629 ast::LitKind::Str(ref st, style) => self.print_string(&st, style),
630 ast::LitKind::Byte(byte) => {
631 let mut res = String::from("b'");
632 res.extend(ascii::escape_default(byte).map(|c| c as char));
634 word(self.writer(), &res[..])
636 ast::LitKind::Char(ch) => {
637 let mut res = String::from("'");
638 res.extend(ch.escape_default());
640 word(self.writer(), &res[..])
642 ast::LitKind::Int(i, t) => {
644 ast::LitIntType::Signed(st) => {
646 &st.val_to_string(i as i64))
648 ast::LitIntType::Unsigned(ut) => {
649 word(self.writer(), &ut.val_to_string(i))
651 ast::LitIntType::Unsuffixed => {
652 word(self.writer(), &format!("{}", i))
656 ast::LitKind::Float(ref f, t) => {
663 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
664 ast::LitKind::Bool(val) => {
665 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
667 ast::LitKind::ByteStr(ref v) => {
668 let mut escaped: String = String::new();
669 for &ch in v.iter() {
670 escaped.extend(ascii::escape_default(ch)
671 .map(|c| c as char));
673 word(self.writer(), &format!("b\"{}\"", escaped))
678 fn print_string(&mut self, st: &str,
679 style: ast::StrStyle) -> io::Result<()> {
680 let st = match style {
681 ast::StrStyle::Cooked => {
682 (format!("\"{}\"", st.escape_default()))
684 ast::StrStyle::Raw(n) => {
685 (format!("r{delim}\"{string}\"{delim}",
686 delim=repeat("#", n),
690 word(self.writer(), &st[..])
693 fn print_inner_attributes(&mut self,
694 attrs: &[ast::Attribute]) -> io::Result<()> {
695 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
698 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
699 attrs: &[ast::Attribute])
701 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
704 fn print_outer_attributes(&mut self,
705 attrs: &[ast::Attribute]) -> io::Result<()> {
706 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
709 fn print_inner_attributes_inline(&mut self,
710 attrs: &[ast::Attribute]) -> io::Result<()> {
711 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
714 fn print_outer_attributes_inline(&mut self,
715 attrs: &[ast::Attribute]) -> io::Result<()> {
716 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
719 fn print_either_attributes(&mut self,
720 attrs: &[ast::Attribute],
721 kind: ast::AttrStyle,
723 trailing_hardbreak: bool) -> io::Result<()> {
726 if attr.node.style == kind {
727 try!(self.print_attribute_inline(attr, is_inline));
734 if count > 0 && trailing_hardbreak && !is_inline {
735 try!(self.hardbreak_if_not_bol());
740 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
741 self.print_attribute_inline(attr, false)
744 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
745 is_inline: bool) -> io::Result<()> {
747 try!(self.hardbreak_if_not_bol());
749 try!(self.maybe_print_comment(attr.span.lo));
750 if attr.node.is_sugared_doc {
751 try!(word(self.writer(), &attr.value_str().unwrap()));
752 hardbreak(self.writer())
754 match attr.node.style {
755 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
756 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
758 try!(self.print_meta_item(&attr.meta()));
759 word(self.writer(), "]")
763 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
764 try!(self.ibox(INDENT_UNIT));
766 ast::MetaItemKind::Word(ref name) => {
767 try!(word(self.writer(), &name));
769 ast::MetaItemKind::NameValue(ref name, ref value) => {
770 try!(self.word_space(&name[..]));
771 try!(self.word_space("="));
772 try!(self.print_literal(value));
774 ast::MetaItemKind::List(ref name, ref items) => {
775 try!(word(self.writer(), &name));
777 try!(self.commasep(Consistent,
779 |s, i| s.print_meta_item(&i)));
786 fn space_if_not_bol(&mut self) -> io::Result<()> {
787 if !self.is_bol() { try!(space(self.writer())); }
791 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
794 impl<'a> PrintState<'a> for State<'a> {
795 fn writer(&mut self) -> &mut pp::Printer<'a> {
799 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
803 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
807 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
808 &mut self.cur_cmnt_and_lit
811 fn literals(&self) -> &Option<Vec<comments::Literal>> {
817 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
818 self.boxes.push(pp::Breaks::Consistent);
819 pp::cbox(&mut self.s, u)
822 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
823 try!(word(&mut self.s, w));
827 pub fn head(&mut self, w: &str) -> io::Result<()> {
828 // outer-box is consistent
829 try!(self.cbox(INDENT_UNIT));
830 // head-box is inconsistent
831 try!(self.ibox(w.len() + 1));
832 // keyword that starts the head
834 try!(self.word_nbsp(w));
839 pub fn bopen(&mut self) -> io::Result<()> {
840 try!(word(&mut self.s, "{"));
841 self.end() // close the head-box
844 pub fn bclose_(&mut self, span: codemap::Span,
845 indented: usize) -> io::Result<()> {
846 self.bclose_maybe_open(span, indented, true)
848 pub fn bclose_maybe_open(&mut self, span: codemap::Span,
849 indented: usize, close_box: bool) -> io::Result<()> {
850 try!(self.maybe_print_comment(span.hi));
851 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
852 try!(word(&mut self.s, "}"));
854 try!(self.end()); // close the outer-box
858 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
859 self.bclose_(span, INDENT_UNIT)
862 pub fn in_cbox(&self) -> bool {
863 match self.boxes.last() {
864 Some(&last_box) => last_box == pp::Breaks::Consistent,
869 pub fn break_offset_if_not_bol(&mut self, n: usize,
870 off: isize) -> io::Result<()> {
872 break_offset(&mut self.s, n, off)
874 if off != 0 && self.s.last_token().is_hardbreak_tok() {
875 // We do something pretty sketchy here: tuck the nonzero
876 // offset-adjustment we were going to deposit along with the
877 // break into the previous hardbreak.
878 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
884 // Synthesizes a comment that was not textually present in the original source
886 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
887 try!(word(&mut self.s, "/*"));
888 try!(space(&mut self.s));
889 try!(word(&mut self.s, &text[..]));
890 try!(space(&mut self.s));
891 word(&mut self.s, "*/")
896 pub fn commasep_cmnt<T, F, G>(&mut self,
900 mut get_span: G) -> io::Result<()> where
901 F: FnMut(&mut State, &T) -> io::Result<()>,
902 G: FnMut(&T) -> codemap::Span,
904 try!(self.rbox(0, b));
905 let len = elts.len();
908 try!(self.maybe_print_comment(get_span(elt).hi));
912 try!(word(&mut self.s, ","));
913 try!(self.maybe_print_trailing_comment(get_span(elt),
914 Some(get_span(&elts[i]).hi)));
915 try!(self.space_if_not_bol());
921 pub fn commasep_exprs(&mut self, b: Breaks,
922 exprs: &[P<ast::Expr>]) -> io::Result<()> {
923 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
926 pub fn print_mod(&mut self, _mod: &ast::Mod,
927 attrs: &[ast::Attribute]) -> io::Result<()> {
928 try!(self.print_inner_attributes(attrs));
929 for item in &_mod.items {
930 try!(self.print_item(&item));
935 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
936 attrs: &[ast::Attribute]) -> io::Result<()> {
937 try!(self.print_inner_attributes(attrs));
938 for item in &nmod.items {
939 try!(self.print_foreign_item(item));
944 pub fn print_opt_lifetime(&mut self,
945 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
946 if let Some(l) = *lifetime {
947 try!(self.print_lifetime(&l));
953 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
954 try!(self.maybe_print_comment(ty.span.lo));
957 ast::TyKind::Vec(ref ty) => {
958 try!(word(&mut self.s, "["));
959 try!(self.print_type(&ty));
960 try!(word(&mut self.s, "]"));
962 ast::TyKind::Ptr(ref mt) => {
963 try!(word(&mut self.s, "*"));
965 ast::Mutability::Mutable => try!(self.word_nbsp("mut")),
966 ast::Mutability::Immutable => try!(self.word_nbsp("const")),
968 try!(self.print_type(&mt.ty));
970 ast::TyKind::Rptr(ref lifetime, ref mt) => {
971 try!(word(&mut self.s, "&"));
972 try!(self.print_opt_lifetime(lifetime));
973 try!(self.print_mt(mt));
975 ast::TyKind::Tup(ref elts) => {
977 try!(self.commasep(Inconsistent, &elts[..],
978 |s, ty| s.print_type(&ty)));
980 try!(word(&mut self.s, ","));
984 ast::TyKind::Paren(ref typ) => {
986 try!(self.print_type(&typ));
989 ast::TyKind::BareFn(ref f) => {
990 let generics = ast::Generics {
991 lifetimes: f.lifetimes.clone(),
993 where_clause: ast::WhereClause {
994 id: ast::DUMMY_NODE_ID,
995 predicates: Vec::new(),
998 try!(self.print_ty_fn(f.abi,
1004 ast::TyKind::Path(None, ref path) => {
1005 try!(self.print_path(path, false, 0));
1007 ast::TyKind::Path(Some(ref qself), ref path) => {
1008 try!(self.print_qpath(path, qself, false))
1010 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1011 try!(self.print_type(&ty));
1012 try!(self.print_bounds("+", &bounds[..]));
1014 ast::TyKind::PolyTraitRef(ref bounds) => {
1015 try!(self.print_bounds("", &bounds[..]));
1017 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1018 try!(word(&mut self.s, "["));
1019 try!(self.print_type(&ty));
1020 try!(word(&mut self.s, "; "));
1021 try!(self.print_expr(&v));
1022 try!(word(&mut self.s, "]"));
1024 ast::TyKind::Typeof(ref e) => {
1025 try!(word(&mut self.s, "typeof("));
1026 try!(self.print_expr(&e));
1027 try!(word(&mut self.s, ")"));
1029 ast::TyKind::Infer => {
1030 try!(word(&mut self.s, "_"));
1032 ast::TyKind::ImplicitSelf => {
1035 ast::TyKind::Mac(ref m) => {
1036 try!(self.print_mac(m, token::Paren));
1042 pub fn print_foreign_item(&mut self,
1043 item: &ast::ForeignItem) -> io::Result<()> {
1044 try!(self.hardbreak_if_not_bol());
1045 try!(self.maybe_print_comment(item.span.lo));
1046 try!(self.print_outer_attributes(&item.attrs));
1048 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1049 try!(self.head(""));
1050 try!(self.print_fn(decl, ast::Unsafety::Normal,
1051 ast::Constness::NotConst,
1052 Abi::Rust, Some(item.ident),
1053 generics, &item.vis));
1054 try!(self.end()); // end head-ibox
1055 try!(word(&mut self.s, ";"));
1056 self.end() // end the outer fn box
1058 ast::ForeignItemKind::Static(ref t, m) => {
1059 try!(self.head(&visibility_qualified(&item.vis, "static")));
1061 try!(self.word_space("mut"));
1063 try!(self.print_ident(item.ident));
1064 try!(self.word_space(":"));
1065 try!(self.print_type(&t));
1066 try!(word(&mut self.s, ";"));
1067 try!(self.end()); // end the head-ibox
1068 self.end() // end the outer cbox
1073 fn print_associated_const(&mut self,
1076 default: Option<&ast::Expr>,
1077 vis: &ast::Visibility)
1080 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1081 try!(self.word_space("const"));
1082 try!(self.print_ident(ident));
1083 try!(self.word_space(":"));
1084 try!(self.print_type(ty));
1085 if let Some(expr) = default {
1086 try!(space(&mut self.s));
1087 try!(self.word_space("="));
1088 try!(self.print_expr(expr));
1090 word(&mut self.s, ";")
1093 fn print_associated_type(&mut self,
1095 bounds: Option<&ast::TyParamBounds>,
1096 ty: Option<&ast::Ty>)
1098 try!(self.word_space("type"));
1099 try!(self.print_ident(ident));
1100 if let Some(bounds) = bounds {
1101 try!(self.print_bounds(":", bounds));
1103 if let Some(ty) = ty {
1104 try!(space(&mut self.s));
1105 try!(self.word_space("="));
1106 try!(self.print_type(ty));
1108 word(&mut self.s, ";")
1111 /// Pretty-print an item
1112 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1113 try!(self.hardbreak_if_not_bol());
1114 try!(self.maybe_print_comment(item.span.lo));
1115 try!(self.print_outer_attributes(&item.attrs));
1116 try!(self.ann.pre(self, NodeItem(item)));
1118 ast::ItemKind::ExternCrate(ref optional_path) => {
1119 try!(self.head(&visibility_qualified(&item.vis, "extern crate")));
1120 if let Some(p) = *optional_path {
1121 let val = p.as_str();
1122 if val.contains("-") {
1123 try!(self.print_string(&val, ast::StrStyle::Cooked));
1125 try!(self.print_name(p));
1127 try!(space(&mut self.s));
1128 try!(word(&mut self.s, "as"));
1129 try!(space(&mut self.s));
1131 try!(self.print_ident(item.ident));
1132 try!(word(&mut self.s, ";"));
1133 try!(self.end()); // end inner head-block
1134 try!(self.end()); // end outer head-block
1136 ast::ItemKind::Use(ref vp) => {
1137 try!(self.head(&visibility_qualified(&item.vis, "use")));
1138 try!(self.print_view_path(&vp));
1139 try!(word(&mut self.s, ";"));
1140 try!(self.end()); // end inner head-block
1141 try!(self.end()); // end outer head-block
1143 ast::ItemKind::Static(ref ty, m, ref expr) => {
1144 try!(self.head(&visibility_qualified(&item.vis, "static")));
1145 if m == ast::Mutability::Mutable {
1146 try!(self.word_space("mut"));
1148 try!(self.print_ident(item.ident));
1149 try!(self.word_space(":"));
1150 try!(self.print_type(&ty));
1151 try!(space(&mut self.s));
1152 try!(self.end()); // end the head-ibox
1154 try!(self.word_space("="));
1155 try!(self.print_expr(&expr));
1156 try!(word(&mut self.s, ";"));
1157 try!(self.end()); // end the outer cbox
1159 ast::ItemKind::Const(ref ty, ref expr) => {
1160 try!(self.head(&visibility_qualified(&item.vis, "const")));
1161 try!(self.print_ident(item.ident));
1162 try!(self.word_space(":"));
1163 try!(self.print_type(&ty));
1164 try!(space(&mut self.s));
1165 try!(self.end()); // end the head-ibox
1167 try!(self.word_space("="));
1168 try!(self.print_expr(&expr));
1169 try!(word(&mut self.s, ";"));
1170 try!(self.end()); // end the outer cbox
1172 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1173 try!(self.head(""));
1183 try!(word(&mut self.s, " "));
1184 try!(self.print_block_with_attrs(&body, &item.attrs));
1186 ast::ItemKind::Mod(ref _mod) => {
1187 try!(self.head(&visibility_qualified(&item.vis, "mod")));
1188 try!(self.print_ident(item.ident));
1191 try!(self.print_mod(_mod, &item.attrs));
1192 try!(self.bclose(item.span));
1194 ast::ItemKind::ForeignMod(ref nmod) => {
1195 try!(self.head("extern"));
1196 try!(self.word_nbsp(&nmod.abi.to_string()));
1198 try!(self.print_foreign_mod(nmod, &item.attrs));
1199 try!(self.bclose(item.span));
1201 ast::ItemKind::Ty(ref ty, ref params) => {
1202 try!(self.ibox(INDENT_UNIT));
1204 try!(self.word_nbsp(&visibility_qualified(&item.vis, "type")));
1205 try!(self.print_ident(item.ident));
1206 try!(self.print_generics(params));
1207 try!(self.end()); // end the inner ibox
1209 try!(self.print_where_clause(¶ms.where_clause));
1210 try!(space(&mut self.s));
1211 try!(self.word_space("="));
1212 try!(self.print_type(&ty));
1213 try!(word(&mut self.s, ";"));
1214 try!(self.end()); // end the outer ibox
1216 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1217 try!(self.print_enum_def(
1225 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1226 try!(self.head(&visibility_qualified(&item.vis, "struct")));
1227 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1230 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1231 try!(self.head(""));
1232 try!(self.print_visibility(&item.vis));
1233 try!(self.print_unsafety(unsafety));
1234 try!(self.word_nbsp("impl"));
1235 try!(self.print_trait_ref(trait_ref));
1236 try!(space(&mut self.s));
1237 try!(self.word_space("for"));
1238 try!(self.word_space(".."));
1240 try!(self.bclose(item.span));
1242 ast::ItemKind::Impl(unsafety,
1247 ref impl_items) => {
1248 try!(self.head(""));
1249 try!(self.print_visibility(&item.vis));
1250 try!(self.print_unsafety(unsafety));
1251 try!(self.word_nbsp("impl"));
1253 if generics.is_parameterized() {
1254 try!(self.print_generics(generics));
1255 try!(space(&mut self.s));
1259 ast::ImplPolarity::Negative => {
1260 try!(word(&mut self.s, "!"));
1267 try!(self.print_trait_ref(t));
1268 try!(space(&mut self.s));
1269 try!(self.word_space("for"));
1274 try!(self.print_type(&ty));
1275 try!(self.print_where_clause(&generics.where_clause));
1277 try!(space(&mut self.s));
1279 try!(self.print_inner_attributes(&item.attrs));
1280 for impl_item in impl_items {
1281 try!(self.print_impl_item(impl_item));
1283 try!(self.bclose(item.span));
1285 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1286 try!(self.head(""));
1287 try!(self.print_visibility(&item.vis));
1288 try!(self.print_unsafety(unsafety));
1289 try!(self.word_nbsp("trait"));
1290 try!(self.print_ident(item.ident));
1291 try!(self.print_generics(generics));
1292 let mut real_bounds = Vec::with_capacity(bounds.len());
1293 for b in bounds.iter() {
1294 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1295 try!(space(&mut self.s));
1296 try!(self.word_space("for ?"));
1297 try!(self.print_trait_ref(&ptr.trait_ref));
1299 real_bounds.push(b.clone());
1302 try!(self.print_bounds(":", &real_bounds[..]));
1303 try!(self.print_where_clause(&generics.where_clause));
1304 try!(word(&mut self.s, " "));
1306 for trait_item in trait_items {
1307 try!(self.print_trait_item(trait_item));
1309 try!(self.bclose(item.span));
1311 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1312 try!(self.print_visibility(&item.vis));
1313 try!(self.print_path(&node.path, false, 0));
1314 try!(word(&mut self.s, "! "));
1315 try!(self.print_ident(item.ident));
1316 try!(self.cbox(INDENT_UNIT));
1318 try!(self.print_tts(&node.tts[..]));
1319 try!(self.pclose());
1320 try!(word(&mut self.s, ";"));
1324 self.ann.post(self, NodeItem(item))
1327 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1328 self.print_path(&t.path, false, 0)
1331 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1332 if !lifetimes.is_empty() {
1333 try!(word(&mut self.s, "for<"));
1334 let mut comma = false;
1335 for lifetime_def in lifetimes {
1337 try!(self.word_space(","))
1339 try!(self.print_lifetime_def(lifetime_def));
1342 try!(word(&mut self.s, ">"));
1347 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1348 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1349 self.print_trait_ref(&t.trait_ref)
1352 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1353 generics: &ast::Generics, ident: ast::Ident,
1354 span: codemap::Span,
1355 visibility: &ast::Visibility) -> io::Result<()> {
1356 try!(self.head(&visibility_qualified(visibility, "enum")));
1357 try!(self.print_ident(ident));
1358 try!(self.print_generics(generics));
1359 try!(self.print_where_clause(&generics.where_clause));
1360 try!(space(&mut self.s));
1361 self.print_variants(&enum_definition.variants, span)
1364 pub fn print_variants(&mut self,
1365 variants: &[ast::Variant],
1366 span: codemap::Span) -> io::Result<()> {
1369 try!(self.space_if_not_bol());
1370 try!(self.maybe_print_comment(v.span.lo));
1371 try!(self.print_outer_attributes(&v.node.attrs));
1372 try!(self.ibox(INDENT_UNIT));
1373 try!(self.print_variant(v));
1374 try!(word(&mut self.s, ","));
1376 try!(self.maybe_print_trailing_comment(v.span, None));
1381 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1383 ast::Visibility::Public => self.word_nbsp("pub"),
1384 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1385 ast::Visibility::Restricted { ref path, .. } =>
1386 self.word_nbsp(&format!("pub({})", path)),
1387 ast::Visibility::Inherited => Ok(())
1391 pub fn print_struct(&mut self,
1392 struct_def: &ast::VariantData,
1393 generics: &ast::Generics,
1395 span: codemap::Span,
1396 print_finalizer: bool) -> io::Result<()> {
1397 try!(self.print_ident(ident));
1398 try!(self.print_generics(generics));
1399 if !struct_def.is_struct() {
1400 if struct_def.is_tuple() {
1403 Inconsistent, struct_def.fields(),
1405 try!(s.print_visibility(&field.vis));
1406 try!(s.maybe_print_comment(field.span.lo));
1407 s.print_type(&field.ty)
1410 try!(self.pclose());
1412 try!(self.print_where_clause(&generics.where_clause));
1413 if print_finalizer {
1414 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 try!(self.hardbreak_if_not_bol());
1426 try!(self.maybe_print_comment(field.span.lo));
1427 try!(self.print_outer_attributes(&field.attrs));
1428 try!(self.print_visibility(&field.vis));
1429 try!(self.print_ident(field.ident.unwrap()));
1430 try!(self.word_nbsp(":"));
1431 try!(self.print_type(&field.ty));
1432 try!(word(&mut self.s, ","));
1439 /// This doesn't deserve to be called "pretty" printing, but it should be
1440 /// meaning-preserving. A quick hack that might help would be to look at the
1441 /// spans embedded in the TTs to decide where to put spaces and newlines.
1442 /// But it'd be better to parse these according to the grammar of the
1443 /// appropriate macro, transcribe back into the grammar we just parsed from,
1444 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1445 /// expression arguments as expressions). It can be done! I think.
1446 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1448 TokenTree::Token(_, ref tk) => {
1449 try!(word(&mut self.s, &token_to_string(tk)));
1451 parse::token::DocComment(..) => {
1452 hardbreak(&mut self.s)
1457 TokenTree::Delimited(_, ref delimed) => {
1458 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1459 try!(space(&mut self.s));
1460 try!(self.print_tts(&delimed.tts));
1461 try!(space(&mut self.s));
1462 word(&mut self.s, &token_to_string(&delimed.close_token()))
1464 TokenTree::Sequence(_, ref seq) => {
1465 try!(word(&mut self.s, "$("));
1466 for tt_elt in &seq.tts {
1467 try!(self.print_tt(tt_elt));
1469 try!(word(&mut self.s, ")"));
1470 match seq.separator {
1472 try!(word(&mut self.s, &token_to_string(tk)));
1477 ast::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1478 ast::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1484 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1486 for (i, tt) in tts.iter().enumerate() {
1488 try!(space(&mut self.s));
1490 try!(self.print_tt(tt));
1495 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1496 try!(self.head(""));
1497 let generics = ast::Generics::default();
1498 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1499 match v.node.disr_expr {
1501 try!(space(&mut self.s));
1502 try!(self.word_space("="));
1509 pub fn print_method_sig(&mut self,
1512 vis: &ast::Visibility)
1514 self.print_fn(&m.decl,
1523 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1525 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1526 try!(self.hardbreak_if_not_bol());
1527 try!(self.maybe_print_comment(ti.span.lo));
1528 try!(self.print_outer_attributes(&ti.attrs));
1530 ast::TraitItemKind::Const(ref ty, ref default) => {
1531 try!(self.print_associated_const(ti.ident, &ty,
1532 default.as_ref().map(|expr| &**expr),
1533 &ast::Visibility::Inherited));
1535 ast::TraitItemKind::Method(ref sig, ref body) => {
1537 try!(self.head(""));
1539 try!(self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited));
1540 if let Some(ref body) = *body {
1542 try!(self.print_block_with_attrs(body, &ti.attrs));
1544 try!(word(&mut self.s, ";"));
1547 ast::TraitItemKind::Type(ref bounds, ref default) => {
1548 try!(self.print_associated_type(ti.ident, Some(bounds),
1549 default.as_ref().map(|ty| &**ty)));
1552 self.ann.post(self, NodeSubItem(ti.id))
1555 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1556 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1557 try!(self.hardbreak_if_not_bol());
1558 try!(self.maybe_print_comment(ii.span.lo));
1559 try!(self.print_outer_attributes(&ii.attrs));
1560 if let ast::Defaultness::Default = ii.defaultness {
1561 try!(self.word_nbsp("default"));
1564 ast::ImplItemKind::Const(ref ty, ref expr) => {
1565 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis));
1567 ast::ImplItemKind::Method(ref sig, ref body) => {
1568 try!(self.head(""));
1569 try!(self.print_method_sig(ii.ident, sig, &ii.vis));
1571 try!(self.print_block_with_attrs(body, &ii.attrs));
1573 ast::ImplItemKind::Type(ref ty) => {
1574 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1576 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1577 // code copied from ItemKind::Mac:
1578 try!(self.print_path(&node.path, false, 0));
1579 try!(word(&mut self.s, "! "));
1580 try!(self.cbox(INDENT_UNIT));
1582 try!(self.print_tts(&node.tts[..]));
1583 try!(self.pclose());
1584 try!(word(&mut self.s, ";"));
1588 self.ann.post(self, NodeSubItem(ii.id))
1591 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1592 try!(self.maybe_print_comment(st.span.lo));
1594 ast::StmtKind::Decl(ref decl, _) => {
1595 try!(self.print_decl(&decl));
1597 ast::StmtKind::Expr(ref expr, _) => {
1598 try!(self.space_if_not_bol());
1599 try!(self.print_expr_outer_attr_style(&expr, false));
1601 ast::StmtKind::Semi(ref expr, _) => {
1602 try!(self.space_if_not_bol());
1603 try!(self.print_expr_outer_attr_style(&expr, false));
1604 try!(word(&mut self.s, ";"));
1606 ast::StmtKind::Mac(ref mac, style, ref attrs) => {
1607 try!(self.space_if_not_bol());
1608 try!(self.print_outer_attributes(&attrs));
1609 let delim = match style {
1610 ast::MacStmtStyle::Braces => token::Brace,
1613 try!(self.print_mac(&mac, delim));
1615 ast::MacStmtStyle::Braces => {}
1616 _ => try!(word(&mut self.s, ";")),
1620 if parse::classify::stmt_ends_with_semi(&st.node) {
1621 try!(word(&mut self.s, ";"));
1623 self.maybe_print_trailing_comment(st.span, None)
1626 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1627 self.print_block_with_attrs(blk, &[])
1630 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1631 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1634 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1635 attrs: &[ast::Attribute])
1637 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1640 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1641 indented: usize) -> io::Result<()> {
1642 self.print_block_maybe_unclosed(blk, indented, &[], false)
1645 pub fn print_block_with_attrs(&mut self,
1647 attrs: &[ast::Attribute]) -> io::Result<()> {
1648 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1651 pub fn print_block_maybe_unclosed(&mut self,
1654 attrs: &[ast::Attribute],
1655 close_box: bool) -> io::Result<()> {
1657 BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")),
1658 BlockCheckMode::Default => ()
1660 try!(self.maybe_print_comment(blk.span.lo));
1661 try!(self.ann.pre(self, NodeBlock(blk)));
1664 try!(self.print_inner_attributes(attrs));
1666 for st in &blk.stmts {
1667 try!(self.print_stmt(st));
1671 try!(self.space_if_not_bol());
1672 try!(self.print_expr_outer_attr_style(&expr, false));
1673 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1677 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1678 self.ann.post(self, NodeBlock(blk))
1681 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1685 // "another else-if"
1686 ast::ExprKind::If(ref i, ref then, ref e) => {
1687 try!(self.cbox(INDENT_UNIT - 1));
1689 try!(word(&mut self.s, " else if "));
1690 try!(self.print_expr(&i));
1691 try!(space(&mut self.s));
1692 try!(self.print_block(&then));
1693 self.print_else(e.as_ref().map(|e| &**e))
1695 // "another else-if-let"
1696 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1697 try!(self.cbox(INDENT_UNIT - 1));
1699 try!(word(&mut self.s, " else if let "));
1700 try!(self.print_pat(&pat));
1701 try!(space(&mut self.s));
1702 try!(self.word_space("="));
1703 try!(self.print_expr(&expr));
1704 try!(space(&mut self.s));
1705 try!(self.print_block(&then));
1706 self.print_else(e.as_ref().map(|e| &**e))
1709 ast::ExprKind::Block(ref b) => {
1710 try!(self.cbox(INDENT_UNIT - 1));
1712 try!(word(&mut self.s, " else "));
1713 self.print_block(&b)
1715 // BLEAH, constraints would be great here
1717 panic!("print_if saw if with weird alternative");
1725 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1726 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1727 try!(self.head("if"));
1728 try!(self.print_expr(test));
1729 try!(space(&mut self.s));
1730 try!(self.print_block(blk));
1731 self.print_else(elseopt)
1734 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1735 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1736 try!(self.head("if let"));
1737 try!(self.print_pat(pat));
1738 try!(space(&mut self.s));
1739 try!(self.word_space("="));
1740 try!(self.print_expr(expr));
1741 try!(space(&mut self.s));
1742 try!(self.print_block(blk));
1743 self.print_else(elseopt)
1746 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1748 try!(self.print_path(&m.node.path, false, 0));
1749 try!(word(&mut self.s, "!"));
1751 token::Paren => try!(self.popen()),
1752 token::Bracket => try!(word(&mut self.s, "[")),
1754 try!(self.head(""));
1758 try!(self.print_tts(&m.node.tts));
1760 token::Paren => self.pclose(),
1761 token::Bracket => word(&mut self.s, "]"),
1762 token::Brace => self.bclose(m.span),
1767 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1769 try!(self.commasep_exprs(Inconsistent, args));
1773 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1774 binop: ast::BinOp) -> bool {
1775 match sub_expr.node {
1776 ast::ExprKind::Binary(ref sub_op, _, _) => {
1777 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1778 AssocOp::from_ast_binop(binop.node).precedence() {
1788 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1789 let needs_par = needs_parentheses(expr);
1793 try!(self.print_expr(expr));
1795 try!(self.pclose());
1800 fn print_expr_in_place(&mut self,
1802 expr: &ast::Expr) -> io::Result<()> {
1803 try!(self.print_expr_maybe_paren(place));
1804 try!(space(&mut self.s));
1805 try!(self.word_space("<-"));
1806 self.print_expr_maybe_paren(expr)
1809 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1810 attrs: &[Attribute]) -> io::Result<()> {
1811 try!(self.ibox(INDENT_UNIT));
1812 try!(word(&mut self.s, "["));
1813 try!(self.print_inner_attributes_inline(attrs));
1814 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1815 try!(word(&mut self.s, "]"));
1819 fn print_expr_repeat(&mut self,
1820 element: &ast::Expr,
1822 attrs: &[Attribute]) -> io::Result<()> {
1823 try!(self.ibox(INDENT_UNIT));
1824 try!(word(&mut self.s, "["));
1825 try!(self.print_inner_attributes_inline(attrs));
1826 try!(self.print_expr(element));
1827 try!(self.word_space(";"));
1828 try!(self.print_expr(count));
1829 try!(word(&mut self.s, "]"));
1833 fn print_expr_struct(&mut self,
1835 fields: &[ast::Field],
1836 wth: &Option<P<ast::Expr>>,
1837 attrs: &[Attribute]) -> io::Result<()> {
1838 try!(self.print_path(path, true, 0));
1839 try!(word(&mut self.s, "{"));
1840 try!(self.print_inner_attributes_inline(attrs));
1841 try!(self.commasep_cmnt(
1845 try!(s.ibox(INDENT_UNIT));
1846 try!(s.print_ident(field.ident.node));
1847 try!(s.word_space(":"));
1848 try!(s.print_expr(&field.expr));
1854 try!(self.ibox(INDENT_UNIT));
1855 if !fields.is_empty() {
1856 try!(word(&mut self.s, ","));
1857 try!(space(&mut self.s));
1859 try!(word(&mut self.s, ".."));
1860 try!(self.print_expr(&expr));
1863 _ => if !fields.is_empty() {
1864 try!(word(&mut self.s, ","))
1867 try!(word(&mut self.s, "}"));
1871 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1872 attrs: &[Attribute]) -> io::Result<()> {
1874 try!(self.print_inner_attributes_inline(attrs));
1875 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1876 if exprs.len() == 1 {
1877 try!(word(&mut self.s, ","));
1882 fn print_expr_call(&mut self,
1884 args: &[P<ast::Expr>]) -> io::Result<()> {
1885 try!(self.print_expr_maybe_paren(func));
1886 self.print_call_post(args)
1889 fn print_expr_method_call(&mut self,
1890 ident: ast::SpannedIdent,
1892 args: &[P<ast::Expr>]) -> io::Result<()> {
1893 let base_args = &args[1..];
1894 try!(self.print_expr(&args[0]));
1895 try!(word(&mut self.s, "."));
1896 try!(self.print_ident(ident.node));
1897 if !tys.is_empty() {
1898 try!(word(&mut self.s, "::<"));
1899 try!(self.commasep(Inconsistent, tys,
1900 |s, ty| s.print_type(&ty)));
1901 try!(word(&mut self.s, ">"));
1903 self.print_call_post(base_args)
1906 fn print_expr_binary(&mut self,
1909 rhs: &ast::Expr) -> io::Result<()> {
1910 if self.check_expr_bin_needs_paren(lhs, op) {
1911 try!(self.print_expr_maybe_paren(lhs));
1913 try!(self.print_expr(lhs));
1915 try!(space(&mut self.s));
1916 try!(self.word_space(op.node.to_string()));
1917 if self.check_expr_bin_needs_paren(rhs, op) {
1918 self.print_expr_maybe_paren(rhs)
1920 self.print_expr(rhs)
1924 fn print_expr_unary(&mut self,
1926 expr: &ast::Expr) -> io::Result<()> {
1927 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1928 self.print_expr_maybe_paren(expr)
1931 fn print_expr_addr_of(&mut self,
1932 mutability: ast::Mutability,
1933 expr: &ast::Expr) -> io::Result<()> {
1934 try!(word(&mut self.s, "&"));
1935 try!(self.print_mutability(mutability));
1936 self.print_expr_maybe_paren(expr)
1939 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1940 self.print_expr_outer_attr_style(expr, true)
1943 fn print_expr_outer_attr_style(&mut self,
1945 is_inline: bool) -> io::Result<()> {
1946 try!(self.maybe_print_comment(expr.span.lo));
1948 let attrs = &expr.attrs;
1950 try!(self.print_outer_attributes_inline(attrs));
1952 try!(self.print_outer_attributes(attrs));
1955 try!(self.ibox(INDENT_UNIT));
1956 try!(self.ann.pre(self, NodeExpr(expr)));
1958 ast::ExprKind::Box(ref expr) => {
1959 try!(self.word_space("box"));
1960 try!(self.print_expr(expr));
1962 ast::ExprKind::InPlace(ref place, ref expr) => {
1963 try!(self.print_expr_in_place(place, expr));
1965 ast::ExprKind::Vec(ref exprs) => {
1966 try!(self.print_expr_vec(&exprs[..], attrs));
1968 ast::ExprKind::Repeat(ref element, ref count) => {
1969 try!(self.print_expr_repeat(&element, &count, attrs));
1971 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1972 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
1974 ast::ExprKind::Tup(ref exprs) => {
1975 try!(self.print_expr_tup(&exprs[..], attrs));
1977 ast::ExprKind::Call(ref func, ref args) => {
1978 try!(self.print_expr_call(&func, &args[..]));
1980 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
1981 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1983 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1984 try!(self.print_expr_binary(op, &lhs, &rhs));
1986 ast::ExprKind::Unary(op, ref expr) => {
1987 try!(self.print_expr_unary(op, &expr));
1989 ast::ExprKind::AddrOf(m, ref expr) => {
1990 try!(self.print_expr_addr_of(m, &expr));
1992 ast::ExprKind::Lit(ref lit) => {
1993 try!(self.print_literal(&lit));
1995 ast::ExprKind::Cast(ref expr, ref ty) => {
1996 if let ast::ExprKind::Cast(..) = expr.node {
1997 try!(self.print_expr(&expr));
1999 try!(self.print_expr_maybe_paren(&expr));
2001 try!(space(&mut self.s));
2002 try!(self.word_space("as"));
2003 try!(self.print_type(&ty));
2005 ast::ExprKind::Type(ref expr, ref ty) => {
2006 try!(self.print_expr(&expr));
2007 try!(self.word_space(":"));
2008 try!(self.print_type(&ty));
2010 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2011 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
2013 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2014 try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e)));
2016 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2017 if let Some(ident) = opt_ident {
2018 try!(self.print_ident(ident.node));
2019 try!(self.word_space(":"));
2021 try!(self.head("while"));
2022 try!(self.print_expr(&test));
2023 try!(space(&mut self.s));
2024 try!(self.print_block_with_attrs(&blk, attrs));
2026 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2027 if let Some(ident) = opt_ident {
2028 try!(self.print_ident(ident.node));
2029 try!(self.word_space(":"));
2031 try!(self.head("while let"));
2032 try!(self.print_pat(&pat));
2033 try!(space(&mut self.s));
2034 try!(self.word_space("="));
2035 try!(self.print_expr(&expr));
2036 try!(space(&mut self.s));
2037 try!(self.print_block_with_attrs(&blk, attrs));
2039 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2040 if let Some(ident) = opt_ident {
2041 try!(self.print_ident(ident.node));
2042 try!(self.word_space(":"));
2044 try!(self.head("for"));
2045 try!(self.print_pat(&pat));
2046 try!(space(&mut self.s));
2047 try!(self.word_space("in"));
2048 try!(self.print_expr(&iter));
2049 try!(space(&mut self.s));
2050 try!(self.print_block_with_attrs(&blk, attrs));
2052 ast::ExprKind::Loop(ref blk, opt_ident) => {
2053 if let Some(ident) = opt_ident {
2054 try!(self.print_ident(ident.node));
2055 try!(self.word_space(":"));
2057 try!(self.head("loop"));
2058 try!(space(&mut self.s));
2059 try!(self.print_block_with_attrs(&blk, attrs));
2061 ast::ExprKind::Match(ref expr, ref arms) => {
2062 try!(self.cbox(INDENT_UNIT));
2064 try!(self.word_nbsp("match"));
2065 try!(self.print_expr(&expr));
2066 try!(space(&mut self.s));
2068 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2070 try!(self.print_arm(arm));
2072 try!(self.bclose_(expr.span, INDENT_UNIT));
2074 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2075 try!(self.print_capture_clause(capture_clause));
2077 try!(self.print_fn_block_args(&decl));
2078 try!(space(&mut self.s));
2080 let default_return = match decl.output {
2081 ast::FunctionRetTy::Default(..) => true,
2085 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2086 try!(self.print_block_unclosed(&body));
2088 // we extract the block, so as not to create another set of boxes
2089 let i_expr = body.expr.as_ref().unwrap();
2091 ast::ExprKind::Block(ref blk) => {
2092 try!(self.print_block_unclosed_with_attrs(&blk, &i_expr.attrs));
2095 // this is a bare expression
2096 try!(self.print_expr(&i_expr));
2097 try!(self.end()); // need to close a box
2101 // a box will be closed by print_expr, but we didn't want an overall
2102 // wrapper so we closed the corresponding opening. so create an
2103 // empty box to satisfy the close.
2106 ast::ExprKind::Block(ref blk) => {
2107 // containing cbox, will be closed by print-block at }
2108 try!(self.cbox(INDENT_UNIT));
2109 // head-box, will be closed by print-block after {
2111 try!(self.print_block_with_attrs(&blk, attrs));
2113 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2114 try!(self.print_expr(&lhs));
2115 try!(space(&mut self.s));
2116 try!(self.word_space("="));
2117 try!(self.print_expr(&rhs));
2119 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2120 try!(self.print_expr(&lhs));
2121 try!(space(&mut self.s));
2122 try!(word(&mut self.s, op.node.to_string()));
2123 try!(self.word_space("="));
2124 try!(self.print_expr(&rhs));
2126 ast::ExprKind::Field(ref expr, id) => {
2127 try!(self.print_expr(&expr));
2128 try!(word(&mut self.s, "."));
2129 try!(self.print_ident(id.node));
2131 ast::ExprKind::TupField(ref expr, id) => {
2132 try!(self.print_expr(&expr));
2133 try!(word(&mut self.s, "."));
2134 try!(self.print_usize(id.node));
2136 ast::ExprKind::Index(ref expr, ref index) => {
2137 try!(self.print_expr(&expr));
2138 try!(word(&mut self.s, "["));
2139 try!(self.print_expr(&index));
2140 try!(word(&mut self.s, "]"));
2142 ast::ExprKind::Range(ref start, ref end, limits) => {
2143 if let &Some(ref e) = start {
2144 try!(self.print_expr(&e));
2146 if limits == ast::RangeLimits::HalfOpen {
2147 try!(word(&mut self.s, ".."));
2149 try!(word(&mut self.s, "..."));
2151 if let &Some(ref e) = end {
2152 try!(self.print_expr(&e));
2155 ast::ExprKind::Path(None, ref path) => {
2156 try!(self.print_path(path, true, 0))
2158 ast::ExprKind::Path(Some(ref qself), ref path) => {
2159 try!(self.print_qpath(path, qself, true))
2161 ast::ExprKind::Break(opt_ident) => {
2162 try!(word(&mut self.s, "break"));
2163 try!(space(&mut self.s));
2164 if let Some(ident) = opt_ident {
2165 try!(self.print_ident(ident.node));
2166 try!(space(&mut self.s));
2169 ast::ExprKind::Again(opt_ident) => {
2170 try!(word(&mut self.s, "continue"));
2171 try!(space(&mut self.s));
2172 if let Some(ident) = opt_ident {
2173 try!(self.print_ident(ident.node));
2174 try!(space(&mut self.s))
2177 ast::ExprKind::Ret(ref result) => {
2178 try!(word(&mut self.s, "return"));
2181 try!(word(&mut self.s, " "));
2182 try!(self.print_expr(&expr));
2187 ast::ExprKind::InlineAsm(ref a) => {
2188 try!(word(&mut self.s, "asm!"));
2190 try!(self.print_string(&a.asm, a.asm_str_style));
2191 try!(self.word_space(":"));
2193 try!(self.commasep(Inconsistent, &a.outputs,
2195 let mut ch = out.constraint.chars();
2197 Some('=') if out.is_rw => {
2198 try!(s.print_string(&format!("+{}", ch.as_str()),
2199 ast::StrStyle::Cooked))
2201 _ => try!(s.print_string(&out.constraint,
2202 ast::StrStyle::Cooked))
2205 try!(s.print_expr(&out.expr));
2209 try!(space(&mut self.s));
2210 try!(self.word_space(":"));
2212 try!(self.commasep(Inconsistent, &a.inputs,
2213 |s, &(ref co, ref o)| {
2214 try!(s.print_string(&co, ast::StrStyle::Cooked));
2216 try!(s.print_expr(&o));
2220 try!(space(&mut self.s));
2221 try!(self.word_space(":"));
2223 try!(self.commasep(Inconsistent, &a.clobbers,
2225 try!(s.print_string(&co, ast::StrStyle::Cooked));
2229 let mut options = vec!();
2231 options.push("volatile");
2234 options.push("alignstack");
2236 if a.dialect == ast::AsmDialect::Intel {
2237 options.push("intel");
2240 if !options.is_empty() {
2241 try!(space(&mut self.s));
2242 try!(self.word_space(":"));
2243 try!(self.commasep(Inconsistent, &options,
2245 try!(s.print_string(co, ast::StrStyle::Cooked));
2250 try!(self.pclose());
2252 ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2253 ast::ExprKind::Paren(ref e) => {
2255 try!(self.print_inner_attributes_inline(attrs));
2256 try!(self.print_expr(&e));
2257 try!(self.pclose());
2259 ast::ExprKind::Try(ref e) => {
2260 try!(self.print_expr(e));
2261 try!(word(&mut self.s, "?"))
2264 try!(self.ann.post(self, NodeExpr(expr)));
2268 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2269 try!(self.print_pat(&loc.pat));
2270 if let Some(ref ty) = loc.ty {
2271 try!(self.word_space(":"));
2272 try!(self.print_type(&ty));
2277 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2278 try!(self.maybe_print_comment(decl.span.lo));
2280 ast::DeclKind::Local(ref loc) => {
2281 try!(self.print_outer_attributes(&loc.attrs));
2282 try!(self.space_if_not_bol());
2283 try!(self.ibox(INDENT_UNIT));
2284 try!(self.word_nbsp("let"));
2286 try!(self.ibox(INDENT_UNIT));
2287 try!(self.print_local_decl(&loc));
2289 if let Some(ref init) = loc.init {
2291 try!(self.word_space("="));
2292 try!(self.print_expr(&init));
2296 ast::DeclKind::Item(ref item) => self.print_item(&item)
2300 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2301 try!(word(&mut self.s, &ident.name.as_str()));
2302 self.ann.post(self, NodeIdent(&ident))
2305 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2306 word(&mut self.s, &i.to_string())
2309 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2310 try!(word(&mut self.s, &name.as_str()));
2311 self.ann.post(self, NodeName(&name))
2314 pub fn print_for_decl(&mut self, loc: &ast::Local,
2315 coll: &ast::Expr) -> io::Result<()> {
2316 try!(self.print_local_decl(loc));
2317 try!(space(&mut self.s));
2318 try!(self.word_space("in"));
2319 self.print_expr(coll)
2322 fn print_path(&mut self,
2324 colons_before_params: bool,
2328 try!(self.maybe_print_comment(path.span.lo));
2330 let mut first = !path.global;
2331 for segment in &path.segments[..path.segments.len()-depth] {
2335 try!(word(&mut self.s, "::"))
2338 try!(self.print_ident(segment.identifier));
2340 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2346 fn print_qpath(&mut self,
2349 colons_before_params: bool)
2352 try!(word(&mut self.s, "<"));
2353 try!(self.print_type(&qself.ty));
2354 if qself.position > 0 {
2355 try!(space(&mut self.s));
2356 try!(self.word_space("as"));
2357 let depth = path.segments.len() - qself.position;
2358 try!(self.print_path(&path, false, depth));
2360 try!(word(&mut self.s, ">"));
2361 try!(word(&mut self.s, "::"));
2362 let item_segment = path.segments.last().unwrap();
2363 try!(self.print_ident(item_segment.identifier));
2364 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2367 fn print_path_parameters(&mut self,
2368 parameters: &ast::PathParameters,
2369 colons_before_params: bool)
2372 if parameters.is_empty() {
2376 if colons_before_params {
2377 try!(word(&mut self.s, "::"))
2381 ast::PathParameters::AngleBracketed(ref data) => {
2382 try!(word(&mut self.s, "<"));
2384 let mut comma = false;
2385 for lifetime in &data.lifetimes {
2387 try!(self.word_space(","))
2389 try!(self.print_lifetime(lifetime));
2393 if !data.types.is_empty() {
2395 try!(self.word_space(","))
2400 |s, ty| s.print_type(&ty)));
2404 for binding in data.bindings.iter() {
2406 try!(self.word_space(","))
2408 try!(self.print_ident(binding.ident));
2409 try!(space(&mut self.s));
2410 try!(self.word_space("="));
2411 try!(self.print_type(&binding.ty));
2415 try!(word(&mut self.s, ">"))
2418 ast::PathParameters::Parenthesized(ref data) => {
2419 try!(word(&mut self.s, "("));
2423 |s, ty| s.print_type(&ty)));
2424 try!(word(&mut self.s, ")"));
2429 try!(self.space_if_not_bol());
2430 try!(self.word_space("->"));
2431 try!(self.print_type(&ty));
2440 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2441 try!(self.maybe_print_comment(pat.span.lo));
2442 try!(self.ann.pre(self, NodePat(pat)));
2443 /* Pat isn't normalized, but the beauty of it
2444 is that it doesn't matter */
2446 PatKind::Wild => try!(word(&mut self.s, "_")),
2447 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2448 match binding_mode {
2449 ast::BindingMode::ByRef(mutbl) => {
2450 try!(self.word_nbsp("ref"));
2451 try!(self.print_mutability(mutbl));
2453 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2454 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2455 try!(self.word_nbsp("mut"));
2458 try!(self.print_ident(path1.node));
2459 if let Some(ref p) = *sub {
2460 try!(word(&mut self.s, "@"));
2461 try!(self.print_pat(&p));
2464 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2465 try!(self.print_path(path, true, 0));
2467 if let Some(ddpos) = ddpos {
2468 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2470 try!(self.word_space(","));
2472 try!(word(&mut self.s, ".."));
2473 if ddpos != elts.len() {
2474 try!(word(&mut self.s, ","));
2475 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2478 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2480 try!(self.pclose());
2482 PatKind::Path(ref path) => {
2483 try!(self.print_path(path, true, 0));
2485 PatKind::QPath(ref qself, ref path) => {
2486 try!(self.print_qpath(path, qself, false));
2488 PatKind::Struct(ref path, ref fields, etc) => {
2489 try!(self.print_path(path, true, 0));
2491 try!(self.word_space("{"));
2492 try!(self.commasep_cmnt(
2493 Consistent, &fields[..],
2495 try!(s.cbox(INDENT_UNIT));
2496 if !f.node.is_shorthand {
2497 try!(s.print_ident(f.node.ident));
2498 try!(s.word_nbsp(":"));
2500 try!(s.print_pat(&f.node.pat));
2503 |f| f.node.pat.span));
2505 if !fields.is_empty() { try!(self.word_space(",")); }
2506 try!(word(&mut self.s, ".."));
2508 try!(space(&mut self.s));
2509 try!(word(&mut self.s, "}"));
2511 PatKind::Tuple(ref elts, ddpos) => {
2513 if let Some(ddpos) = ddpos {
2514 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2516 try!(self.word_space(","));
2518 try!(word(&mut self.s, ".."));
2519 if ddpos != elts.len() {
2520 try!(word(&mut self.s, ","));
2521 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2524 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2525 if elts.len() == 1 {
2526 try!(word(&mut self.s, ","));
2529 try!(self.pclose());
2531 PatKind::Box(ref inner) => {
2532 try!(word(&mut self.s, "box "));
2533 try!(self.print_pat(&inner));
2535 PatKind::Ref(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 PatKind::Lit(ref e) => try!(self.print_expr(&**e)),
2543 PatKind::Range(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 PatKind::Vec(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 != PatKind::Wild {
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 PatKind::Mac(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 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2619 match explicit_self.node {
2620 SelfKind::Value(m) => {
2621 try!(self.print_mutability(m));
2622 word(&mut self.s, "self")
2624 SelfKind::Region(ref lt, m) => {
2625 try!(word(&mut self.s, "&"));
2626 try!(self.print_opt_lifetime(lt));
2627 try!(self.print_mutability(m));
2628 word(&mut self.s, "self")
2630 SelfKind::Explicit(ref typ, m) => {
2631 try!(self.print_mutability(m));
2632 try!(word(&mut self.s, "self"));
2633 try!(self.word_space(":"));
2634 self.print_type(&typ)
2639 pub fn print_fn(&mut self,
2641 unsafety: ast::Unsafety,
2642 constness: ast::Constness,
2644 name: Option<ast::Ident>,
2645 generics: &ast::Generics,
2646 vis: &ast::Visibility) -> io::Result<()> {
2647 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2649 if let Some(name) = name {
2651 try!(self.print_ident(name));
2653 try!(self.print_generics(generics));
2654 try!(self.print_fn_args_and_ret(decl));
2655 self.print_where_clause(&generics.where_clause)
2658 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2661 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false)));
2663 try!(word(&mut self.s, ", ..."));
2665 try!(self.pclose());
2667 self.print_fn_output(decl)
2670 pub fn print_fn_block_args(
2674 try!(word(&mut self.s, "|"));
2675 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true)));
2676 try!(word(&mut self.s, "|"));
2678 if let ast::FunctionRetTy::Default(..) = decl.output {
2682 try!(self.space_if_not_bol());
2683 try!(self.word_space("->"));
2685 ast::FunctionRetTy::Ty(ref ty) => {
2686 try!(self.print_type(&ty));
2687 self.maybe_print_comment(ty.span.lo)
2689 ast::FunctionRetTy::Default(..) => unreachable!(),
2690 ast::FunctionRetTy::None(span) => {
2691 try!(self.word_nbsp("!"));
2692 self.maybe_print_comment(span.lo)
2697 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2699 match capture_clause {
2700 ast::CaptureBy::Value => self.word_space("move"),
2701 ast::CaptureBy::Ref => Ok(()),
2705 pub fn print_bounds(&mut self,
2707 bounds: &[ast::TyParamBound])
2709 if !bounds.is_empty() {
2710 try!(word(&mut self.s, prefix));
2711 let mut first = true;
2712 for bound in bounds {
2717 try!(self.word_space("+"));
2721 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2722 self.print_poly_trait_ref(tref)
2724 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2725 try!(word(&mut self.s, "?"));
2726 self.print_poly_trait_ref(tref)
2728 RegionTyParamBound(ref lt) => {
2729 self.print_lifetime(lt)
2739 pub fn print_lifetime(&mut self,
2740 lifetime: &ast::Lifetime)
2743 self.print_name(lifetime.name)
2746 pub fn print_lifetime_def(&mut self,
2747 lifetime: &ast::LifetimeDef)
2750 try!(self.print_lifetime(&lifetime.lifetime));
2752 for v in &lifetime.bounds {
2753 try!(word(&mut self.s, sep));
2754 try!(self.print_lifetime(v));
2760 pub fn print_generics(&mut self,
2761 generics: &ast::Generics)
2764 let total = generics.lifetimes.len() + generics.ty_params.len();
2769 try!(word(&mut self.s, "<"));
2771 let mut ints = Vec::new();
2776 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2777 if idx < generics.lifetimes.len() {
2778 let lifetime = &generics.lifetimes[idx];
2779 s.print_lifetime_def(lifetime)
2781 let idx = idx - generics.lifetimes.len();
2782 let param = &generics.ty_params[idx];
2783 s.print_ty_param(param)
2787 try!(word(&mut self.s, ">"));
2791 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2792 try!(self.print_ident(param.ident));
2793 try!(self.print_bounds(":", ¶m.bounds));
2794 match param.default {
2795 Some(ref default) => {
2796 try!(space(&mut self.s));
2797 try!(self.word_space("="));
2798 self.print_type(&default)
2804 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2806 if where_clause.predicates.is_empty() {
2810 try!(space(&mut self.s));
2811 try!(self.word_space("where"));
2813 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2815 try!(self.word_space(","));
2819 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2823 try!(self.print_formal_lifetime_list(bound_lifetimes));
2824 try!(self.print_type(&bounded_ty));
2825 try!(self.print_bounds(":", bounds));
2827 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2830 try!(self.print_lifetime(lifetime));
2831 try!(word(&mut self.s, ":"));
2833 for (i, bound) in bounds.iter().enumerate() {
2834 try!(self.print_lifetime(bound));
2837 try!(word(&mut self.s, ":"));
2841 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2842 try!(self.print_path(path, false, 0));
2843 try!(space(&mut self.s));
2844 try!(self.word_space("="));
2845 try!(self.print_type(&ty));
2853 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2855 ast::ViewPathSimple(ident, ref path) => {
2856 try!(self.print_path(path, false, 0));
2858 if path.segments.last().unwrap().identifier.name !=
2860 try!(space(&mut self.s));
2861 try!(self.word_space("as"));
2862 try!(self.print_ident(ident));
2868 ast::ViewPathGlob(ref path) => {
2869 try!(self.print_path(path, false, 0));
2870 word(&mut self.s, "::*")
2873 ast::ViewPathList(ref path, ref idents) => {
2874 if path.segments.is_empty() {
2875 try!(word(&mut self.s, "{"));
2877 try!(self.print_path(path, false, 0));
2878 try!(word(&mut self.s, "::{"));
2880 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2882 ast::PathListItemKind::Ident { name, rename, .. } => {
2883 try!(s.print_ident(name));
2884 if let Some(ident) = rename {
2885 try!(space(&mut s.s));
2886 try!(s.word_space("as"));
2887 try!(s.print_ident(ident));
2891 ast::PathListItemKind::Mod { rename, .. } => {
2892 try!(word(&mut s.s, "self"));
2893 if let Some(ident) = rename {
2894 try!(space(&mut s.s));
2895 try!(s.word_space("as"));
2896 try!(s.print_ident(ident));
2902 word(&mut self.s, "}")
2907 pub fn print_mutability(&mut self,
2908 mutbl: ast::Mutability) -> io::Result<()> {
2910 ast::Mutability::Mutable => self.word_nbsp("mut"),
2911 ast::Mutability::Immutable => Ok(()),
2915 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2916 try!(self.print_mutability(mt.mutbl));
2917 self.print_type(&mt.ty)
2920 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2921 try!(self.ibox(INDENT_UNIT));
2922 match input.ty.node {
2923 ast::TyKind::Infer if is_closure => try!(self.print_pat(&input.pat)),
2925 if let Some(eself) = input.to_self() {
2926 try!(self.print_explicit_self(&eself));
2928 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2929 ident.node.name == keywords::Invalid.name()
2934 try!(self.print_pat(&input.pat));
2935 try!(word(&mut self.s, ":"));
2936 try!(space(&mut self.s));
2938 try!(self.print_type(&input.ty));
2945 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2946 if let ast::FunctionRetTy::Default(..) = decl.output {
2950 try!(self.space_if_not_bol());
2951 try!(self.ibox(INDENT_UNIT));
2952 try!(self.word_space("->"));
2954 ast::FunctionRetTy::None(_) =>
2955 try!(self.word_nbsp("!")),
2956 ast::FunctionRetTy::Default(..) => unreachable!(),
2957 ast::FunctionRetTy::Ty(ref ty) =>
2958 try!(self.print_type(&ty))
2963 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2968 pub fn print_ty_fn(&mut self,
2970 unsafety: ast::Unsafety,
2972 name: Option<ast::Ident>,
2973 generics: &ast::Generics)
2975 try!(self.ibox(INDENT_UNIT));
2976 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2977 try!(word(&mut self.s, "for"));
2978 try!(self.print_generics(generics));
2980 let generics = ast::Generics {
2981 lifetimes: Vec::new(),
2982 ty_params: P::new(),
2983 where_clause: ast::WhereClause {
2984 id: ast::DUMMY_NODE_ID,
2985 predicates: Vec::new(),
2988 try!(self.print_fn(decl,
2990 ast::Constness::NotConst,
2994 &ast::Visibility::Inherited));
2998 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2999 next_pos: Option<BytePos>)
3001 let cm = match self.cm {
3005 if let Some(ref cmnt) = self.next_comment() {
3006 if (*cmnt).style != comments::Trailing { return Ok(()) }
3007 let span_line = cm.lookup_char_pos(span.hi);
3008 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3009 let mut next = (*cmnt).pos + BytePos(1);
3010 if let Some(p) = next_pos {
3013 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3014 span_line.line == comment_line.line {
3015 self.print_comment(cmnt)?;
3016 self.cur_cmnt_and_lit.cur_cmnt += 1;
3022 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3023 // If there aren't any remaining comments, then we need to manually
3024 // make sure there is a line break at the end.
3025 if self.next_comment().is_none() {
3026 try!(hardbreak(&mut self.s));
3029 match self.next_comment() {
3031 try!(self.print_comment(cmnt));
3032 self.cur_cmnt_and_lit.cur_cmnt += 1;
3040 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3041 opt_abi: Option<Abi>)
3044 Some(Abi::Rust) => Ok(()),
3046 try!(self.word_nbsp("extern"));
3047 self.word_nbsp(&abi.to_string())
3053 pub fn print_extern_opt_abi(&mut self,
3054 opt_abi: Option<Abi>) -> io::Result<()> {
3057 try!(self.word_nbsp("extern"));
3058 self.word_nbsp(&abi.to_string())
3064 pub fn print_fn_header_info(&mut self,
3065 unsafety: ast::Unsafety,
3066 constness: ast::Constness,
3068 vis: &ast::Visibility) -> io::Result<()> {
3069 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3072 ast::Constness::NotConst => {}
3073 ast::Constness::Const => try!(self.word_nbsp("const"))
3076 try!(self.print_unsafety(unsafety));
3078 if abi != Abi::Rust {
3079 try!(self.word_nbsp("extern"));
3080 try!(self.word_nbsp(&abi.to_string()));
3083 word(&mut self.s, "fn")
3086 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3088 ast::Unsafety::Normal => Ok(()),
3089 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3094 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3105 fn test_fun_to_string() {
3106 let abba_ident = token::str_to_ident("abba");
3108 let decl = ast::FnDecl {
3110 output: ast::FunctionRetTy::Default(codemap::DUMMY_SP),
3113 let generics = ast::Generics::default();
3114 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3115 ast::Constness::NotConst,
3116 abba_ident, &generics),
3121 fn test_variant_to_string() {
3122 let ident = token::str_to_ident("principal_skinner");
3124 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3127 // making this up as I go.... ?
3128 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3132 let varstr = variant_to_string(&var);
3133 assert_eq!(varstr, "principal_skinner");