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, BlockCheckMode, PatKind};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{self, CodeMap};
21 use syntax_pos::{self, BytePos};
23 use parse::token::{self, keywords, 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};
31 use tokenstream::{self, TokenTree};
34 use std::io::{self, Write, Read};
37 pub enum AnnNode<'a> {
38 NodeIdent(&'a ast::Ident),
39 NodeName(&'a ast::Name),
40 NodeBlock(&'a ast::Block),
41 NodeItem(&'a ast::Item),
42 NodeSubItem(ast::NodeId),
43 NodeExpr(&'a ast::Expr),
44 NodePat(&'a ast::Pat),
48 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
49 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
52 #[derive(Copy, Clone)]
55 impl PpAnn for NoAnn {}
57 #[derive(Copy, Clone)]
58 pub struct CurrentCommentAndLiteral {
63 pub struct State<'a> {
64 pub s: pp::Printer<'a>,
65 cm: Option<&'a CodeMap>,
66 comments: Option<Vec<comments::Comment> >,
67 literals: Option<Vec<comments::Literal> >,
68 cur_cmnt_and_lit: CurrentCommentAndLiteral,
69 boxes: Vec<pp::Breaks>,
73 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
74 static NO_ANN: NoAnn = NoAnn;
75 rust_printer_annotated(writer, &NO_ANN)
78 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
79 ann: &'a PpAnn) -> State<'a> {
81 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
85 cur_cmnt_and_lit: CurrentCommentAndLiteral {
94 pub const INDENT_UNIT: usize = 4;
96 pub const DEFAULT_COLUMNS: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
102 span_diagnostic: &errors::Handler,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm,
116 if is_expanded && !std_inject::no_std(krate) {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
122 // #![feature(prelude_import)]
123 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
124 let list = attr::mk_list_item(InternedString::new("feature"),
125 vec![prelude_import_meta]);
126 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
127 try!(s.print_attribute(&fake_attr));
130 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
131 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
132 try!(s.print_attribute(&fake_attr));
135 try!(s.print_mod(&krate.module, &krate.attrs));
136 try!(s.print_remaining_comments());
141 pub fn new_from_input(cm: &'a CodeMap,
142 span_diagnostic: &errors::Handler,
147 is_expanded: bool) -> State<'a> {
148 let (cmnts, lits) = comments::gather_comments_and_literals(
158 // If the code is post expansion, don't use the table of
159 // literals, since it doesn't correspond with the literals
160 // in the AST anymore.
161 if is_expanded { None } else { Some(lits) })
164 pub fn new(cm: &'a CodeMap,
167 comments: Option<Vec<comments::Comment>>,
168 literals: Option<Vec<comments::Literal>>) -> State<'a> {
170 s: pp::mk_printer(out, DEFAULT_COLUMNS),
174 cur_cmnt_and_lit: CurrentCommentAndLiteral {
184 pub fn to_string<F>(f: F) -> String where
185 F: FnOnce(&mut State) -> io::Result<()>,
187 let mut wr = Vec::new();
189 let mut printer = rust_printer(Box::new(&mut wr));
190 f(&mut printer).unwrap();
191 eof(&mut printer.s).unwrap();
193 String::from_utf8(wr).unwrap()
196 pub fn binop_to_string(op: BinOpToken) -> &'static str {
202 token::Percent => "%",
211 pub fn token_to_string(tok: &Token) -> String {
213 token::Eq => "=".to_string(),
214 token::Lt => "<".to_string(),
215 token::Le => "<=".to_string(),
216 token::EqEq => "==".to_string(),
217 token::Ne => "!=".to_string(),
218 token::Ge => ">=".to_string(),
219 token::Gt => ">".to_string(),
220 token::Not => "!".to_string(),
221 token::Tilde => "~".to_string(),
222 token::OrOr => "||".to_string(),
223 token::AndAnd => "&&".to_string(),
224 token::BinOp(op) => binop_to_string(op).to_string(),
225 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
227 /* Structural symbols */
228 token::At => "@".to_string(),
229 token::Dot => ".".to_string(),
230 token::DotDot => "..".to_string(),
231 token::DotDotDot => "...".to_string(),
232 token::Comma => ",".to_string(),
233 token::Semi => ";".to_string(),
234 token::Colon => ":".to_string(),
235 token::ModSep => "::".to_string(),
236 token::RArrow => "->".to_string(),
237 token::LArrow => "<-".to_string(),
238 token::FatArrow => "=>".to_string(),
239 token::OpenDelim(token::Paren) => "(".to_string(),
240 token::CloseDelim(token::Paren) => ")".to_string(),
241 token::OpenDelim(token::Bracket) => "[".to_string(),
242 token::CloseDelim(token::Bracket) => "]".to_string(),
243 token::OpenDelim(token::Brace) => "{".to_string(),
244 token::CloseDelim(token::Brace) => "}".to_string(),
245 token::OpenDelim(token::NoDelim) => " ".to_string(),
246 token::CloseDelim(token::NoDelim) => " ".to_string(),
247 token::Pound => "#".to_string(),
248 token::Dollar => "$".to_string(),
249 token::Question => "?".to_string(),
252 token::Literal(lit, suf) => {
253 let mut out = match lit {
254 token::Byte(b) => format!("b'{}'", b),
255 token::Char(c) => format!("'{}'", c),
256 token::Float(c) => c.to_string(),
257 token::Integer(c) => c.to_string(),
258 token::Str_(s) => format!("\"{}\"", s),
259 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
260 delim=repeat("#", n),
262 token::ByteStr(v) => format!("b\"{}\"", v),
263 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
264 delim=repeat("#", n),
268 if let Some(s) = suf {
269 out.push_str(&s.as_str())
275 /* Name components */
276 token::Ident(s) => s.to_string(),
277 token::Lifetime(s) => s.to_string(),
278 token::Underscore => "_".to_string(),
281 token::DocComment(s) => s.to_string(),
282 token::SubstNt(s) => format!("${}", s),
283 token::MatchNt(s, t) => format!("${}:{}", s, t),
284 token::Eof => "<eof>".to_string(),
285 token::Whitespace => " ".to_string(),
286 token::Comment => "/* */".to_string(),
287 token::Shebang(s) => format!("/* shebang: {}*/", s),
289 token::SpecialVarNt(var) => format!("${}", var.as_str()),
291 token::Interpolated(ref nt) => match *nt {
292 token::NtExpr(ref e) => expr_to_string(&e),
293 token::NtMeta(ref e) => meta_item_to_string(&e),
294 token::NtTy(ref e) => ty_to_string(&e),
295 token::NtPath(ref e) => path_to_string(&e),
296 token::NtItem(ref e) => item_to_string(&e),
297 token::NtBlock(ref e) => block_to_string(&e),
298 token::NtStmt(ref e) => stmt_to_string(&e),
299 token::NtPat(ref e) => pat_to_string(&e),
300 token::NtIdent(ref e) => ident_to_string(e.node),
301 token::NtTT(ref e) => tt_to_string(&e),
302 token::NtArm(ref e) => arm_to_string(&e),
303 token::NtImplItem(ref e) => impl_item_to_string(&e),
304 token::NtTraitItem(ref e) => trait_item_to_string(&e),
305 token::NtGenerics(ref e) => generics_to_string(&e),
306 token::NtWhereClause(ref e) => where_clause_to_string(&e),
307 token::NtArg(ref e) => arg_to_string(&e),
312 pub fn ty_to_string(ty: &ast::Ty) -> String {
313 to_string(|s| s.print_type(ty))
316 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
317 to_string(|s| s.print_bounds("", bounds))
320 pub fn pat_to_string(pat: &ast::Pat) -> String {
321 to_string(|s| s.print_pat(pat))
324 pub fn arm_to_string(arm: &ast::Arm) -> String {
325 to_string(|s| s.print_arm(arm))
328 pub fn expr_to_string(e: &ast::Expr) -> String {
329 to_string(|s| s.print_expr(e))
332 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
333 to_string(|s| s.print_lifetime(e))
336 pub fn tt_to_string(tt: &tokenstream::TokenTree) -> String {
337 to_string(|s| s.print_tt(tt))
340 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
341 to_string(|s| s.print_tts(tts))
344 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
345 to_string(|s| s.print_stmt(stmt))
348 pub fn attr_to_string(attr: &ast::Attribute) -> String {
349 to_string(|s| s.print_attribute(attr))
352 pub fn item_to_string(i: &ast::Item) -> String {
353 to_string(|s| s.print_item(i))
356 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
357 to_string(|s| s.print_impl_item(i))
360 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
361 to_string(|s| s.print_trait_item(i))
364 pub fn generics_to_string(generics: &ast::Generics) -> String {
365 to_string(|s| s.print_generics(generics))
368 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
369 to_string(|s| s.print_where_clause(i))
372 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
373 to_string(|s| s.print_fn_block_args(p))
376 pub fn path_to_string(p: &ast::Path) -> String {
377 to_string(|s| s.print_path(p, false, 0))
380 pub fn ident_to_string(id: ast::Ident) -> String {
381 to_string(|s| s.print_ident(id))
384 pub fn fun_to_string(decl: &ast::FnDecl,
385 unsafety: ast::Unsafety,
386 constness: ast::Constness,
388 generics: &ast::Generics)
392 try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
393 generics, &ast::Visibility::Inherited));
394 try!(s.end()); // Close the head box
395 s.end() // Close the outer box
399 pub fn block_to_string(blk: &ast::Block) -> String {
401 // containing cbox, will be closed by print-block at }
402 try!(s.cbox(INDENT_UNIT));
403 // head-ibox, will be closed by print-block after {
409 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
410 to_string(|s| s.print_meta_item(mi))
413 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
414 to_string(|s| s.print_attribute(attr))
417 pub fn lit_to_string(l: &ast::Lit) -> String {
418 to_string(|s| s.print_literal(l))
421 pub fn variant_to_string(var: &ast::Variant) -> String {
422 to_string(|s| s.print_variant(var))
425 pub fn arg_to_string(arg: &ast::Arg) -> String {
426 to_string(|s| s.print_arg(arg, false))
429 pub fn mac_to_string(arg: &ast::Mac) -> String {
430 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
433 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
435 ast::Visibility::Public => format!("pub {}", s),
436 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
437 ast::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, 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 try!(word(self.writer(), &attr.value_str().unwrap()));
756 hardbreak(self.writer())
758 match attr.node.style {
759 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
760 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
762 try!(self.print_meta_item(&attr.meta()));
763 word(self.writer(), "]")
767 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
768 try!(self.ibox(INDENT_UNIT));
770 ast::MetaItemKind::Word(ref name) => {
771 try!(word(self.writer(), &name));
773 ast::MetaItemKind::NameValue(ref name, ref value) => {
774 try!(self.word_space(&name[..]));
775 try!(self.word_space("="));
776 try!(self.print_literal(value));
778 ast::MetaItemKind::List(ref name, ref items) => {
779 try!(word(self.writer(), &name));
781 try!(self.commasep(Consistent,
783 |s, i| s.print_meta_item(&i)));
790 fn space_if_not_bol(&mut self) -> io::Result<()> {
791 if !self.is_bol() { try!(space(self.writer())); }
795 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
798 impl<'a> PrintState<'a> for State<'a> {
799 fn writer(&mut self) -> &mut pp::Printer<'a> {
803 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
807 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
811 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
812 &mut self.cur_cmnt_and_lit
815 fn literals(&self) -> &Option<Vec<comments::Literal>> {
821 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
822 self.boxes.push(pp::Breaks::Consistent);
823 pp::cbox(&mut self.s, u)
826 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
827 try!(word(&mut self.s, w));
831 pub fn head(&mut self, w: &str) -> io::Result<()> {
832 // outer-box is consistent
833 try!(self.cbox(INDENT_UNIT));
834 // head-box is inconsistent
835 try!(self.ibox(w.len() + 1));
836 // keyword that starts the head
838 try!(self.word_nbsp(w));
843 pub fn bopen(&mut self) -> io::Result<()> {
844 try!(word(&mut self.s, "{"));
845 self.end() // close the head-box
848 pub fn bclose_(&mut self, span: syntax_pos::Span,
849 indented: usize) -> io::Result<()> {
850 self.bclose_maybe_open(span, indented, true)
852 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
853 indented: usize, close_box: bool) -> io::Result<()> {
854 try!(self.maybe_print_comment(span.hi));
855 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
856 try!(word(&mut self.s, "}"));
858 try!(self.end()); // close the outer-box
862 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
863 self.bclose_(span, INDENT_UNIT)
866 pub fn in_cbox(&self) -> bool {
867 match self.boxes.last() {
868 Some(&last_box) => last_box == pp::Breaks::Consistent,
873 pub fn break_offset_if_not_bol(&mut self, n: usize,
874 off: isize) -> io::Result<()> {
876 break_offset(&mut self.s, n, off)
878 if off != 0 && self.s.last_token().is_hardbreak_tok() {
879 // We do something pretty sketchy here: tuck the nonzero
880 // offset-adjustment we were going to deposit along with the
881 // break into the previous hardbreak.
882 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
888 // Synthesizes a comment that was not textually present in the original source
890 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
891 try!(word(&mut self.s, "/*"));
892 try!(space(&mut self.s));
893 try!(word(&mut self.s, &text[..]));
894 try!(space(&mut self.s));
895 word(&mut self.s, "*/")
900 pub fn commasep_cmnt<T, F, G>(&mut self,
904 mut get_span: G) -> io::Result<()> where
905 F: FnMut(&mut State, &T) -> io::Result<()>,
906 G: FnMut(&T) -> syntax_pos::Span,
908 try!(self.rbox(0, b));
909 let len = elts.len();
912 try!(self.maybe_print_comment(get_span(elt).hi));
916 try!(word(&mut self.s, ","));
917 try!(self.maybe_print_trailing_comment(get_span(elt),
918 Some(get_span(&elts[i]).hi)));
919 try!(self.space_if_not_bol());
925 pub fn commasep_exprs(&mut self, b: Breaks,
926 exprs: &[P<ast::Expr>]) -> io::Result<()> {
927 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
930 pub fn print_mod(&mut self, _mod: &ast::Mod,
931 attrs: &[ast::Attribute]) -> io::Result<()> {
932 try!(self.print_inner_attributes(attrs));
933 for item in &_mod.items {
934 try!(self.print_item(&item));
939 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
940 attrs: &[ast::Attribute]) -> io::Result<()> {
941 try!(self.print_inner_attributes(attrs));
942 for item in &nmod.items {
943 try!(self.print_foreign_item(item));
948 pub fn print_opt_lifetime(&mut self,
949 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
950 if let Some(l) = *lifetime {
951 try!(self.print_lifetime(&l));
957 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
958 try!(self.maybe_print_comment(ty.span.lo));
961 ast::TyKind::Vec(ref ty) => {
962 try!(word(&mut self.s, "["));
963 try!(self.print_type(&ty));
964 try!(word(&mut self.s, "]"));
966 ast::TyKind::Ptr(ref mt) => {
967 try!(word(&mut self.s, "*"));
969 ast::Mutability::Mutable => try!(self.word_nbsp("mut")),
970 ast::Mutability::Immutable => try!(self.word_nbsp("const")),
972 try!(self.print_type(&mt.ty));
974 ast::TyKind::Rptr(ref lifetime, ref mt) => {
975 try!(word(&mut self.s, "&"));
976 try!(self.print_opt_lifetime(lifetime));
977 try!(self.print_mt(mt));
979 ast::TyKind::Never => {
980 try!(word(&mut self.s, "!"));
982 ast::TyKind::Tup(ref elts) => {
984 try!(self.commasep(Inconsistent, &elts[..],
985 |s, ty| s.print_type(&ty)));
987 try!(word(&mut self.s, ","));
991 ast::TyKind::Paren(ref typ) => {
993 try!(self.print_type(&typ));
996 ast::TyKind::BareFn(ref f) => {
997 let generics = ast::Generics {
998 lifetimes: f.lifetimes.clone(),
1000 where_clause: ast::WhereClause {
1001 id: ast::DUMMY_NODE_ID,
1002 predicates: Vec::new(),
1005 try!(self.print_ty_fn(f.abi,
1011 ast::TyKind::Path(None, ref path) => {
1012 try!(self.print_path(path, false, 0));
1014 ast::TyKind::Path(Some(ref qself), ref path) => {
1015 try!(self.print_qpath(path, qself, false))
1017 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1018 try!(self.print_type(&ty));
1019 try!(self.print_bounds("+", &bounds[..]));
1021 ast::TyKind::PolyTraitRef(ref bounds) => {
1022 try!(self.print_bounds("", &bounds[..]));
1024 ast::TyKind::ImplTrait(ref bounds) => {
1025 try!(self.print_bounds("impl ", &bounds[..]));
1027 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1028 try!(word(&mut self.s, "["));
1029 try!(self.print_type(&ty));
1030 try!(word(&mut self.s, "; "));
1031 try!(self.print_expr(&v));
1032 try!(word(&mut self.s, "]"));
1034 ast::TyKind::Typeof(ref e) => {
1035 try!(word(&mut self.s, "typeof("));
1036 try!(self.print_expr(&e));
1037 try!(word(&mut self.s, ")"));
1039 ast::TyKind::Infer => {
1040 try!(word(&mut self.s, "_"));
1042 ast::TyKind::ImplicitSelf => {
1043 try!(word(&mut self.s, "Self"));
1045 ast::TyKind::Mac(ref m) => {
1046 try!(self.print_mac(m, token::Paren));
1052 pub fn print_foreign_item(&mut self,
1053 item: &ast::ForeignItem) -> io::Result<()> {
1054 try!(self.hardbreak_if_not_bol());
1055 try!(self.maybe_print_comment(item.span.lo));
1056 try!(self.print_outer_attributes(&item.attrs));
1058 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1059 try!(self.head(""));
1060 try!(self.print_fn(decl, ast::Unsafety::Normal,
1061 ast::Constness::NotConst,
1062 Abi::Rust, Some(item.ident),
1063 generics, &item.vis));
1064 try!(self.end()); // end head-ibox
1065 try!(word(&mut self.s, ";"));
1066 self.end() // end the outer fn box
1068 ast::ForeignItemKind::Static(ref t, m) => {
1069 try!(self.head(&visibility_qualified(&item.vis, "static")));
1071 try!(self.word_space("mut"));
1073 try!(self.print_ident(item.ident));
1074 try!(self.word_space(":"));
1075 try!(self.print_type(&t));
1076 try!(word(&mut self.s, ";"));
1077 try!(self.end()); // end the head-ibox
1078 self.end() // end the outer cbox
1083 fn print_associated_const(&mut self,
1086 default: Option<&ast::Expr>,
1087 vis: &ast::Visibility)
1090 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1091 try!(self.word_space("const"));
1092 try!(self.print_ident(ident));
1093 try!(self.word_space(":"));
1094 try!(self.print_type(ty));
1095 if let Some(expr) = default {
1096 try!(space(&mut self.s));
1097 try!(self.word_space("="));
1098 try!(self.print_expr(expr));
1100 word(&mut self.s, ";")
1103 fn print_associated_type(&mut self,
1105 bounds: Option<&ast::TyParamBounds>,
1106 ty: Option<&ast::Ty>)
1108 try!(self.word_space("type"));
1109 try!(self.print_ident(ident));
1110 if let Some(bounds) = bounds {
1111 try!(self.print_bounds(":", bounds));
1113 if let Some(ty) = ty {
1114 try!(space(&mut self.s));
1115 try!(self.word_space("="));
1116 try!(self.print_type(ty));
1118 word(&mut self.s, ";")
1121 /// Pretty-print an item
1122 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1123 try!(self.hardbreak_if_not_bol());
1124 try!(self.maybe_print_comment(item.span.lo));
1125 try!(self.print_outer_attributes(&item.attrs));
1126 try!(self.ann.pre(self, NodeItem(item)));
1128 ast::ItemKind::ExternCrate(ref optional_path) => {
1129 try!(self.head(&visibility_qualified(&item.vis, "extern crate")));
1130 if let Some(p) = *optional_path {
1131 let val = p.as_str();
1132 if val.contains("-") {
1133 try!(self.print_string(&val, ast::StrStyle::Cooked));
1135 try!(self.print_name(p));
1137 try!(space(&mut self.s));
1138 try!(word(&mut self.s, "as"));
1139 try!(space(&mut self.s));
1141 try!(self.print_ident(item.ident));
1142 try!(word(&mut self.s, ";"));
1143 try!(self.end()); // end inner head-block
1144 try!(self.end()); // end outer head-block
1146 ast::ItemKind::Use(ref vp) => {
1147 try!(self.head(&visibility_qualified(&item.vis, "use")));
1148 try!(self.print_view_path(&vp));
1149 try!(word(&mut self.s, ";"));
1150 try!(self.end()); // end inner head-block
1151 try!(self.end()); // end outer head-block
1153 ast::ItemKind::Static(ref ty, m, ref expr) => {
1154 try!(self.head(&visibility_qualified(&item.vis, "static")));
1155 if m == ast::Mutability::Mutable {
1156 try!(self.word_space("mut"));
1158 try!(self.print_ident(item.ident));
1159 try!(self.word_space(":"));
1160 try!(self.print_type(&ty));
1161 try!(space(&mut self.s));
1162 try!(self.end()); // end the head-ibox
1164 try!(self.word_space("="));
1165 try!(self.print_expr(&expr));
1166 try!(word(&mut self.s, ";"));
1167 try!(self.end()); // end the outer cbox
1169 ast::ItemKind::Const(ref ty, ref expr) => {
1170 try!(self.head(&visibility_qualified(&item.vis, "const")));
1171 try!(self.print_ident(item.ident));
1172 try!(self.word_space(":"));
1173 try!(self.print_type(&ty));
1174 try!(space(&mut self.s));
1175 try!(self.end()); // end the head-ibox
1177 try!(self.word_space("="));
1178 try!(self.print_expr(&expr));
1179 try!(word(&mut self.s, ";"));
1180 try!(self.end()); // end the outer cbox
1182 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1183 try!(self.head(""));
1193 try!(word(&mut self.s, " "));
1194 try!(self.print_block_with_attrs(&body, &item.attrs));
1196 ast::ItemKind::Mod(ref _mod) => {
1197 try!(self.head(&visibility_qualified(&item.vis, "mod")));
1198 try!(self.print_ident(item.ident));
1201 try!(self.print_mod(_mod, &item.attrs));
1202 try!(self.bclose(item.span));
1204 ast::ItemKind::ForeignMod(ref nmod) => {
1205 try!(self.head("extern"));
1206 try!(self.word_nbsp(&nmod.abi.to_string()));
1208 try!(self.print_foreign_mod(nmod, &item.attrs));
1209 try!(self.bclose(item.span));
1211 ast::ItemKind::Ty(ref ty, ref params) => {
1212 try!(self.ibox(INDENT_UNIT));
1214 try!(self.word_nbsp(&visibility_qualified(&item.vis, "type")));
1215 try!(self.print_ident(item.ident));
1216 try!(self.print_generics(params));
1217 try!(self.end()); // end the inner ibox
1219 try!(self.print_where_clause(¶ms.where_clause));
1220 try!(space(&mut self.s));
1221 try!(self.word_space("="));
1222 try!(self.print_type(&ty));
1223 try!(word(&mut self.s, ";"));
1224 try!(self.end()); // end the outer ibox
1226 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1227 try!(self.print_enum_def(
1235 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1236 try!(self.head(&visibility_qualified(&item.vis, "struct")));
1237 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1240 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1241 try!(self.head(""));
1242 try!(self.print_visibility(&item.vis));
1243 try!(self.print_unsafety(unsafety));
1244 try!(self.word_nbsp("impl"));
1245 try!(self.print_trait_ref(trait_ref));
1246 try!(space(&mut self.s));
1247 try!(self.word_space("for"));
1248 try!(self.word_space(".."));
1250 try!(self.bclose(item.span));
1252 ast::ItemKind::Impl(unsafety,
1257 ref impl_items) => {
1258 try!(self.head(""));
1259 try!(self.print_visibility(&item.vis));
1260 try!(self.print_unsafety(unsafety));
1261 try!(self.word_nbsp("impl"));
1263 if generics.is_parameterized() {
1264 try!(self.print_generics(generics));
1265 try!(space(&mut self.s));
1269 ast::ImplPolarity::Negative => {
1270 try!(word(&mut self.s, "!"));
1275 if let Some(ref t) = *opt_trait {
1276 try!(self.print_trait_ref(t));
1277 try!(space(&mut self.s));
1278 try!(self.word_space("for"));
1281 try!(self.print_type(&ty));
1282 try!(self.print_where_clause(&generics.where_clause));
1284 try!(space(&mut self.s));
1286 try!(self.print_inner_attributes(&item.attrs));
1287 for impl_item in impl_items {
1288 try!(self.print_impl_item(impl_item));
1290 try!(self.bclose(item.span));
1292 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1293 try!(self.head(""));
1294 try!(self.print_visibility(&item.vis));
1295 try!(self.print_unsafety(unsafety));
1296 try!(self.word_nbsp("trait"));
1297 try!(self.print_ident(item.ident));
1298 try!(self.print_generics(generics));
1299 let mut real_bounds = Vec::with_capacity(bounds.len());
1300 for b in bounds.iter() {
1301 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1302 try!(space(&mut self.s));
1303 try!(self.word_space("for ?"));
1304 try!(self.print_trait_ref(&ptr.trait_ref));
1306 real_bounds.push(b.clone());
1309 try!(self.print_bounds(":", &real_bounds[..]));
1310 try!(self.print_where_clause(&generics.where_clause));
1311 try!(word(&mut self.s, " "));
1313 for trait_item in trait_items {
1314 try!(self.print_trait_item(trait_item));
1316 try!(self.bclose(item.span));
1318 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1319 try!(self.print_visibility(&item.vis));
1320 try!(self.print_path(&node.path, false, 0));
1321 try!(word(&mut self.s, "! "));
1322 try!(self.print_ident(item.ident));
1323 try!(self.cbox(INDENT_UNIT));
1325 try!(self.print_tts(&node.tts[..]));
1326 try!(self.pclose());
1327 try!(word(&mut self.s, ";"));
1331 self.ann.post(self, NodeItem(item))
1334 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1335 self.print_path(&t.path, false, 0)
1338 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1339 if !lifetimes.is_empty() {
1340 try!(word(&mut self.s, "for<"));
1341 let mut comma = false;
1342 for lifetime_def in lifetimes {
1344 try!(self.word_space(","))
1346 try!(self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds));
1349 try!(word(&mut self.s, ">"));
1354 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1355 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1356 self.print_trait_ref(&t.trait_ref)
1359 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1360 generics: &ast::Generics, ident: ast::Ident,
1361 span: syntax_pos::Span,
1362 visibility: &ast::Visibility) -> io::Result<()> {
1363 try!(self.head(&visibility_qualified(visibility, "enum")));
1364 try!(self.print_ident(ident));
1365 try!(self.print_generics(generics));
1366 try!(self.print_where_clause(&generics.where_clause));
1367 try!(space(&mut self.s));
1368 self.print_variants(&enum_definition.variants, span)
1371 pub fn print_variants(&mut self,
1372 variants: &[ast::Variant],
1373 span: syntax_pos::Span) -> io::Result<()> {
1376 try!(self.space_if_not_bol());
1377 try!(self.maybe_print_comment(v.span.lo));
1378 try!(self.print_outer_attributes(&v.node.attrs));
1379 try!(self.ibox(INDENT_UNIT));
1380 try!(self.print_variant(v));
1381 try!(word(&mut self.s, ","));
1383 try!(self.maybe_print_trailing_comment(v.span, None));
1388 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1390 ast::Visibility::Public => self.word_nbsp("pub"),
1391 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1392 ast::Visibility::Restricted { ref path, .. } =>
1393 self.word_nbsp(&format!("pub({})", path)),
1394 ast::Visibility::Inherited => Ok(())
1398 pub fn print_struct(&mut self,
1399 struct_def: &ast::VariantData,
1400 generics: &ast::Generics,
1402 span: syntax_pos::Span,
1403 print_finalizer: bool) -> io::Result<()> {
1404 try!(self.print_ident(ident));
1405 try!(self.print_generics(generics));
1406 if !struct_def.is_struct() {
1407 if struct_def.is_tuple() {
1410 Inconsistent, struct_def.fields(),
1412 try!(s.maybe_print_comment(field.span.lo));
1413 try!(s.print_outer_attributes(&field.attrs));
1414 try!(s.print_visibility(&field.vis));
1415 s.print_type(&field.ty)
1418 try!(self.pclose());
1420 try!(self.print_where_clause(&generics.where_clause));
1421 if print_finalizer {
1422 try!(word(&mut self.s, ";"));
1425 self.end() // close the outer-box
1427 try!(self.print_where_clause(&generics.where_clause));
1430 try!(self.hardbreak_if_not_bol());
1432 for field in struct_def.fields() {
1433 try!(self.hardbreak_if_not_bol());
1434 try!(self.maybe_print_comment(field.span.lo));
1435 try!(self.print_outer_attributes(&field.attrs));
1436 try!(self.print_visibility(&field.vis));
1437 try!(self.print_ident(field.ident.unwrap()));
1438 try!(self.word_nbsp(":"));
1439 try!(self.print_type(&field.ty));
1440 try!(word(&mut self.s, ","));
1447 /// This doesn't deserve to be called "pretty" printing, but it should be
1448 /// meaning-preserving. A quick hack that might help would be to look at the
1449 /// spans embedded in the TTs to decide where to put spaces and newlines.
1450 /// But it'd be better to parse these according to the grammar of the
1451 /// appropriate macro, transcribe back into the grammar we just parsed from,
1452 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1453 /// expression arguments as expressions). It can be done! I think.
1454 pub fn print_tt(&mut self, tt: &tokenstream::TokenTree) -> io::Result<()> {
1456 TokenTree::Token(_, ref tk) => {
1457 try!(word(&mut self.s, &token_to_string(tk)));
1459 parse::token::DocComment(..) => {
1460 hardbreak(&mut self.s)
1465 TokenTree::Delimited(_, ref delimed) => {
1466 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1467 try!(space(&mut self.s));
1468 try!(self.print_tts(&delimed.tts));
1469 try!(space(&mut self.s));
1470 word(&mut self.s, &token_to_string(&delimed.close_token()))
1472 TokenTree::Sequence(_, ref seq) => {
1473 try!(word(&mut self.s, "$("));
1474 for tt_elt in &seq.tts {
1475 try!(self.print_tt(tt_elt));
1477 try!(word(&mut self.s, ")"));
1478 if let Some(ref tk) = seq.separator {
1479 try!(word(&mut self.s, &token_to_string(tk)));
1482 tokenstream::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1483 tokenstream::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1489 pub fn print_tts(&mut self, tts: &[tokenstream::TokenTree]) -> io::Result<()> {
1491 for (i, tt) in tts.iter().enumerate() {
1493 try!(space(&mut self.s));
1495 try!(self.print_tt(tt));
1500 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1501 try!(self.head(""));
1502 let generics = ast::Generics::default();
1503 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1504 match v.node.disr_expr {
1506 try!(space(&mut self.s));
1507 try!(self.word_space("="));
1514 pub fn print_method_sig(&mut self,
1517 vis: &ast::Visibility)
1519 self.print_fn(&m.decl,
1528 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1530 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1531 try!(self.hardbreak_if_not_bol());
1532 try!(self.maybe_print_comment(ti.span.lo));
1533 try!(self.print_outer_attributes(&ti.attrs));
1535 ast::TraitItemKind::Const(ref ty, ref default) => {
1536 try!(self.print_associated_const(ti.ident, &ty,
1537 default.as_ref().map(|expr| &**expr),
1538 &ast::Visibility::Inherited));
1540 ast::TraitItemKind::Method(ref sig, ref body) => {
1542 try!(self.head(""));
1544 try!(self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited));
1545 if let Some(ref body) = *body {
1547 try!(self.print_block_with_attrs(body, &ti.attrs));
1549 try!(word(&mut self.s, ";"));
1552 ast::TraitItemKind::Type(ref bounds, ref default) => {
1553 try!(self.print_associated_type(ti.ident, Some(bounds),
1554 default.as_ref().map(|ty| &**ty)));
1556 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1557 // code copied from ItemKind::Mac:
1558 self.print_path(&node.path, false, 0)?;
1559 word(&mut self.s, "! ")?;
1560 self.cbox(INDENT_UNIT)?;
1562 self.print_tts(&node.tts[..])?;
1564 word(&mut self.s, ";")?;
1568 self.ann.post(self, NodeSubItem(ti.id))
1571 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1572 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1573 try!(self.hardbreak_if_not_bol());
1574 try!(self.maybe_print_comment(ii.span.lo));
1575 try!(self.print_outer_attributes(&ii.attrs));
1576 if let ast::Defaultness::Default = ii.defaultness {
1577 try!(self.word_nbsp("default"));
1580 ast::ImplItemKind::Const(ref ty, ref expr) => {
1581 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis));
1583 ast::ImplItemKind::Method(ref sig, ref body) => {
1584 try!(self.head(""));
1585 try!(self.print_method_sig(ii.ident, sig, &ii.vis));
1587 try!(self.print_block_with_attrs(body, &ii.attrs));
1589 ast::ImplItemKind::Type(ref ty) => {
1590 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1592 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1593 // code copied from ItemKind::Mac:
1594 try!(self.print_path(&node.path, false, 0));
1595 try!(word(&mut self.s, "! "));
1596 try!(self.cbox(INDENT_UNIT));
1598 try!(self.print_tts(&node.tts[..]));
1599 try!(self.pclose());
1600 try!(word(&mut self.s, ";"));
1604 self.ann.post(self, NodeSubItem(ii.id))
1607 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1608 try!(self.maybe_print_comment(st.span.lo));
1610 ast::StmtKind::Local(ref loc) => {
1611 try!(self.print_outer_attributes(&loc.attrs));
1612 try!(self.space_if_not_bol());
1613 try!(self.ibox(INDENT_UNIT));
1614 try!(self.word_nbsp("let"));
1616 try!(self.ibox(INDENT_UNIT));
1617 try!(self.print_local_decl(&loc));
1619 if let Some(ref init) = loc.init {
1621 try!(self.word_space("="));
1622 try!(self.print_expr(&init));
1624 try!(word(&mut self.s, ";"));
1627 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1628 ast::StmtKind::Expr(ref expr) => {
1629 try!(self.space_if_not_bol());
1630 try!(self.print_expr_outer_attr_style(&expr, false));
1631 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1632 try!(word(&mut self.s, ";"));
1635 ast::StmtKind::Semi(ref expr) => {
1636 try!(self.space_if_not_bol());
1637 try!(self.print_expr_outer_attr_style(&expr, false));
1638 try!(word(&mut self.s, ";"));
1640 ast::StmtKind::Mac(ref mac) => {
1641 let (ref mac, style, ref attrs) = **mac;
1642 try!(self.space_if_not_bol());
1643 try!(self.print_outer_attributes(&attrs));
1644 let delim = match style {
1645 ast::MacStmtStyle::Braces => token::Brace,
1648 try!(self.print_mac(&mac, delim));
1649 if style == ast::MacStmtStyle::Semicolon {
1650 try!(word(&mut self.s, ";"));
1654 self.maybe_print_trailing_comment(st.span, None)
1657 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1658 self.print_block_with_attrs(blk, &[])
1661 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1662 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1665 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1666 attrs: &[ast::Attribute])
1668 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1671 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1672 indented: usize) -> io::Result<()> {
1673 self.print_block_maybe_unclosed(blk, indented, &[], false)
1676 pub fn print_block_with_attrs(&mut self,
1678 attrs: &[ast::Attribute]) -> io::Result<()> {
1679 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1682 pub fn print_block_maybe_unclosed(&mut self,
1685 attrs: &[ast::Attribute],
1686 close_box: bool) -> io::Result<()> {
1688 BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")),
1689 BlockCheckMode::Default => ()
1691 try!(self.maybe_print_comment(blk.span.lo));
1692 try!(self.ann.pre(self, NodeBlock(blk)));
1695 try!(self.print_inner_attributes(attrs));
1697 for (i, st) in blk.stmts.iter().enumerate() {
1699 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1700 try!(self.space_if_not_bol());
1701 try!(self.print_expr_outer_attr_style(&expr, false));
1702 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1704 _ => try!(self.print_stmt(st)),
1708 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1709 self.ann.post(self, NodeBlock(blk))
1712 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1716 // "another else-if"
1717 ast::ExprKind::If(ref i, ref then, ref e) => {
1718 try!(self.cbox(INDENT_UNIT - 1));
1720 try!(word(&mut self.s, " else if "));
1721 try!(self.print_expr(&i));
1722 try!(space(&mut self.s));
1723 try!(self.print_block(&then));
1724 self.print_else(e.as_ref().map(|e| &**e))
1726 // "another else-if-let"
1727 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1728 try!(self.cbox(INDENT_UNIT - 1));
1730 try!(word(&mut self.s, " else if let "));
1731 try!(self.print_pat(&pat));
1732 try!(space(&mut self.s));
1733 try!(self.word_space("="));
1734 try!(self.print_expr(&expr));
1735 try!(space(&mut self.s));
1736 try!(self.print_block(&then));
1737 self.print_else(e.as_ref().map(|e| &**e))
1740 ast::ExprKind::Block(ref b) => {
1741 try!(self.cbox(INDENT_UNIT - 1));
1743 try!(word(&mut self.s, " else "));
1744 self.print_block(&b)
1746 // BLEAH, constraints would be great here
1748 panic!("print_if saw if with weird alternative");
1756 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1757 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1758 try!(self.head("if"));
1759 try!(self.print_expr(test));
1760 try!(space(&mut self.s));
1761 try!(self.print_block(blk));
1762 self.print_else(elseopt)
1765 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1766 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1767 try!(self.head("if let"));
1768 try!(self.print_pat(pat));
1769 try!(space(&mut self.s));
1770 try!(self.word_space("="));
1771 try!(self.print_expr(expr));
1772 try!(space(&mut self.s));
1773 try!(self.print_block(blk));
1774 self.print_else(elseopt)
1777 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1779 try!(self.print_path(&m.node.path, false, 0));
1780 try!(word(&mut self.s, "!"));
1782 token::Paren => try!(self.popen()),
1783 token::Bracket => try!(word(&mut self.s, "[")),
1785 try!(self.head(""));
1788 token::NoDelim => {}
1790 try!(self.print_tts(&m.node.tts));
1792 token::Paren => self.pclose(),
1793 token::Bracket => word(&mut self.s, "]"),
1794 token::Brace => self.bclose(m.span),
1795 token::NoDelim => Ok(()),
1800 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1802 try!(self.commasep_exprs(Inconsistent, args));
1806 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1807 binop: ast::BinOp) -> bool {
1808 match sub_expr.node {
1809 ast::ExprKind::Binary(ref sub_op, _, _) => {
1810 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1811 AssocOp::from_ast_binop(binop.node).precedence() {
1821 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1822 let needs_par = needs_parentheses(expr);
1826 try!(self.print_expr(expr));
1828 try!(self.pclose());
1833 fn print_expr_in_place(&mut self,
1835 expr: &ast::Expr) -> io::Result<()> {
1836 try!(self.print_expr_maybe_paren(place));
1837 try!(space(&mut self.s));
1838 try!(self.word_space("<-"));
1839 self.print_expr_maybe_paren(expr)
1842 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1843 attrs: &[Attribute]) -> io::Result<()> {
1844 try!(self.ibox(INDENT_UNIT));
1845 try!(word(&mut self.s, "["));
1846 try!(self.print_inner_attributes_inline(attrs));
1847 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1848 try!(word(&mut self.s, "]"));
1852 fn print_expr_repeat(&mut self,
1853 element: &ast::Expr,
1855 attrs: &[Attribute]) -> io::Result<()> {
1856 try!(self.ibox(INDENT_UNIT));
1857 try!(word(&mut self.s, "["));
1858 try!(self.print_inner_attributes_inline(attrs));
1859 try!(self.print_expr(element));
1860 try!(self.word_space(";"));
1861 try!(self.print_expr(count));
1862 try!(word(&mut self.s, "]"));
1866 fn print_expr_struct(&mut self,
1868 fields: &[ast::Field],
1869 wth: &Option<P<ast::Expr>>,
1870 attrs: &[Attribute]) -> io::Result<()> {
1871 try!(self.print_path(path, true, 0));
1872 try!(word(&mut self.s, "{"));
1873 try!(self.print_inner_attributes_inline(attrs));
1874 try!(self.commasep_cmnt(
1878 try!(s.ibox(INDENT_UNIT));
1879 try!(s.print_ident(field.ident.node));
1880 try!(s.word_space(":"));
1881 try!(s.print_expr(&field.expr));
1887 try!(self.ibox(INDENT_UNIT));
1888 if !fields.is_empty() {
1889 try!(word(&mut self.s, ","));
1890 try!(space(&mut self.s));
1892 try!(word(&mut self.s, ".."));
1893 try!(self.print_expr(&expr));
1896 _ => if !fields.is_empty() {
1897 try!(word(&mut self.s, ","))
1900 try!(word(&mut self.s, "}"));
1904 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1905 attrs: &[Attribute]) -> io::Result<()> {
1907 try!(self.print_inner_attributes_inline(attrs));
1908 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1909 if exprs.len() == 1 {
1910 try!(word(&mut self.s, ","));
1915 fn print_expr_call(&mut self,
1917 args: &[P<ast::Expr>]) -> io::Result<()> {
1918 try!(self.print_expr_maybe_paren(func));
1919 self.print_call_post(args)
1922 fn print_expr_method_call(&mut self,
1923 ident: ast::SpannedIdent,
1925 args: &[P<ast::Expr>]) -> io::Result<()> {
1926 let base_args = &args[1..];
1927 try!(self.print_expr(&args[0]));
1928 try!(word(&mut self.s, "."));
1929 try!(self.print_ident(ident.node));
1930 if !tys.is_empty() {
1931 try!(word(&mut self.s, "::<"));
1932 try!(self.commasep(Inconsistent, tys,
1933 |s, ty| s.print_type(&ty)));
1934 try!(word(&mut self.s, ">"));
1936 self.print_call_post(base_args)
1939 fn print_expr_binary(&mut self,
1942 rhs: &ast::Expr) -> io::Result<()> {
1943 if self.check_expr_bin_needs_paren(lhs, op) {
1944 try!(self.print_expr_maybe_paren(lhs));
1946 try!(self.print_expr(lhs));
1948 try!(space(&mut self.s));
1949 try!(self.word_space(op.node.to_string()));
1950 if self.check_expr_bin_needs_paren(rhs, op) {
1951 self.print_expr_maybe_paren(rhs)
1953 self.print_expr(rhs)
1957 fn print_expr_unary(&mut self,
1959 expr: &ast::Expr) -> io::Result<()> {
1960 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1961 self.print_expr_maybe_paren(expr)
1964 fn print_expr_addr_of(&mut self,
1965 mutability: ast::Mutability,
1966 expr: &ast::Expr) -> io::Result<()> {
1967 try!(word(&mut self.s, "&"));
1968 try!(self.print_mutability(mutability));
1969 self.print_expr_maybe_paren(expr)
1972 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1973 self.print_expr_outer_attr_style(expr, true)
1976 fn print_expr_outer_attr_style(&mut self,
1978 is_inline: bool) -> io::Result<()> {
1979 try!(self.maybe_print_comment(expr.span.lo));
1981 let attrs = &expr.attrs;
1983 try!(self.print_outer_attributes_inline(attrs));
1985 try!(self.print_outer_attributes(attrs));
1988 try!(self.ibox(INDENT_UNIT));
1989 try!(self.ann.pre(self, NodeExpr(expr)));
1991 ast::ExprKind::Box(ref expr) => {
1992 try!(self.word_space("box"));
1993 try!(self.print_expr(expr));
1995 ast::ExprKind::InPlace(ref place, ref expr) => {
1996 try!(self.print_expr_in_place(place, expr));
1998 ast::ExprKind::Vec(ref exprs) => {
1999 try!(self.print_expr_vec(&exprs[..], attrs));
2001 ast::ExprKind::Repeat(ref element, ref count) => {
2002 try!(self.print_expr_repeat(&element, &count, attrs));
2004 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2005 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
2007 ast::ExprKind::Tup(ref exprs) => {
2008 try!(self.print_expr_tup(&exprs[..], attrs));
2010 ast::ExprKind::Call(ref func, ref args) => {
2011 try!(self.print_expr_call(&func, &args[..]));
2013 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2014 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
2016 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2017 try!(self.print_expr_binary(op, &lhs, &rhs));
2019 ast::ExprKind::Unary(op, ref expr) => {
2020 try!(self.print_expr_unary(op, &expr));
2022 ast::ExprKind::AddrOf(m, ref expr) => {
2023 try!(self.print_expr_addr_of(m, &expr));
2025 ast::ExprKind::Lit(ref lit) => {
2026 try!(self.print_literal(&lit));
2028 ast::ExprKind::Cast(ref expr, ref ty) => {
2029 if let ast::ExprKind::Cast(..) = expr.node {
2030 try!(self.print_expr(&expr));
2032 try!(self.print_expr_maybe_paren(&expr));
2034 try!(space(&mut self.s));
2035 try!(self.word_space("as"));
2036 try!(self.print_type(&ty));
2038 ast::ExprKind::Type(ref expr, ref ty) => {
2039 try!(self.print_expr(&expr));
2040 try!(self.word_space(":"));
2041 try!(self.print_type(&ty));
2043 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2044 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
2046 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2047 try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e)));
2049 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2050 if let Some(ident) = opt_ident {
2051 try!(self.print_ident(ident.node));
2052 try!(self.word_space(":"));
2054 try!(self.head("while"));
2055 try!(self.print_expr(&test));
2056 try!(space(&mut self.s));
2057 try!(self.print_block_with_attrs(&blk, attrs));
2059 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2060 if let Some(ident) = opt_ident {
2061 try!(self.print_ident(ident.node));
2062 try!(self.word_space(":"));
2064 try!(self.head("while let"));
2065 try!(self.print_pat(&pat));
2066 try!(space(&mut self.s));
2067 try!(self.word_space("="));
2068 try!(self.print_expr(&expr));
2069 try!(space(&mut self.s));
2070 try!(self.print_block_with_attrs(&blk, attrs));
2072 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2073 if let Some(ident) = opt_ident {
2074 try!(self.print_ident(ident.node));
2075 try!(self.word_space(":"));
2077 try!(self.head("for"));
2078 try!(self.print_pat(&pat));
2079 try!(space(&mut self.s));
2080 try!(self.word_space("in"));
2081 try!(self.print_expr(&iter));
2082 try!(space(&mut self.s));
2083 try!(self.print_block_with_attrs(&blk, attrs));
2085 ast::ExprKind::Loop(ref blk, opt_ident) => {
2086 if let Some(ident) = opt_ident {
2087 try!(self.print_ident(ident.node));
2088 try!(self.word_space(":"));
2090 try!(self.head("loop"));
2091 try!(space(&mut self.s));
2092 try!(self.print_block_with_attrs(&blk, attrs));
2094 ast::ExprKind::Match(ref expr, ref arms) => {
2095 try!(self.cbox(INDENT_UNIT));
2097 try!(self.word_nbsp("match"));
2098 try!(self.print_expr(&expr));
2099 try!(space(&mut self.s));
2101 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2103 try!(self.print_arm(arm));
2105 try!(self.bclose_(expr.span, INDENT_UNIT));
2107 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2108 try!(self.print_capture_clause(capture_clause));
2110 try!(self.print_fn_block_args(&decl));
2111 try!(space(&mut self.s));
2113 let default_return = match decl.output {
2114 ast::FunctionRetTy::Default(..) => true,
2118 match body.stmts.last().map(|stmt| &stmt.node) {
2119 Some(&ast::StmtKind::Expr(ref i_expr)) if default_return &&
2120 body.stmts.len() == 1 => {
2121 // we extract the block, so as not to create another set of boxes
2122 if let ast::ExprKind::Block(ref blk) = i_expr.node {
2123 try!(self.print_block_unclosed_with_attrs(&blk, &i_expr.attrs));
2125 // this is a bare expression
2126 try!(self.print_expr(&i_expr));
2127 try!(self.end()); // need to close a box
2130 _ => try!(self.print_block_unclosed(&body)),
2133 // a box will be closed by print_expr, but we didn't want an overall
2134 // wrapper so we closed the corresponding opening. so create an
2135 // empty box to satisfy the close.
2138 ast::ExprKind::Block(ref blk) => {
2139 // containing cbox, will be closed by print-block at }
2140 try!(self.cbox(INDENT_UNIT));
2141 // head-box, will be closed by print-block after {
2143 try!(self.print_block_with_attrs(&blk, attrs));
2145 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2146 try!(self.print_expr(&lhs));
2147 try!(space(&mut self.s));
2148 try!(self.word_space("="));
2149 try!(self.print_expr(&rhs));
2151 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2152 try!(self.print_expr(&lhs));
2153 try!(space(&mut self.s));
2154 try!(word(&mut self.s, op.node.to_string()));
2155 try!(self.word_space("="));
2156 try!(self.print_expr(&rhs));
2158 ast::ExprKind::Field(ref expr, id) => {
2159 try!(self.print_expr(&expr));
2160 try!(word(&mut self.s, "."));
2161 try!(self.print_ident(id.node));
2163 ast::ExprKind::TupField(ref expr, id) => {
2164 try!(self.print_expr(&expr));
2165 try!(word(&mut self.s, "."));
2166 try!(self.print_usize(id.node));
2168 ast::ExprKind::Index(ref expr, ref index) => {
2169 try!(self.print_expr(&expr));
2170 try!(word(&mut self.s, "["));
2171 try!(self.print_expr(&index));
2172 try!(word(&mut self.s, "]"));
2174 ast::ExprKind::Range(ref start, ref end, limits) => {
2175 if let &Some(ref e) = start {
2176 try!(self.print_expr(&e));
2178 if limits == ast::RangeLimits::HalfOpen {
2179 try!(word(&mut self.s, ".."));
2181 try!(word(&mut self.s, "..."));
2183 if let &Some(ref e) = end {
2184 try!(self.print_expr(&e));
2187 ast::ExprKind::Path(None, ref path) => {
2188 try!(self.print_path(path, true, 0))
2190 ast::ExprKind::Path(Some(ref qself), ref path) => {
2191 try!(self.print_qpath(path, qself, true))
2193 ast::ExprKind::Break(opt_ident) => {
2194 try!(word(&mut self.s, "break"));
2195 try!(space(&mut self.s));
2196 if let Some(ident) = opt_ident {
2197 try!(self.print_ident(ident.node));
2198 try!(space(&mut self.s));
2201 ast::ExprKind::Continue(opt_ident) => {
2202 try!(word(&mut self.s, "continue"));
2203 try!(space(&mut self.s));
2204 if let Some(ident) = opt_ident {
2205 try!(self.print_ident(ident.node));
2206 try!(space(&mut self.s))
2209 ast::ExprKind::Ret(ref result) => {
2210 try!(word(&mut self.s, "return"));
2213 try!(word(&mut self.s, " "));
2214 try!(self.print_expr(&expr));
2219 ast::ExprKind::InlineAsm(ref a) => {
2220 try!(word(&mut self.s, "asm!"));
2222 try!(self.print_string(&a.asm, a.asm_str_style));
2223 try!(self.word_space(":"));
2225 try!(self.commasep(Inconsistent, &a.outputs,
2227 let mut ch = out.constraint.chars();
2229 Some('=') if out.is_rw => {
2230 try!(s.print_string(&format!("+{}", ch.as_str()),
2231 ast::StrStyle::Cooked))
2233 _ => try!(s.print_string(&out.constraint,
2234 ast::StrStyle::Cooked))
2237 try!(s.print_expr(&out.expr));
2241 try!(space(&mut self.s));
2242 try!(self.word_space(":"));
2244 try!(self.commasep(Inconsistent, &a.inputs,
2245 |s, &(ref co, ref o)| {
2246 try!(s.print_string(&co, ast::StrStyle::Cooked));
2248 try!(s.print_expr(&o));
2252 try!(space(&mut self.s));
2253 try!(self.word_space(":"));
2255 try!(self.commasep(Inconsistent, &a.clobbers,
2257 try!(s.print_string(&co, ast::StrStyle::Cooked));
2261 let mut options = vec!();
2263 options.push("volatile");
2266 options.push("alignstack");
2268 if a.dialect == ast::AsmDialect::Intel {
2269 options.push("intel");
2272 if !options.is_empty() {
2273 try!(space(&mut self.s));
2274 try!(self.word_space(":"));
2275 try!(self.commasep(Inconsistent, &options,
2277 try!(s.print_string(co, ast::StrStyle::Cooked));
2282 try!(self.pclose());
2284 ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2285 ast::ExprKind::Paren(ref e) => {
2287 try!(self.print_inner_attributes_inline(attrs));
2288 try!(self.print_expr(&e));
2289 try!(self.pclose());
2291 ast::ExprKind::Try(ref e) => {
2292 try!(self.print_expr(e));
2293 try!(word(&mut self.s, "?"))
2296 try!(self.ann.post(self, NodeExpr(expr)));
2300 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2301 try!(self.print_pat(&loc.pat));
2302 if let Some(ref ty) = loc.ty {
2303 try!(self.word_space(":"));
2304 try!(self.print_type(&ty));
2309 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2310 try!(word(&mut self.s, &ident.name.as_str()));
2311 self.ann.post(self, NodeIdent(&ident))
2314 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2315 word(&mut self.s, &i.to_string())
2318 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2319 try!(word(&mut self.s, &name.as_str()));
2320 self.ann.post(self, NodeName(&name))
2323 pub fn print_for_decl(&mut self, loc: &ast::Local,
2324 coll: &ast::Expr) -> io::Result<()> {
2325 try!(self.print_local_decl(loc));
2326 try!(space(&mut self.s));
2327 try!(self.word_space("in"));
2328 self.print_expr(coll)
2331 fn print_path(&mut self,
2333 colons_before_params: bool,
2337 try!(self.maybe_print_comment(path.span.lo));
2339 let mut first = !path.global;
2340 for segment in &path.segments[..path.segments.len()-depth] {
2344 try!(word(&mut self.s, "::"))
2347 try!(self.print_ident(segment.identifier));
2349 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2355 fn print_qpath(&mut self,
2358 colons_before_params: bool)
2361 try!(word(&mut self.s, "<"));
2362 try!(self.print_type(&qself.ty));
2363 if qself.position > 0 {
2364 try!(space(&mut self.s));
2365 try!(self.word_space("as"));
2366 let depth = path.segments.len() - qself.position;
2367 try!(self.print_path(&path, false, depth));
2369 try!(word(&mut self.s, ">"));
2370 try!(word(&mut self.s, "::"));
2371 let item_segment = path.segments.last().unwrap();
2372 try!(self.print_ident(item_segment.identifier));
2373 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2376 fn print_path_parameters(&mut self,
2377 parameters: &ast::PathParameters,
2378 colons_before_params: bool)
2381 if parameters.is_empty() {
2385 if colons_before_params {
2386 try!(word(&mut self.s, "::"))
2390 ast::PathParameters::AngleBracketed(ref data) => {
2391 try!(word(&mut self.s, "<"));
2393 let mut comma = false;
2394 for lifetime in &data.lifetimes {
2396 try!(self.word_space(","))
2398 try!(self.print_lifetime(lifetime));
2402 if !data.types.is_empty() {
2404 try!(self.word_space(","))
2409 |s, ty| s.print_type(&ty)));
2413 for binding in data.bindings.iter() {
2415 try!(self.word_space(","))
2417 try!(self.print_ident(binding.ident));
2418 try!(space(&mut self.s));
2419 try!(self.word_space("="));
2420 try!(self.print_type(&binding.ty));
2424 try!(word(&mut self.s, ">"))
2427 ast::PathParameters::Parenthesized(ref data) => {
2428 try!(word(&mut self.s, "("));
2432 |s, ty| s.print_type(&ty)));
2433 try!(word(&mut self.s, ")"));
2438 try!(self.space_if_not_bol());
2439 try!(self.word_space("->"));
2440 try!(self.print_type(&ty));
2449 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2450 try!(self.maybe_print_comment(pat.span.lo));
2451 try!(self.ann.pre(self, NodePat(pat)));
2452 /* Pat isn't normalized, but the beauty of it
2453 is that it doesn't matter */
2455 PatKind::Wild => try!(word(&mut self.s, "_")),
2456 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2457 match binding_mode {
2458 ast::BindingMode::ByRef(mutbl) => {
2459 try!(self.word_nbsp("ref"));
2460 try!(self.print_mutability(mutbl));
2462 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2463 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2464 try!(self.word_nbsp("mut"));
2467 try!(self.print_ident(path1.node));
2468 if let Some(ref p) = *sub {
2469 try!(word(&mut self.s, "@"));
2470 try!(self.print_pat(&p));
2473 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2474 try!(self.print_path(path, true, 0));
2476 if let Some(ddpos) = ddpos {
2477 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2479 try!(self.word_space(","));
2481 try!(word(&mut self.s, ".."));
2482 if ddpos != elts.len() {
2483 try!(word(&mut self.s, ","));
2484 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2487 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2489 try!(self.pclose());
2491 PatKind::Path(None, ref path) => {
2492 try!(self.print_path(path, true, 0));
2494 PatKind::Path(Some(ref qself), ref path) => {
2495 try!(self.print_qpath(path, qself, false));
2497 PatKind::Struct(ref path, ref fields, etc) => {
2498 try!(self.print_path(path, true, 0));
2500 try!(self.word_space("{"));
2501 try!(self.commasep_cmnt(
2502 Consistent, &fields[..],
2504 try!(s.cbox(INDENT_UNIT));
2505 if !f.node.is_shorthand {
2506 try!(s.print_ident(f.node.ident));
2507 try!(s.word_nbsp(":"));
2509 try!(s.print_pat(&f.node.pat));
2512 |f| f.node.pat.span));
2514 if !fields.is_empty() { try!(self.word_space(",")); }
2515 try!(word(&mut self.s, ".."));
2517 try!(space(&mut self.s));
2518 try!(word(&mut self.s, "}"));
2520 PatKind::Tuple(ref elts, ddpos) => {
2522 if let Some(ddpos) = ddpos {
2523 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2525 try!(self.word_space(","));
2527 try!(word(&mut self.s, ".."));
2528 if ddpos != elts.len() {
2529 try!(word(&mut self.s, ","));
2530 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2533 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2534 if elts.len() == 1 {
2535 try!(word(&mut self.s, ","));
2538 try!(self.pclose());
2540 PatKind::Box(ref inner) => {
2541 try!(word(&mut self.s, "box "));
2542 try!(self.print_pat(&inner));
2544 PatKind::Ref(ref inner, mutbl) => {
2545 try!(word(&mut self.s, "&"));
2546 if mutbl == ast::Mutability::Mutable {
2547 try!(word(&mut self.s, "mut "));
2549 try!(self.print_pat(&inner));
2551 PatKind::Lit(ref e) => try!(self.print_expr(&**e)),
2552 PatKind::Range(ref begin, ref end) => {
2553 try!(self.print_expr(&begin));
2554 try!(space(&mut self.s));
2555 try!(word(&mut self.s, "..."));
2556 try!(self.print_expr(&end));
2558 PatKind::Vec(ref before, ref slice, ref after) => {
2559 try!(word(&mut self.s, "["));
2560 try!(self.commasep(Inconsistent,
2562 |s, p| s.print_pat(&p)));
2563 if let Some(ref p) = *slice {
2564 if !before.is_empty() { try!(self.word_space(",")); }
2565 if p.node != PatKind::Wild {
2566 try!(self.print_pat(&p));
2568 try!(word(&mut self.s, ".."));
2569 if !after.is_empty() { try!(self.word_space(",")); }
2571 try!(self.commasep(Inconsistent,
2573 |s, p| s.print_pat(&p)));
2574 try!(word(&mut self.s, "]"));
2576 PatKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2578 self.ann.post(self, NodePat(pat))
2581 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2582 // I have no idea why this check is necessary, but here it
2584 if arm.attrs.is_empty() {
2585 try!(space(&mut self.s));
2587 try!(self.cbox(INDENT_UNIT));
2589 try!(self.print_outer_attributes(&arm.attrs));
2590 let mut first = true;
2591 for p in &arm.pats {
2595 try!(space(&mut self.s));
2596 try!(self.word_space("|"));
2598 try!(self.print_pat(&p));
2600 try!(space(&mut self.s));
2601 if let Some(ref e) = arm.guard {
2602 try!(self.word_space("if"));
2603 try!(self.print_expr(&e));
2604 try!(space(&mut self.s));
2606 try!(self.word_space("=>"));
2608 match arm.body.node {
2609 ast::ExprKind::Block(ref blk) => {
2610 // the block will close the pattern's ibox
2611 try!(self.print_block_unclosed_indent(&blk, INDENT_UNIT));
2613 // If it is a user-provided unsafe block, print a comma after it
2614 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2615 try!(word(&mut self.s, ","));
2619 try!(self.end()); // close the ibox for the pattern
2620 try!(self.print_expr(&arm.body));
2621 try!(word(&mut self.s, ","));
2624 self.end() // close enclosing cbox
2627 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2628 match explicit_self.node {
2629 SelfKind::Value(m) => {
2630 try!(self.print_mutability(m));
2631 word(&mut self.s, "self")
2633 SelfKind::Region(ref lt, m) => {
2634 try!(word(&mut self.s, "&"));
2635 try!(self.print_opt_lifetime(lt));
2636 try!(self.print_mutability(m));
2637 word(&mut self.s, "self")
2639 SelfKind::Explicit(ref typ, m) => {
2640 try!(self.print_mutability(m));
2641 try!(word(&mut self.s, "self"));
2642 try!(self.word_space(":"));
2643 self.print_type(&typ)
2648 pub fn print_fn(&mut self,
2650 unsafety: ast::Unsafety,
2651 constness: ast::Constness,
2653 name: Option<ast::Ident>,
2654 generics: &ast::Generics,
2655 vis: &ast::Visibility) -> io::Result<()> {
2656 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2658 if let Some(name) = name {
2660 try!(self.print_ident(name));
2662 try!(self.print_generics(generics));
2663 try!(self.print_fn_args_and_ret(decl));
2664 self.print_where_clause(&generics.where_clause)
2667 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2670 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false)));
2672 try!(word(&mut self.s, ", ..."));
2674 try!(self.pclose());
2676 self.print_fn_output(decl)
2679 pub fn print_fn_block_args(
2683 try!(word(&mut self.s, "|"));
2684 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true)));
2685 try!(word(&mut self.s, "|"));
2687 if let ast::FunctionRetTy::Default(..) = decl.output {
2691 try!(self.space_if_not_bol());
2692 try!(self.word_space("->"));
2694 ast::FunctionRetTy::Ty(ref ty) => {
2695 try!(self.print_type(&ty));
2696 self.maybe_print_comment(ty.span.lo)
2698 ast::FunctionRetTy::Default(..) => unreachable!(),
2702 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2704 match capture_clause {
2705 ast::CaptureBy::Value => self.word_space("move"),
2706 ast::CaptureBy::Ref => Ok(()),
2710 pub fn print_bounds(&mut self,
2712 bounds: &[ast::TyParamBound])
2714 if !bounds.is_empty() {
2715 try!(word(&mut self.s, prefix));
2716 let mut first = true;
2717 for bound in bounds {
2722 try!(self.word_space("+"));
2726 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2727 self.print_poly_trait_ref(tref)
2729 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2730 try!(word(&mut self.s, "?"));
2731 self.print_poly_trait_ref(tref)
2733 RegionTyParamBound(ref lt) => {
2734 self.print_lifetime(lt)
2744 pub fn print_lifetime(&mut self,
2745 lifetime: &ast::Lifetime)
2748 self.print_name(lifetime.name)
2751 pub fn print_lifetime_bounds(&mut self,
2752 lifetime: &ast::Lifetime,
2753 bounds: &[ast::Lifetime])
2756 try!(self.print_lifetime(lifetime));
2757 if !bounds.is_empty() {
2758 try!(word(&mut self.s, ": "));
2759 for (i, bound) in bounds.iter().enumerate() {
2761 try!(word(&mut self.s, " + "));
2763 try!(self.print_lifetime(bound));
2769 pub fn print_generics(&mut self,
2770 generics: &ast::Generics)
2773 let total = generics.lifetimes.len() + generics.ty_params.len();
2778 try!(word(&mut self.s, "<"));
2780 let mut ints = Vec::new();
2785 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2786 if idx < generics.lifetimes.len() {
2787 let lifetime_def = &generics.lifetimes[idx];
2788 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2790 let idx = idx - generics.lifetimes.len();
2791 let param = &generics.ty_params[idx];
2792 s.print_ty_param(param)
2796 try!(word(&mut self.s, ">"));
2800 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2801 try!(self.print_ident(param.ident));
2802 try!(self.print_bounds(":", ¶m.bounds));
2803 match param.default {
2804 Some(ref default) => {
2805 try!(space(&mut self.s));
2806 try!(self.word_space("="));
2807 self.print_type(&default)
2813 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2815 if where_clause.predicates.is_empty() {
2819 try!(space(&mut self.s));
2820 try!(self.word_space("where"));
2822 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2824 try!(self.word_space(","));
2828 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2832 try!(self.print_formal_lifetime_list(bound_lifetimes));
2833 try!(self.print_type(&bounded_ty));
2834 try!(self.print_bounds(":", bounds));
2836 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2839 try!(self.print_lifetime_bounds(lifetime, bounds));
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::Default(..) => unreachable!(),
2955 ast::FunctionRetTy::Ty(ref ty) =>
2956 try!(self.print_type(&ty))
2961 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2966 pub fn print_ty_fn(&mut self,
2968 unsafety: ast::Unsafety,
2970 name: Option<ast::Ident>,
2971 generics: &ast::Generics)
2973 try!(self.ibox(INDENT_UNIT));
2974 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2975 try!(word(&mut self.s, "for"));
2976 try!(self.print_generics(generics));
2978 let generics = ast::Generics {
2979 lifetimes: Vec::new(),
2980 ty_params: P::new(),
2981 where_clause: ast::WhereClause {
2982 id: ast::DUMMY_NODE_ID,
2983 predicates: Vec::new(),
2986 try!(self.print_fn(decl,
2988 ast::Constness::NotConst,
2992 &ast::Visibility::Inherited));
2996 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2997 next_pos: Option<BytePos>)
2999 let cm = match self.cm {
3003 if let Some(ref cmnt) = self.next_comment() {
3004 if (*cmnt).style != comments::Trailing { return Ok(()) }
3005 let span_line = cm.lookup_char_pos(span.hi);
3006 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3007 let mut next = (*cmnt).pos + BytePos(1);
3008 if let Some(p) = next_pos {
3011 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3012 span_line.line == comment_line.line {
3013 self.print_comment(cmnt)?;
3014 self.cur_cmnt_and_lit.cur_cmnt += 1;
3020 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3021 // If there aren't any remaining comments, then we need to manually
3022 // make sure there is a line break at the end.
3023 if self.next_comment().is_none() {
3024 try!(hardbreak(&mut self.s));
3027 match self.next_comment() {
3029 try!(self.print_comment(cmnt));
3030 self.cur_cmnt_and_lit.cur_cmnt += 1;
3038 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3039 opt_abi: Option<Abi>)
3042 Some(Abi::Rust) => Ok(()),
3044 try!(self.word_nbsp("extern"));
3045 self.word_nbsp(&abi.to_string())
3051 pub fn print_extern_opt_abi(&mut self,
3052 opt_abi: Option<Abi>) -> io::Result<()> {
3055 try!(self.word_nbsp("extern"));
3056 self.word_nbsp(&abi.to_string())
3062 pub fn print_fn_header_info(&mut self,
3063 unsafety: ast::Unsafety,
3064 constness: ast::Constness,
3066 vis: &ast::Visibility) -> io::Result<()> {
3067 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3070 ast::Constness::NotConst => {}
3071 ast::Constness::Const => try!(self.word_nbsp("const"))
3074 try!(self.print_unsafety(unsafety));
3076 if abi != Abi::Rust {
3077 try!(self.word_nbsp("extern"));
3078 try!(self.word_nbsp(&abi.to_string()));
3081 word(&mut self.s, "fn")
3084 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3086 ast::Unsafety::Normal => Ok(()),
3087 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3092 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3104 fn test_fun_to_string() {
3105 let abba_ident = token::str_to_ident("abba");
3107 let decl = ast::FnDecl {
3109 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3112 let generics = ast::Generics::default();
3113 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3114 ast::Constness::NotConst,
3115 abba_ident, &generics),
3120 fn test_variant_to_string() {
3121 let ident = token::str_to_ident("principal_skinner");
3123 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3126 // making this up as I go.... ?
3127 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3131 let varstr = variant_to_string(&var);
3132 assert_eq!(varstr, "principal_skinner");