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 attr::ThinAttributesExt;
18 use util::parser::AssocOp;
20 use attr::{AttrMetaMethods, AttributeMethods};
21 use codemap::{self, CodeMap, 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};
33 use std::io::{self, Write, Read};
36 pub enum AnnNode<'a> {
37 NodeIdent(&'a ast::Ident),
38 NodeName(&'a ast::Name),
39 NodeBlock(&'a ast::Block),
40 NodeItem(&'a ast::Item),
41 NodeSubItem(ast::NodeId),
42 NodeExpr(&'a ast::Expr),
43 NodePat(&'a ast::Pat),
47 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
48 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
51 #[derive(Copy, Clone)]
54 impl PpAnn for NoAnn {}
56 #[derive(Copy, Clone)]
57 pub struct CurrentCommentAndLiteral {
62 pub struct State<'a> {
63 pub s: pp::Printer<'a>,
64 cm: Option<&'a CodeMap>,
65 comments: Option<Vec<comments::Comment> >,
66 literals: Option<Vec<comments::Literal> >,
67 cur_cmnt_and_lit: CurrentCommentAndLiteral,
68 boxes: Vec<pp::Breaks>,
72 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
73 static NO_ANN: NoAnn = NoAnn;
74 rust_printer_annotated(writer, &NO_ANN)
77 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
78 ann: &'a PpAnn) -> State<'a> {
80 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
84 cur_cmnt_and_lit: CurrentCommentAndLiteral {
93 pub const INDENT_UNIT: usize = 4;
95 pub const DEFAULT_COLUMNS: usize = 78;
97 /// Requires you to pass an input filename and reader so that
98 /// it can scan the input text for comments and literals to
100 pub fn print_crate<'a>(cm: &'a CodeMap,
101 span_diagnostic: &errors::Handler,
107 is_expanded: bool) -> io::Result<()> {
108 let mut s = State::new_from_input(cm,
115 if is_expanded && !std_inject::no_std(krate) {
116 // We need to print `#![no_std]` (and its feature gate) so that
117 // compiling pretty-printed source won't inject libstd again.
118 // However we don't want these attributes in the AST because
119 // of the feature gate, so we fake them up here.
121 // #![feature(prelude_import)]
122 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
123 let list = attr::mk_list_item(InternedString::new("feature"),
124 vec![prelude_import_meta]);
125 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
126 try!(s.print_attribute(&fake_attr));
129 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
130 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
131 try!(s.print_attribute(&fake_attr));
134 try!(s.print_mod(&krate.module, &krate.attrs));
135 try!(s.print_remaining_comments());
140 pub fn new_from_input(cm: &'a CodeMap,
141 span_diagnostic: &errors::Handler,
146 is_expanded: bool) -> State<'a> {
147 let (cmnts, lits) = comments::gather_comments_and_literals(
157 // If the code is post expansion, don't use the table of
158 // literals, since it doesn't correspond with the literals
159 // in the AST anymore.
160 if is_expanded { None } else { Some(lits) })
163 pub fn new(cm: &'a CodeMap,
166 comments: Option<Vec<comments::Comment>>,
167 literals: Option<Vec<comments::Literal>>) -> State<'a> {
169 s: pp::mk_printer(out, DEFAULT_COLUMNS),
173 cur_cmnt_and_lit: CurrentCommentAndLiteral {
183 pub fn to_string<F>(f: F) -> String where
184 F: FnOnce(&mut State) -> io::Result<()>,
186 let mut wr = Vec::new();
188 let mut printer = rust_printer(Box::new(&mut wr));
189 f(&mut printer).unwrap();
190 eof(&mut printer.s).unwrap();
192 String::from_utf8(wr).unwrap()
195 pub fn binop_to_string(op: BinOpToken) -> &'static str {
201 token::Percent => "%",
210 pub fn token_to_string(tok: &Token) -> String {
212 token::Eq => "=".to_string(),
213 token::Lt => "<".to_string(),
214 token::Le => "<=".to_string(),
215 token::EqEq => "==".to_string(),
216 token::Ne => "!=".to_string(),
217 token::Ge => ">=".to_string(),
218 token::Gt => ">".to_string(),
219 token::Not => "!".to_string(),
220 token::Tilde => "~".to_string(),
221 token::OrOr => "||".to_string(),
222 token::AndAnd => "&&".to_string(),
223 token::BinOp(op) => binop_to_string(op).to_string(),
224 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
226 /* Structural symbols */
227 token::At => "@".to_string(),
228 token::Dot => ".".to_string(),
229 token::DotDot => "..".to_string(),
230 token::DotDotDot => "...".to_string(),
231 token::Comma => ",".to_string(),
232 token::Semi => ";".to_string(),
233 token::Colon => ":".to_string(),
234 token::ModSep => "::".to_string(),
235 token::RArrow => "->".to_string(),
236 token::LArrow => "<-".to_string(),
237 token::FatArrow => "=>".to_string(),
238 token::OpenDelim(token::Paren) => "(".to_string(),
239 token::CloseDelim(token::Paren) => ")".to_string(),
240 token::OpenDelim(token::Bracket) => "[".to_string(),
241 token::CloseDelim(token::Bracket) => "]".to_string(),
242 token::OpenDelim(token::Brace) => "{".to_string(),
243 token::CloseDelim(token::Brace) => "}".to_string(),
244 token::Pound => "#".to_string(),
245 token::Dollar => "$".to_string(),
246 token::Question => "?".to_string(),
249 token::Literal(lit, suf) => {
250 let mut out = match lit {
251 token::Byte(b) => format!("b'{}'", b),
252 token::Char(c) => format!("'{}'", c),
253 token::Float(c) => c.to_string(),
254 token::Integer(c) => c.to_string(),
255 token::Str_(s) => format!("\"{}\"", s),
256 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
257 delim=repeat("#", n),
259 token::ByteStr(v) => format!("b\"{}\"", v),
260 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
261 delim=repeat("#", n),
265 if let Some(s) = suf {
266 out.push_str(&s.as_str())
272 /* Name components */
273 token::Ident(s) => s.to_string(),
274 token::Lifetime(s) => s.to_string(),
275 token::Underscore => "_".to_string(),
278 token::DocComment(s) => s.to_string(),
279 token::SubstNt(s) => format!("${}", s),
280 token::MatchNt(s, t) => format!("${}:{}", s, t),
281 token::Eof => "<eof>".to_string(),
282 token::Whitespace => " ".to_string(),
283 token::Comment => "/* */".to_string(),
284 token::Shebang(s) => format!("/* shebang: {}*/", s),
286 token::SpecialVarNt(var) => format!("${}", var.as_str()),
288 token::Interpolated(ref nt) => match *nt {
289 token::NtExpr(ref e) => expr_to_string(&e),
290 token::NtMeta(ref e) => meta_item_to_string(&e),
291 token::NtTy(ref e) => ty_to_string(&e),
292 token::NtPath(ref e) => path_to_string(&e),
293 token::NtItem(ref e) => item_to_string(&e),
294 token::NtBlock(ref e) => block_to_string(&e),
295 token::NtStmt(ref e) => stmt_to_string(&e),
296 token::NtPat(ref e) => pat_to_string(&e),
297 token::NtIdent(ref e) => ident_to_string(e.node),
298 token::NtTT(ref e) => tt_to_string(&e),
299 token::NtArm(ref e) => arm_to_string(&e),
300 token::NtImplItem(ref e) => impl_item_to_string(&e),
301 token::NtTraitItem(ref e) => trait_item_to_string(&e),
302 token::NtGenerics(ref e) => generics_to_string(&e),
303 token::NtWhereClause(ref e) => where_clause_to_string(&e),
304 token::NtArg(ref e) => arg_to_string(&e),
309 pub fn ty_to_string(ty: &ast::Ty) -> String {
310 to_string(|s| s.print_type(ty))
313 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
314 to_string(|s| s.print_bounds("", bounds))
317 pub fn pat_to_string(pat: &ast::Pat) -> String {
318 to_string(|s| s.print_pat(pat))
321 pub fn arm_to_string(arm: &ast::Arm) -> String {
322 to_string(|s| s.print_arm(arm))
325 pub fn expr_to_string(e: &ast::Expr) -> String {
326 to_string(|s| s.print_expr(e))
329 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
330 to_string(|s| s.print_lifetime(e))
333 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
334 to_string(|s| s.print_tt(tt))
337 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
338 to_string(|s| s.print_tts(tts))
341 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
342 to_string(|s| s.print_stmt(stmt))
345 pub fn attr_to_string(attr: &ast::Attribute) -> String {
346 to_string(|s| s.print_attribute(attr))
349 pub fn item_to_string(i: &ast::Item) -> String {
350 to_string(|s| s.print_item(i))
353 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
354 to_string(|s| s.print_impl_item(i))
357 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
358 to_string(|s| s.print_trait_item(i))
361 pub fn generics_to_string(generics: &ast::Generics) -> String {
362 to_string(|s| s.print_generics(generics))
365 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
366 to_string(|s| s.print_where_clause(i))
369 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
370 to_string(|s| s.print_fn_block_args(p))
373 pub fn path_to_string(p: &ast::Path) -> String {
374 to_string(|s| s.print_path(p, false, 0))
377 pub fn ident_to_string(id: ast::Ident) -> String {
378 to_string(|s| s.print_ident(id))
381 pub fn fun_to_string(decl: &ast::FnDecl,
382 unsafety: ast::Unsafety,
383 constness: ast::Constness,
385 generics: &ast::Generics)
389 try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
390 generics, &ast::Visibility::Inherited));
391 try!(s.end()); // Close the head box
392 s.end() // Close the outer box
396 pub fn block_to_string(blk: &ast::Block) -> String {
398 // containing cbox, will be closed by print-block at }
399 try!(s.cbox(INDENT_UNIT));
400 // head-ibox, will be closed by print-block after {
406 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
407 to_string(|s| s.print_meta_item(mi))
410 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
411 to_string(|s| s.print_attribute(attr))
414 pub fn lit_to_string(l: &ast::Lit) -> String {
415 to_string(|s| s.print_literal(l))
418 pub fn variant_to_string(var: &ast::Variant) -> String {
419 to_string(|s| s.print_variant(var))
422 pub fn arg_to_string(arg: &ast::Arg) -> String {
423 to_string(|s| s.print_arg(arg, false))
426 pub fn mac_to_string(arg: &ast::Mac) -> String {
427 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
430 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
432 ast::Visibility::Public => format!("pub {}", s),
433 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
434 ast::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
435 ast::Visibility::Inherited => s.to_string()
439 fn needs_parentheses(expr: &ast::Expr) -> bool {
441 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
442 ast::ExprKind::Closure(..) |
443 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
444 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
449 pub trait PrintState<'a> {
450 fn writer(&mut self) -> &mut pp::Printer<'a>;
451 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
452 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
453 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
454 fn literals(&self) -> &Option<Vec<comments::Literal>>;
456 fn word_space(&mut self, w: &str) -> io::Result<()> {
457 try!(word(self.writer(), w));
461 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
463 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
465 fn is_begin(&mut self) -> bool {
466 match self.writer().last_token() {
467 pp::Token::Begin(_) => true,
472 fn is_end(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::End => true,
479 // is this the beginning of a line?
480 fn is_bol(&mut self) -> bool {
481 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
484 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
486 try!(hardbreak(self.writer()))
492 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
493 self.boxes().push(b);
494 pp::rbox(self.writer(), u, b)
497 fn ibox(&mut self, u: usize) -> io::Result<()> {
498 self.boxes().push(pp::Breaks::Inconsistent);
499 pp::ibox(self.writer(), u)
502 fn end(&mut self) -> io::Result<()> {
503 self.boxes().pop().unwrap();
504 pp::end(self.writer())
507 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
508 where F: FnMut(&mut Self, &T) -> io::Result<()>,
510 try!(self.rbox(0, b));
511 let mut first = true;
513 if first { first = false; } else { try!(self.word_space(",")); }
519 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
520 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
522 let mut result = None;
524 if let &Some(ref lits) = self.literals()
526 while cur_lit < lits.len() {
527 let ltrl = (*lits)[cur_lit].clone();
528 if ltrl.pos > pos { break; }
537 self.cur_cmnt_and_lit().cur_lit = cur_lit;
541 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
543 match self.next_comment() {
545 if (*cmnt).pos < pos {
546 try!(self.print_comment(cmnt));
547 self.cur_cmnt_and_lit().cur_cmnt += 1;
556 fn print_comment(&mut self,
557 cmnt: &comments::Comment) -> io::Result<()> {
560 assert_eq!(cmnt.lines.len(), 1);
561 try!(zerobreak(self.writer()));
562 try!(word(self.writer(), &cmnt.lines[0]));
563 zerobreak(self.writer())
565 comments::Isolated => {
566 try!(self.hardbreak_if_not_bol());
567 for line in &cmnt.lines {
568 // Don't print empty lines because they will end up as trailing
570 if !line.is_empty() {
571 try!(word(self.writer(), &line[..]));
573 try!(hardbreak(self.writer()));
577 comments::Trailing => {
578 try!(word(self.writer(), " "));
579 if cmnt.lines.len() == 1 {
580 try!(word(self.writer(), &cmnt.lines[0]));
581 hardbreak(self.writer())
584 for line in &cmnt.lines {
585 if !line.is_empty() {
586 try!(word(self.writer(), &line[..]));
588 try!(hardbreak(self.writer()));
593 comments::BlankLine => {
594 // We need to do at least one, possibly two hardbreaks.
595 let is_semi = match self.writer().last_token() {
596 pp::Token::String(s, _) => ";" == s,
599 if is_semi || self.is_begin() || self.is_end() {
600 try!(hardbreak(self.writer()));
602 hardbreak(self.writer())
607 fn next_comment(&mut self) -> Option<comments::Comment> {
608 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
609 match *self.comments() {
611 if cur_cmnt < cmnts.len() {
612 Some(cmnts[cur_cmnt].clone())
621 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
622 try!(self.maybe_print_comment(lit.span.lo));
623 match self.next_lit(lit.span.lo) {
625 return word(self.writer(), &(*ltrl).lit);
630 ast::LitKind::Str(ref st, style) => self.print_string(&st, style),
631 ast::LitKind::Byte(byte) => {
632 let mut res = String::from("b'");
633 res.extend(ascii::escape_default(byte).map(|c| c as char));
635 word(self.writer(), &res[..])
637 ast::LitKind::Char(ch) => {
638 let mut res = String::from("'");
639 res.extend(ch.escape_default());
641 word(self.writer(), &res[..])
643 ast::LitKind::Int(i, t) => {
645 ast::LitIntType::Signed(st) => {
647 &st.val_to_string(i as i64))
649 ast::LitIntType::Unsigned(ut) => {
650 word(self.writer(), &ut.val_to_string(i))
652 ast::LitIntType::Unsuffixed => {
653 word(self.writer(), &format!("{}", i))
657 ast::LitKind::Float(ref f, t) => {
664 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
665 ast::LitKind::Bool(val) => {
666 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
668 ast::LitKind::ByteStr(ref v) => {
669 let mut escaped: String = String::new();
670 for &ch in v.iter() {
671 escaped.extend(ascii::escape_default(ch)
672 .map(|c| c as char));
674 word(self.writer(), &format!("b\"{}\"", escaped))
679 fn print_string(&mut self, st: &str,
680 style: ast::StrStyle) -> io::Result<()> {
681 let st = match style {
682 ast::StrStyle::Cooked => {
683 (format!("\"{}\"", st.escape_default()))
685 ast::StrStyle::Raw(n) => {
686 (format!("r{delim}\"{string}\"{delim}",
687 delim=repeat("#", n),
691 word(self.writer(), &st[..])
694 fn print_inner_attributes(&mut self,
695 attrs: &[ast::Attribute]) -> io::Result<()> {
696 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
699 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
700 attrs: &[ast::Attribute])
702 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
705 fn print_outer_attributes(&mut self,
706 attrs: &[ast::Attribute]) -> io::Result<()> {
707 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
710 fn print_inner_attributes_inline(&mut self,
711 attrs: &[ast::Attribute]) -> io::Result<()> {
712 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
715 fn print_outer_attributes_inline(&mut self,
716 attrs: &[ast::Attribute]) -> io::Result<()> {
717 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
720 fn print_either_attributes(&mut self,
721 attrs: &[ast::Attribute],
722 kind: ast::AttrStyle,
724 trailing_hardbreak: bool) -> io::Result<()> {
727 if attr.node.style == kind {
728 try!(self.print_attribute_inline(attr, is_inline));
735 if count > 0 && trailing_hardbreak && !is_inline {
736 try!(self.hardbreak_if_not_bol());
741 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
742 self.print_attribute_inline(attr, false)
745 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
746 is_inline: bool) -> io::Result<()> {
748 try!(self.hardbreak_if_not_bol());
750 try!(self.maybe_print_comment(attr.span.lo));
751 if attr.node.is_sugared_doc {
752 try!(word(self.writer(), &attr.value_str().unwrap()));
753 hardbreak(self.writer())
755 match attr.node.style {
756 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
757 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
759 try!(self.print_meta_item(&attr.meta()));
760 word(self.writer(), "]")
764 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
765 try!(self.ibox(INDENT_UNIT));
767 ast::MetaItemKind::Word(ref name) => {
768 try!(word(self.writer(), &name));
770 ast::MetaItemKind::NameValue(ref name, ref value) => {
771 try!(self.word_space(&name[..]));
772 try!(self.word_space("="));
773 try!(self.print_literal(value));
775 ast::MetaItemKind::List(ref name, ref items) => {
776 try!(word(self.writer(), &name));
778 try!(self.commasep(Consistent,
780 |s, i| s.print_meta_item(&i)));
787 fn space_if_not_bol(&mut self) -> io::Result<()> {
788 if !self.is_bol() { try!(space(self.writer())); }
792 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
795 impl<'a> PrintState<'a> for State<'a> {
796 fn writer(&mut self) -> &mut pp::Printer<'a> {
800 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
804 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
808 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
809 &mut self.cur_cmnt_and_lit
812 fn literals(&self) -> &Option<Vec<comments::Literal>> {
818 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
819 self.boxes.push(pp::Breaks::Consistent);
820 pp::cbox(&mut self.s, u)
823 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
824 try!(word(&mut self.s, w));
828 pub fn head(&mut self, w: &str) -> io::Result<()> {
829 // outer-box is consistent
830 try!(self.cbox(INDENT_UNIT));
831 // head-box is inconsistent
832 try!(self.ibox(w.len() + 1));
833 // keyword that starts the head
835 try!(self.word_nbsp(w));
840 pub fn bopen(&mut self) -> io::Result<()> {
841 try!(word(&mut self.s, "{"));
842 self.end() // close the head-box
845 pub fn bclose_(&mut self, span: codemap::Span,
846 indented: usize) -> io::Result<()> {
847 self.bclose_maybe_open(span, indented, true)
849 pub fn bclose_maybe_open(&mut self, span: codemap::Span,
850 indented: usize, close_box: bool) -> io::Result<()> {
851 try!(self.maybe_print_comment(span.hi));
852 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
853 try!(word(&mut self.s, "}"));
855 try!(self.end()); // close the outer-box
859 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
860 self.bclose_(span, INDENT_UNIT)
863 pub fn in_cbox(&self) -> bool {
864 match self.boxes.last() {
865 Some(&last_box) => last_box == pp::Breaks::Consistent,
870 pub fn break_offset_if_not_bol(&mut self, n: usize,
871 off: isize) -> io::Result<()> {
873 break_offset(&mut self.s, n, off)
875 if off != 0 && self.s.last_token().is_hardbreak_tok() {
876 // We do something pretty sketchy here: tuck the nonzero
877 // offset-adjustment we were going to deposit along with the
878 // break into the previous hardbreak.
879 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
885 // Synthesizes a comment that was not textually present in the original source
887 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
888 try!(word(&mut self.s, "/*"));
889 try!(space(&mut self.s));
890 try!(word(&mut self.s, &text[..]));
891 try!(space(&mut self.s));
892 word(&mut self.s, "*/")
897 pub fn commasep_cmnt<T, F, G>(&mut self,
901 mut get_span: G) -> io::Result<()> where
902 F: FnMut(&mut State, &T) -> io::Result<()>,
903 G: FnMut(&T) -> codemap::Span,
905 try!(self.rbox(0, b));
906 let len = elts.len();
909 try!(self.maybe_print_comment(get_span(elt).hi));
913 try!(word(&mut self.s, ","));
914 try!(self.maybe_print_trailing_comment(get_span(elt),
915 Some(get_span(&elts[i]).hi)));
916 try!(self.space_if_not_bol());
922 pub fn commasep_exprs(&mut self, b: Breaks,
923 exprs: &[P<ast::Expr>]) -> io::Result<()> {
924 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
927 pub fn print_mod(&mut self, _mod: &ast::Mod,
928 attrs: &[ast::Attribute]) -> io::Result<()> {
929 try!(self.print_inner_attributes(attrs));
930 for item in &_mod.items {
931 try!(self.print_item(&item));
936 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
937 attrs: &[ast::Attribute]) -> io::Result<()> {
938 try!(self.print_inner_attributes(attrs));
939 for item in &nmod.items {
940 try!(self.print_foreign_item(item));
945 pub fn print_opt_lifetime(&mut self,
946 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
947 if let Some(l) = *lifetime {
948 try!(self.print_lifetime(&l));
954 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
955 try!(self.maybe_print_comment(ty.span.lo));
958 ast::TyKind::Vec(ref ty) => {
959 try!(word(&mut self.s, "["));
960 try!(self.print_type(&ty));
961 try!(word(&mut self.s, "]"));
963 ast::TyKind::Ptr(ref mt) => {
964 try!(word(&mut self.s, "*"));
966 ast::Mutability::Mutable => try!(self.word_nbsp("mut")),
967 ast::Mutability::Immutable => try!(self.word_nbsp("const")),
969 try!(self.print_type(&mt.ty));
971 ast::TyKind::Rptr(ref lifetime, ref mt) => {
972 try!(word(&mut self.s, "&"));
973 try!(self.print_opt_lifetime(lifetime));
974 try!(self.print_mt(mt));
976 ast::TyKind::Tup(ref elts) => {
978 try!(self.commasep(Inconsistent, &elts[..],
979 |s, ty| s.print_type(&ty)));
981 try!(word(&mut self.s, ","));
985 ast::TyKind::Paren(ref typ) => {
987 try!(self.print_type(&typ));
990 ast::TyKind::BareFn(ref f) => {
991 let generics = ast::Generics {
992 lifetimes: f.lifetimes.clone(),
994 where_clause: ast::WhereClause {
995 id: ast::DUMMY_NODE_ID,
996 predicates: Vec::new(),
999 try!(self.print_ty_fn(f.abi,
1005 ast::TyKind::Path(None, ref path) => {
1006 try!(self.print_path(path, false, 0));
1008 ast::TyKind::Path(Some(ref qself), ref path) => {
1009 try!(self.print_qpath(path, qself, false))
1011 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1012 try!(self.print_type(&ty));
1013 try!(self.print_bounds("+", &bounds[..]));
1015 ast::TyKind::PolyTraitRef(ref bounds) => {
1016 try!(self.print_bounds("", &bounds[..]));
1018 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1019 try!(word(&mut self.s, "["));
1020 try!(self.print_type(&ty));
1021 try!(word(&mut self.s, "; "));
1022 try!(self.print_expr(&v));
1023 try!(word(&mut self.s, "]"));
1025 ast::TyKind::Typeof(ref e) => {
1026 try!(word(&mut self.s, "typeof("));
1027 try!(self.print_expr(&e));
1028 try!(word(&mut self.s, ")"));
1030 ast::TyKind::Infer => {
1031 try!(word(&mut self.s, "_"));
1033 ast::TyKind::ImplicitSelf => {
1034 try!(word(&mut self.s, "Self"));
1036 ast::TyKind::Mac(ref m) => {
1037 try!(self.print_mac(m, token::Paren));
1043 pub fn print_foreign_item(&mut self,
1044 item: &ast::ForeignItem) -> io::Result<()> {
1045 try!(self.hardbreak_if_not_bol());
1046 try!(self.maybe_print_comment(item.span.lo));
1047 try!(self.print_outer_attributes(&item.attrs));
1049 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1050 try!(self.head(""));
1051 try!(self.print_fn(decl, ast::Unsafety::Normal,
1052 ast::Constness::NotConst,
1053 Abi::Rust, Some(item.ident),
1054 generics, &item.vis));
1055 try!(self.end()); // end head-ibox
1056 try!(word(&mut self.s, ";"));
1057 self.end() // end the outer fn box
1059 ast::ForeignItemKind::Static(ref t, m) => {
1060 try!(self.head(&visibility_qualified(&item.vis, "static")));
1062 try!(self.word_space("mut"));
1064 try!(self.print_ident(item.ident));
1065 try!(self.word_space(":"));
1066 try!(self.print_type(&t));
1067 try!(word(&mut self.s, ";"));
1068 try!(self.end()); // end the head-ibox
1069 self.end() // end the outer cbox
1074 fn print_associated_const(&mut self,
1077 default: Option<&ast::Expr>,
1078 vis: &ast::Visibility)
1081 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1082 try!(self.word_space("const"));
1083 try!(self.print_ident(ident));
1084 try!(self.word_space(":"));
1085 try!(self.print_type(ty));
1086 if let Some(expr) = default {
1087 try!(space(&mut self.s));
1088 try!(self.word_space("="));
1089 try!(self.print_expr(expr));
1091 word(&mut self.s, ";")
1094 fn print_associated_type(&mut self,
1096 bounds: Option<&ast::TyParamBounds>,
1097 ty: Option<&ast::Ty>)
1099 try!(self.word_space("type"));
1100 try!(self.print_ident(ident));
1101 if let Some(bounds) = bounds {
1102 try!(self.print_bounds(":", bounds));
1104 if let Some(ty) = ty {
1105 try!(space(&mut self.s));
1106 try!(self.word_space("="));
1107 try!(self.print_type(ty));
1109 word(&mut self.s, ";")
1112 /// Pretty-print an item
1113 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1114 try!(self.hardbreak_if_not_bol());
1115 try!(self.maybe_print_comment(item.span.lo));
1116 try!(self.print_outer_attributes(&item.attrs));
1117 try!(self.ann.pre(self, NodeItem(item)));
1119 ast::ItemKind::ExternCrate(ref optional_path) => {
1120 try!(self.head(&visibility_qualified(&item.vis, "extern crate")));
1121 if let Some(p) = *optional_path {
1122 let val = p.as_str();
1123 if val.contains("-") {
1124 try!(self.print_string(&val, ast::StrStyle::Cooked));
1126 try!(self.print_name(p));
1128 try!(space(&mut self.s));
1129 try!(word(&mut self.s, "as"));
1130 try!(space(&mut self.s));
1132 try!(self.print_ident(item.ident));
1133 try!(word(&mut self.s, ";"));
1134 try!(self.end()); // end inner head-block
1135 try!(self.end()); // end outer head-block
1137 ast::ItemKind::Use(ref vp) => {
1138 try!(self.head(&visibility_qualified(&item.vis, "use")));
1139 try!(self.print_view_path(&vp));
1140 try!(word(&mut self.s, ";"));
1141 try!(self.end()); // end inner head-block
1142 try!(self.end()); // end outer head-block
1144 ast::ItemKind::Static(ref ty, m, ref expr) => {
1145 try!(self.head(&visibility_qualified(&item.vis, "static")));
1146 if m == ast::Mutability::Mutable {
1147 try!(self.word_space("mut"));
1149 try!(self.print_ident(item.ident));
1150 try!(self.word_space(":"));
1151 try!(self.print_type(&ty));
1152 try!(space(&mut self.s));
1153 try!(self.end()); // end the head-ibox
1155 try!(self.word_space("="));
1156 try!(self.print_expr(&expr));
1157 try!(word(&mut self.s, ";"));
1158 try!(self.end()); // end the outer cbox
1160 ast::ItemKind::Const(ref ty, ref expr) => {
1161 try!(self.head(&visibility_qualified(&item.vis, "const")));
1162 try!(self.print_ident(item.ident));
1163 try!(self.word_space(":"));
1164 try!(self.print_type(&ty));
1165 try!(space(&mut self.s));
1166 try!(self.end()); // end the head-ibox
1168 try!(self.word_space("="));
1169 try!(self.print_expr(&expr));
1170 try!(word(&mut self.s, ";"));
1171 try!(self.end()); // end the outer cbox
1173 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1174 try!(self.head(""));
1184 try!(word(&mut self.s, " "));
1185 try!(self.print_block_with_attrs(&body, &item.attrs));
1187 ast::ItemKind::Mod(ref _mod) => {
1188 try!(self.head(&visibility_qualified(&item.vis, "mod")));
1189 try!(self.print_ident(item.ident));
1192 try!(self.print_mod(_mod, &item.attrs));
1193 try!(self.bclose(item.span));
1195 ast::ItemKind::ForeignMod(ref nmod) => {
1196 try!(self.head("extern"));
1197 try!(self.word_nbsp(&nmod.abi.to_string()));
1199 try!(self.print_foreign_mod(nmod, &item.attrs));
1200 try!(self.bclose(item.span));
1202 ast::ItemKind::Ty(ref ty, ref params) => {
1203 try!(self.ibox(INDENT_UNIT));
1205 try!(self.word_nbsp(&visibility_qualified(&item.vis, "type")));
1206 try!(self.print_ident(item.ident));
1207 try!(self.print_generics(params));
1208 try!(self.end()); // end the inner ibox
1210 try!(self.print_where_clause(¶ms.where_clause));
1211 try!(space(&mut self.s));
1212 try!(self.word_space("="));
1213 try!(self.print_type(&ty));
1214 try!(word(&mut self.s, ";"));
1215 try!(self.end()); // end the outer ibox
1217 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1218 try!(self.print_enum_def(
1226 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1227 try!(self.head(&visibility_qualified(&item.vis, "struct")));
1228 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1231 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1232 try!(self.head(""));
1233 try!(self.print_visibility(&item.vis));
1234 try!(self.print_unsafety(unsafety));
1235 try!(self.word_nbsp("impl"));
1236 try!(self.print_trait_ref(trait_ref));
1237 try!(space(&mut self.s));
1238 try!(self.word_space("for"));
1239 try!(self.word_space(".."));
1241 try!(self.bclose(item.span));
1243 ast::ItemKind::Impl(unsafety,
1248 ref impl_items) => {
1249 try!(self.head(""));
1250 try!(self.print_visibility(&item.vis));
1251 try!(self.print_unsafety(unsafety));
1252 try!(self.word_nbsp("impl"));
1254 if generics.is_parameterized() {
1255 try!(self.print_generics(generics));
1256 try!(space(&mut self.s));
1260 ast::ImplPolarity::Negative => {
1261 try!(word(&mut self.s, "!"));
1268 try!(self.print_trait_ref(t));
1269 try!(space(&mut self.s));
1270 try!(self.word_space("for"));
1275 try!(self.print_type(&ty));
1276 try!(self.print_where_clause(&generics.where_clause));
1278 try!(space(&mut self.s));
1280 try!(self.print_inner_attributes(&item.attrs));
1281 for impl_item in impl_items {
1282 try!(self.print_impl_item(impl_item));
1284 try!(self.bclose(item.span));
1286 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1287 try!(self.head(""));
1288 try!(self.print_visibility(&item.vis));
1289 try!(self.print_unsafety(unsafety));
1290 try!(self.word_nbsp("trait"));
1291 try!(self.print_ident(item.ident));
1292 try!(self.print_generics(generics));
1293 let mut real_bounds = Vec::with_capacity(bounds.len());
1294 for b in bounds.iter() {
1295 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1296 try!(space(&mut self.s));
1297 try!(self.word_space("for ?"));
1298 try!(self.print_trait_ref(&ptr.trait_ref));
1300 real_bounds.push(b.clone());
1303 try!(self.print_bounds(":", &real_bounds[..]));
1304 try!(self.print_where_clause(&generics.where_clause));
1305 try!(word(&mut self.s, " "));
1307 for trait_item in trait_items {
1308 try!(self.print_trait_item(trait_item));
1310 try!(self.bclose(item.span));
1312 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1313 try!(self.print_visibility(&item.vis));
1314 try!(self.print_path(&node.path, false, 0));
1315 try!(word(&mut self.s, "! "));
1316 try!(self.print_ident(item.ident));
1317 try!(self.cbox(INDENT_UNIT));
1319 try!(self.print_tts(&node.tts[..]));
1320 try!(self.pclose());
1321 try!(word(&mut self.s, ";"));
1325 self.ann.post(self, NodeItem(item))
1328 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1329 self.print_path(&t.path, false, 0)
1332 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1333 if !lifetimes.is_empty() {
1334 try!(word(&mut self.s, "for<"));
1335 let mut comma = false;
1336 for lifetime_def in lifetimes {
1338 try!(self.word_space(","))
1340 try!(self.print_lifetime_def(lifetime_def));
1343 try!(word(&mut self.s, ">"));
1348 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1349 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1350 self.print_trait_ref(&t.trait_ref)
1353 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1354 generics: &ast::Generics, ident: ast::Ident,
1355 span: codemap::Span,
1356 visibility: &ast::Visibility) -> io::Result<()> {
1357 try!(self.head(&visibility_qualified(visibility, "enum")));
1358 try!(self.print_ident(ident));
1359 try!(self.print_generics(generics));
1360 try!(self.print_where_clause(&generics.where_clause));
1361 try!(space(&mut self.s));
1362 self.print_variants(&enum_definition.variants, span)
1365 pub fn print_variants(&mut self,
1366 variants: &[ast::Variant],
1367 span: codemap::Span) -> io::Result<()> {
1370 try!(self.space_if_not_bol());
1371 try!(self.maybe_print_comment(v.span.lo));
1372 try!(self.print_outer_attributes(&v.node.attrs));
1373 try!(self.ibox(INDENT_UNIT));
1374 try!(self.print_variant(v));
1375 try!(word(&mut self.s, ","));
1377 try!(self.maybe_print_trailing_comment(v.span, None));
1382 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1384 ast::Visibility::Public => self.word_nbsp("pub"),
1385 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1386 ast::Visibility::Restricted { ref path, .. } =>
1387 self.word_nbsp(&format!("pub({})", path)),
1388 ast::Visibility::Inherited => Ok(())
1392 pub fn print_struct(&mut self,
1393 struct_def: &ast::VariantData,
1394 generics: &ast::Generics,
1396 span: codemap::Span,
1397 print_finalizer: bool) -> io::Result<()> {
1398 try!(self.print_ident(ident));
1399 try!(self.print_generics(generics));
1400 if !struct_def.is_struct() {
1401 if struct_def.is_tuple() {
1404 Inconsistent, struct_def.fields(),
1406 try!(s.maybe_print_comment(field.span.lo));
1407 try!(s.print_outer_attributes(&field.attrs));
1408 try!(s.print_visibility(&field.vis));
1409 s.print_type(&field.ty)
1412 try!(self.pclose());
1414 try!(self.print_where_clause(&generics.where_clause));
1415 if print_finalizer {
1416 try!(word(&mut self.s, ";"));
1419 self.end() // close the outer-box
1421 try!(self.print_where_clause(&generics.where_clause));
1424 try!(self.hardbreak_if_not_bol());
1426 for field in struct_def.fields() {
1427 try!(self.hardbreak_if_not_bol());
1428 try!(self.maybe_print_comment(field.span.lo));
1429 try!(self.print_outer_attributes(&field.attrs));
1430 try!(self.print_visibility(&field.vis));
1431 try!(self.print_ident(field.ident.unwrap()));
1432 try!(self.word_nbsp(":"));
1433 try!(self.print_type(&field.ty));
1434 try!(word(&mut self.s, ","));
1441 /// This doesn't deserve to be called "pretty" printing, but it should be
1442 /// meaning-preserving. A quick hack that might help would be to look at the
1443 /// spans embedded in the TTs to decide where to put spaces and newlines.
1444 /// But it'd be better to parse these according to the grammar of the
1445 /// appropriate macro, transcribe back into the grammar we just parsed from,
1446 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1447 /// expression arguments as expressions). It can be done! I think.
1448 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1450 TokenTree::Token(_, ref tk) => {
1451 try!(word(&mut self.s, &token_to_string(tk)));
1453 parse::token::DocComment(..) => {
1454 hardbreak(&mut self.s)
1459 TokenTree::Delimited(_, ref delimed) => {
1460 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1461 try!(space(&mut self.s));
1462 try!(self.print_tts(&delimed.tts));
1463 try!(space(&mut self.s));
1464 word(&mut self.s, &token_to_string(&delimed.close_token()))
1466 TokenTree::Sequence(_, ref seq) => {
1467 try!(word(&mut self.s, "$("));
1468 for tt_elt in &seq.tts {
1469 try!(self.print_tt(tt_elt));
1471 try!(word(&mut self.s, ")"));
1472 match seq.separator {
1474 try!(word(&mut self.s, &token_to_string(tk)));
1479 ast::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1480 ast::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1486 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1488 for (i, tt) in tts.iter().enumerate() {
1490 try!(space(&mut self.s));
1492 try!(self.print_tt(tt));
1497 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1498 try!(self.head(""));
1499 let generics = ast::Generics::default();
1500 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1501 match v.node.disr_expr {
1503 try!(space(&mut self.s));
1504 try!(self.word_space("="));
1511 pub fn print_method_sig(&mut self,
1514 vis: &ast::Visibility)
1516 self.print_fn(&m.decl,
1525 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1527 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1528 try!(self.hardbreak_if_not_bol());
1529 try!(self.maybe_print_comment(ti.span.lo));
1530 try!(self.print_outer_attributes(&ti.attrs));
1532 ast::TraitItemKind::Const(ref ty, ref default) => {
1533 try!(self.print_associated_const(ti.ident, &ty,
1534 default.as_ref().map(|expr| &**expr),
1535 &ast::Visibility::Inherited));
1537 ast::TraitItemKind::Method(ref sig, ref body) => {
1539 try!(self.head(""));
1541 try!(self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited));
1542 if let Some(ref body) = *body {
1544 try!(self.print_block_with_attrs(body, &ti.attrs));
1546 try!(word(&mut self.s, ";"));
1549 ast::TraitItemKind::Type(ref bounds, ref default) => {
1550 try!(self.print_associated_type(ti.ident, Some(bounds),
1551 default.as_ref().map(|ty| &**ty)));
1554 self.ann.post(self, NodeSubItem(ti.id))
1557 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1558 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1559 try!(self.hardbreak_if_not_bol());
1560 try!(self.maybe_print_comment(ii.span.lo));
1561 try!(self.print_outer_attributes(&ii.attrs));
1562 if let ast::Defaultness::Default = ii.defaultness {
1563 try!(self.word_nbsp("default"));
1566 ast::ImplItemKind::Const(ref ty, ref expr) => {
1567 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis));
1569 ast::ImplItemKind::Method(ref sig, ref body) => {
1570 try!(self.head(""));
1571 try!(self.print_method_sig(ii.ident, sig, &ii.vis));
1573 try!(self.print_block_with_attrs(body, &ii.attrs));
1575 ast::ImplItemKind::Type(ref ty) => {
1576 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1578 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1579 // code copied from ItemKind::Mac:
1580 try!(self.print_path(&node.path, false, 0));
1581 try!(word(&mut self.s, "! "));
1582 try!(self.cbox(INDENT_UNIT));
1584 try!(self.print_tts(&node.tts[..]));
1585 try!(self.pclose());
1586 try!(word(&mut self.s, ";"));
1590 self.ann.post(self, NodeSubItem(ii.id))
1593 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1594 try!(self.maybe_print_comment(st.span.lo));
1596 ast::StmtKind::Decl(ref decl, _) => {
1597 try!(self.print_decl(&decl));
1599 ast::StmtKind::Expr(ref expr, _) => {
1600 try!(self.space_if_not_bol());
1601 try!(self.print_expr_outer_attr_style(&expr, false));
1602 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1603 try!(word(&mut self.s, ";"));
1606 ast::StmtKind::Semi(ref expr, _) => {
1607 try!(self.space_if_not_bol());
1608 try!(self.print_expr_outer_attr_style(&expr, false));
1609 try!(word(&mut self.s, ";"));
1611 ast::StmtKind::Mac(ref mac, style, ref attrs) => {
1612 try!(self.space_if_not_bol());
1613 try!(self.print_outer_attributes(attrs.as_attr_slice()));
1614 let delim = match style {
1615 ast::MacStmtStyle::Braces => token::Brace,
1618 try!(self.print_mac(&mac, delim));
1620 ast::MacStmtStyle::Braces => {}
1621 _ => try!(word(&mut self.s, ";")),
1625 self.maybe_print_trailing_comment(st.span, None)
1628 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1629 self.print_block_with_attrs(blk, &[])
1632 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1633 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1636 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1637 attrs: &[ast::Attribute])
1639 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1642 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1643 indented: usize) -> io::Result<()> {
1644 self.print_block_maybe_unclosed(blk, indented, &[], false)
1647 pub fn print_block_with_attrs(&mut self,
1649 attrs: &[ast::Attribute]) -> io::Result<()> {
1650 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1653 pub fn print_block_maybe_unclosed(&mut self,
1656 attrs: &[ast::Attribute],
1657 close_box: bool) -> io::Result<()> {
1659 BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")),
1660 BlockCheckMode::Default => ()
1662 try!(self.maybe_print_comment(blk.span.lo));
1663 try!(self.ann.pre(self, NodeBlock(blk)));
1666 try!(self.print_inner_attributes(attrs));
1668 for (i, st) in blk.stmts.iter().enumerate() {
1670 ast::StmtKind::Expr(ref expr, _) if i == blk.stmts.len() - 1 => {
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)));
1675 _ => try!(self.print_stmt(st)),
1679 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1680 self.ann.post(self, NodeBlock(blk))
1683 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1687 // "another else-if"
1688 ast::ExprKind::If(ref i, ref then, ref e) => {
1689 try!(self.cbox(INDENT_UNIT - 1));
1691 try!(word(&mut self.s, " else if "));
1692 try!(self.print_expr(&i));
1693 try!(space(&mut self.s));
1694 try!(self.print_block(&then));
1695 self.print_else(e.as_ref().map(|e| &**e))
1697 // "another else-if-let"
1698 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1699 try!(self.cbox(INDENT_UNIT - 1));
1701 try!(word(&mut self.s, " else if let "));
1702 try!(self.print_pat(&pat));
1703 try!(space(&mut self.s));
1704 try!(self.word_space("="));
1705 try!(self.print_expr(&expr));
1706 try!(space(&mut self.s));
1707 try!(self.print_block(&then));
1708 self.print_else(e.as_ref().map(|e| &**e))
1711 ast::ExprKind::Block(ref b) => {
1712 try!(self.cbox(INDENT_UNIT - 1));
1714 try!(word(&mut self.s, " else "));
1715 self.print_block(&b)
1717 // BLEAH, constraints would be great here
1719 panic!("print_if saw if with weird alternative");
1727 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1728 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1729 try!(self.head("if"));
1730 try!(self.print_expr(test));
1731 try!(space(&mut self.s));
1732 try!(self.print_block(blk));
1733 self.print_else(elseopt)
1736 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1737 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1738 try!(self.head("if let"));
1739 try!(self.print_pat(pat));
1740 try!(space(&mut self.s));
1741 try!(self.word_space("="));
1742 try!(self.print_expr(expr));
1743 try!(space(&mut self.s));
1744 try!(self.print_block(blk));
1745 self.print_else(elseopt)
1748 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1750 try!(self.print_path(&m.node.path, false, 0));
1751 try!(word(&mut self.s, "!"));
1753 token::Paren => try!(self.popen()),
1754 token::Bracket => try!(word(&mut self.s, "[")),
1756 try!(self.head(""));
1760 try!(self.print_tts(&m.node.tts));
1762 token::Paren => self.pclose(),
1763 token::Bracket => word(&mut self.s, "]"),
1764 token::Brace => self.bclose(m.span),
1769 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1771 try!(self.commasep_exprs(Inconsistent, args));
1775 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1776 binop: ast::BinOp) -> bool {
1777 match sub_expr.node {
1778 ast::ExprKind::Binary(ref sub_op, _, _) => {
1779 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1780 AssocOp::from_ast_binop(binop.node).precedence() {
1790 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1791 let needs_par = needs_parentheses(expr);
1795 try!(self.print_expr(expr));
1797 try!(self.pclose());
1802 fn print_expr_in_place(&mut self,
1804 expr: &ast::Expr) -> io::Result<()> {
1805 try!(self.print_expr_maybe_paren(place));
1806 try!(space(&mut self.s));
1807 try!(self.word_space("<-"));
1808 self.print_expr_maybe_paren(expr)
1811 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1812 attrs: &[Attribute]) -> io::Result<()> {
1813 try!(self.ibox(INDENT_UNIT));
1814 try!(word(&mut self.s, "["));
1815 try!(self.print_inner_attributes_inline(attrs));
1816 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1817 try!(word(&mut self.s, "]"));
1821 fn print_expr_repeat(&mut self,
1822 element: &ast::Expr,
1824 attrs: &[Attribute]) -> io::Result<()> {
1825 try!(self.ibox(INDENT_UNIT));
1826 try!(word(&mut self.s, "["));
1827 try!(self.print_inner_attributes_inline(attrs));
1828 try!(self.print_expr(element));
1829 try!(self.word_space(";"));
1830 try!(self.print_expr(count));
1831 try!(word(&mut self.s, "]"));
1835 fn print_expr_struct(&mut self,
1837 fields: &[ast::Field],
1838 wth: &Option<P<ast::Expr>>,
1839 attrs: &[Attribute]) -> io::Result<()> {
1840 try!(self.print_path(path, true, 0));
1841 try!(word(&mut self.s, "{"));
1842 try!(self.print_inner_attributes_inline(attrs));
1843 try!(self.commasep_cmnt(
1847 try!(s.ibox(INDENT_UNIT));
1848 try!(s.print_ident(field.ident.node));
1849 try!(s.word_space(":"));
1850 try!(s.print_expr(&field.expr));
1856 try!(self.ibox(INDENT_UNIT));
1857 if !fields.is_empty() {
1858 try!(word(&mut self.s, ","));
1859 try!(space(&mut self.s));
1861 try!(word(&mut self.s, ".."));
1862 try!(self.print_expr(&expr));
1865 _ => if !fields.is_empty() {
1866 try!(word(&mut self.s, ","))
1869 try!(word(&mut self.s, "}"));
1873 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1874 attrs: &[Attribute]) -> io::Result<()> {
1876 try!(self.print_inner_attributes_inline(attrs));
1877 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1878 if exprs.len() == 1 {
1879 try!(word(&mut self.s, ","));
1884 fn print_expr_call(&mut self,
1886 args: &[P<ast::Expr>]) -> io::Result<()> {
1887 try!(self.print_expr_maybe_paren(func));
1888 self.print_call_post(args)
1891 fn print_expr_method_call(&mut self,
1892 ident: ast::SpannedIdent,
1894 args: &[P<ast::Expr>]) -> io::Result<()> {
1895 let base_args = &args[1..];
1896 try!(self.print_expr(&args[0]));
1897 try!(word(&mut self.s, "."));
1898 try!(self.print_ident(ident.node));
1899 if !tys.is_empty() {
1900 try!(word(&mut self.s, "::<"));
1901 try!(self.commasep(Inconsistent, tys,
1902 |s, ty| s.print_type(&ty)));
1903 try!(word(&mut self.s, ">"));
1905 self.print_call_post(base_args)
1908 fn print_expr_binary(&mut self,
1911 rhs: &ast::Expr) -> io::Result<()> {
1912 if self.check_expr_bin_needs_paren(lhs, op) {
1913 try!(self.print_expr_maybe_paren(lhs));
1915 try!(self.print_expr(lhs));
1917 try!(space(&mut self.s));
1918 try!(self.word_space(op.node.to_string()));
1919 if self.check_expr_bin_needs_paren(rhs, op) {
1920 self.print_expr_maybe_paren(rhs)
1922 self.print_expr(rhs)
1926 fn print_expr_unary(&mut self,
1928 expr: &ast::Expr) -> io::Result<()> {
1929 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1930 self.print_expr_maybe_paren(expr)
1933 fn print_expr_addr_of(&mut self,
1934 mutability: ast::Mutability,
1935 expr: &ast::Expr) -> io::Result<()> {
1936 try!(word(&mut self.s, "&"));
1937 try!(self.print_mutability(mutability));
1938 self.print_expr_maybe_paren(expr)
1941 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1942 self.print_expr_outer_attr_style(expr, true)
1945 fn print_expr_outer_attr_style(&mut self,
1947 is_inline: bool) -> io::Result<()> {
1948 try!(self.maybe_print_comment(expr.span.lo));
1950 let attrs = expr.attrs.as_attr_slice();
1952 try!(self.print_outer_attributes_inline(attrs));
1954 try!(self.print_outer_attributes(attrs));
1957 try!(self.ibox(INDENT_UNIT));
1958 try!(self.ann.pre(self, NodeExpr(expr)));
1960 ast::ExprKind::Box(ref expr) => {
1961 try!(self.word_space("box"));
1962 try!(self.print_expr(expr));
1964 ast::ExprKind::InPlace(ref place, ref expr) => {
1965 try!(self.print_expr_in_place(place, expr));
1967 ast::ExprKind::Vec(ref exprs) => {
1968 try!(self.print_expr_vec(&exprs[..], attrs));
1970 ast::ExprKind::Repeat(ref element, ref count) => {
1971 try!(self.print_expr_repeat(&element, &count, attrs));
1973 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1974 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
1976 ast::ExprKind::Tup(ref exprs) => {
1977 try!(self.print_expr_tup(&exprs[..], attrs));
1979 ast::ExprKind::Call(ref func, ref args) => {
1980 try!(self.print_expr_call(&func, &args[..]));
1982 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
1983 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1985 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1986 try!(self.print_expr_binary(op, &lhs, &rhs));
1988 ast::ExprKind::Unary(op, ref expr) => {
1989 try!(self.print_expr_unary(op, &expr));
1991 ast::ExprKind::AddrOf(m, ref expr) => {
1992 try!(self.print_expr_addr_of(m, &expr));
1994 ast::ExprKind::Lit(ref lit) => {
1995 try!(self.print_literal(&lit));
1997 ast::ExprKind::Cast(ref expr, ref ty) => {
1998 if let ast::ExprKind::Cast(..) = expr.node {
1999 try!(self.print_expr(&expr));
2001 try!(self.print_expr_maybe_paren(&expr));
2003 try!(space(&mut self.s));
2004 try!(self.word_space("as"));
2005 try!(self.print_type(&ty));
2007 ast::ExprKind::Type(ref expr, ref ty) => {
2008 try!(self.print_expr(&expr));
2009 try!(self.word_space(":"));
2010 try!(self.print_type(&ty));
2012 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2013 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
2015 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2016 try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e)));
2018 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2019 if let Some(ident) = opt_ident {
2020 try!(self.print_ident(ident.node));
2021 try!(self.word_space(":"));
2023 try!(self.head("while"));
2024 try!(self.print_expr(&test));
2025 try!(space(&mut self.s));
2026 try!(self.print_block_with_attrs(&blk, attrs));
2028 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2029 if let Some(ident) = opt_ident {
2030 try!(self.print_ident(ident.node));
2031 try!(self.word_space(":"));
2033 try!(self.head("while let"));
2034 try!(self.print_pat(&pat));
2035 try!(space(&mut self.s));
2036 try!(self.word_space("="));
2037 try!(self.print_expr(&expr));
2038 try!(space(&mut self.s));
2039 try!(self.print_block_with_attrs(&blk, attrs));
2041 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2042 if let Some(ident) = opt_ident {
2043 try!(self.print_ident(ident.node));
2044 try!(self.word_space(":"));
2046 try!(self.head("for"));
2047 try!(self.print_pat(&pat));
2048 try!(space(&mut self.s));
2049 try!(self.word_space("in"));
2050 try!(self.print_expr(&iter));
2051 try!(space(&mut self.s));
2052 try!(self.print_block_with_attrs(&blk, attrs));
2054 ast::ExprKind::Loop(ref blk, opt_ident) => {
2055 if let Some(ident) = opt_ident {
2056 try!(self.print_ident(ident.node));
2057 try!(self.word_space(":"));
2059 try!(self.head("loop"));
2060 try!(space(&mut self.s));
2061 try!(self.print_block_with_attrs(&blk, attrs));
2063 ast::ExprKind::Match(ref expr, ref arms) => {
2064 try!(self.cbox(INDENT_UNIT));
2066 try!(self.word_nbsp("match"));
2067 try!(self.print_expr(&expr));
2068 try!(space(&mut self.s));
2070 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2072 try!(self.print_arm(arm));
2074 try!(self.bclose_(expr.span, INDENT_UNIT));
2076 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2077 try!(self.print_capture_clause(capture_clause));
2079 try!(self.print_fn_block_args(&decl));
2080 try!(space(&mut self.s));
2082 let default_return = match decl.output {
2083 ast::FunctionRetTy::Default(..) => true,
2087 match body.stmts.last().map(|stmt| &stmt.node) {
2088 Some(&ast::StmtKind::Expr(ref i_expr, _)) if default_return &&
2089 body.stmts.len() == 1 => {
2090 // we extract the block, so as not to create another set of boxes
2091 if let ast::ExprKind::Block(ref blk) = i_expr.node {
2092 try!(self.print_block_unclosed_with_attrs(
2094 i_expr.attrs.as_attr_slice()));
2096 // this is a bare expression
2097 try!(self.print_expr(&i_expr));
2098 try!(self.end()); // need to close a box
2101 _ => try!(self.print_block_unclosed(&body)),
2104 // a box will be closed by print_expr, but we didn't want an overall
2105 // wrapper so we closed the corresponding opening. so create an
2106 // empty box to satisfy the close.
2109 ast::ExprKind::Block(ref blk) => {
2110 // containing cbox, will be closed by print-block at }
2111 try!(self.cbox(INDENT_UNIT));
2112 // head-box, will be closed by print-block after {
2114 try!(self.print_block_with_attrs(&blk, attrs));
2116 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2117 try!(self.print_expr(&lhs));
2118 try!(space(&mut self.s));
2119 try!(self.word_space("="));
2120 try!(self.print_expr(&rhs));
2122 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2123 try!(self.print_expr(&lhs));
2124 try!(space(&mut self.s));
2125 try!(word(&mut self.s, op.node.to_string()));
2126 try!(self.word_space("="));
2127 try!(self.print_expr(&rhs));
2129 ast::ExprKind::Field(ref expr, id) => {
2130 try!(self.print_expr(&expr));
2131 try!(word(&mut self.s, "."));
2132 try!(self.print_ident(id.node));
2134 ast::ExprKind::TupField(ref expr, id) => {
2135 try!(self.print_expr(&expr));
2136 try!(word(&mut self.s, "."));
2137 try!(self.print_usize(id.node));
2139 ast::ExprKind::Index(ref expr, ref index) => {
2140 try!(self.print_expr(&expr));
2141 try!(word(&mut self.s, "["));
2142 try!(self.print_expr(&index));
2143 try!(word(&mut self.s, "]"));
2145 ast::ExprKind::Range(ref start, ref end, limits) => {
2146 if let &Some(ref e) = start {
2147 try!(self.print_expr(&e));
2149 if limits == ast::RangeLimits::HalfOpen {
2150 try!(word(&mut self.s, ".."));
2152 try!(word(&mut self.s, "..."));
2154 if let &Some(ref e) = end {
2155 try!(self.print_expr(&e));
2158 ast::ExprKind::Path(None, ref path) => {
2159 try!(self.print_path(path, true, 0))
2161 ast::ExprKind::Path(Some(ref qself), ref path) => {
2162 try!(self.print_qpath(path, qself, true))
2164 ast::ExprKind::Break(opt_ident) => {
2165 try!(word(&mut self.s, "break"));
2166 try!(space(&mut self.s));
2167 if let Some(ident) = opt_ident {
2168 try!(self.print_ident(ident.node));
2169 try!(space(&mut self.s));
2172 ast::ExprKind::Again(opt_ident) => {
2173 try!(word(&mut self.s, "continue"));
2174 try!(space(&mut self.s));
2175 if let Some(ident) = opt_ident {
2176 try!(self.print_ident(ident.node));
2177 try!(space(&mut self.s))
2180 ast::ExprKind::Ret(ref result) => {
2181 try!(word(&mut self.s, "return"));
2184 try!(word(&mut self.s, " "));
2185 try!(self.print_expr(&expr));
2190 ast::ExprKind::InlineAsm(ref a) => {
2191 try!(word(&mut self.s, "asm!"));
2193 try!(self.print_string(&a.asm, a.asm_str_style));
2194 try!(self.word_space(":"));
2196 try!(self.commasep(Inconsistent, &a.outputs,
2198 let mut ch = out.constraint.chars();
2200 Some('=') if out.is_rw => {
2201 try!(s.print_string(&format!("+{}", ch.as_str()),
2202 ast::StrStyle::Cooked))
2204 _ => try!(s.print_string(&out.constraint,
2205 ast::StrStyle::Cooked))
2208 try!(s.print_expr(&out.expr));
2212 try!(space(&mut self.s));
2213 try!(self.word_space(":"));
2215 try!(self.commasep(Inconsistent, &a.inputs,
2216 |s, &(ref co, ref o)| {
2217 try!(s.print_string(&co, ast::StrStyle::Cooked));
2219 try!(s.print_expr(&o));
2223 try!(space(&mut self.s));
2224 try!(self.word_space(":"));
2226 try!(self.commasep(Inconsistent, &a.clobbers,
2228 try!(s.print_string(&co, ast::StrStyle::Cooked));
2232 let mut options = vec!();
2234 options.push("volatile");
2237 options.push("alignstack");
2239 if a.dialect == ast::AsmDialect::Intel {
2240 options.push("intel");
2243 if !options.is_empty() {
2244 try!(space(&mut self.s));
2245 try!(self.word_space(":"));
2246 try!(self.commasep(Inconsistent, &options,
2248 try!(s.print_string(co, ast::StrStyle::Cooked));
2253 try!(self.pclose());
2255 ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2256 ast::ExprKind::Paren(ref e) => {
2258 try!(self.print_inner_attributes_inline(attrs));
2259 try!(self.print_expr(&e));
2260 try!(self.pclose());
2262 ast::ExprKind::Try(ref e) => {
2263 try!(self.print_expr(e));
2264 try!(word(&mut self.s, "?"))
2267 try!(self.ann.post(self, NodeExpr(expr)));
2271 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2272 try!(self.print_pat(&loc.pat));
2273 if let Some(ref ty) = loc.ty {
2274 try!(self.word_space(":"));
2275 try!(self.print_type(&ty));
2280 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2281 try!(self.maybe_print_comment(decl.span.lo));
2283 ast::DeclKind::Local(ref loc) => {
2284 try!(self.print_outer_attributes(loc.attrs.as_attr_slice()));
2285 try!(self.space_if_not_bol());
2286 try!(self.ibox(INDENT_UNIT));
2287 try!(self.word_nbsp("let"));
2289 try!(self.ibox(INDENT_UNIT));
2290 try!(self.print_local_decl(&loc));
2292 if let Some(ref init) = loc.init {
2294 try!(self.word_space("="));
2295 try!(self.print_expr(&init));
2297 try!(word(&mut self.s, ";"));
2300 ast::DeclKind::Item(ref item) => self.print_item(&item)
2304 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2305 try!(word(&mut self.s, &ident.name.as_str()));
2306 self.ann.post(self, NodeIdent(&ident))
2309 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2310 word(&mut self.s, &i.to_string())
2313 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2314 try!(word(&mut self.s, &name.as_str()));
2315 self.ann.post(self, NodeName(&name))
2318 pub fn print_for_decl(&mut self, loc: &ast::Local,
2319 coll: &ast::Expr) -> io::Result<()> {
2320 try!(self.print_local_decl(loc));
2321 try!(space(&mut self.s));
2322 try!(self.word_space("in"));
2323 self.print_expr(coll)
2326 fn print_path(&mut self,
2328 colons_before_params: bool,
2332 try!(self.maybe_print_comment(path.span.lo));
2334 let mut first = !path.global;
2335 for segment in &path.segments[..path.segments.len()-depth] {
2339 try!(word(&mut self.s, "::"))
2342 try!(self.print_ident(segment.identifier));
2344 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2350 fn print_qpath(&mut self,
2353 colons_before_params: bool)
2356 try!(word(&mut self.s, "<"));
2357 try!(self.print_type(&qself.ty));
2358 if qself.position > 0 {
2359 try!(space(&mut self.s));
2360 try!(self.word_space("as"));
2361 let depth = path.segments.len() - qself.position;
2362 try!(self.print_path(&path, false, depth));
2364 try!(word(&mut self.s, ">"));
2365 try!(word(&mut self.s, "::"));
2366 let item_segment = path.segments.last().unwrap();
2367 try!(self.print_ident(item_segment.identifier));
2368 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2371 fn print_path_parameters(&mut self,
2372 parameters: &ast::PathParameters,
2373 colons_before_params: bool)
2376 if parameters.is_empty() {
2380 if colons_before_params {
2381 try!(word(&mut self.s, "::"))
2385 ast::PathParameters::AngleBracketed(ref data) => {
2386 try!(word(&mut self.s, "<"));
2388 let mut comma = false;
2389 for lifetime in &data.lifetimes {
2391 try!(self.word_space(","))
2393 try!(self.print_lifetime(lifetime));
2397 if !data.types.is_empty() {
2399 try!(self.word_space(","))
2404 |s, ty| s.print_type(&ty)));
2408 for binding in data.bindings.iter() {
2410 try!(self.word_space(","))
2412 try!(self.print_ident(binding.ident));
2413 try!(space(&mut self.s));
2414 try!(self.word_space("="));
2415 try!(self.print_type(&binding.ty));
2419 try!(word(&mut self.s, ">"))
2422 ast::PathParameters::Parenthesized(ref data) => {
2423 try!(word(&mut self.s, "("));
2427 |s, ty| s.print_type(&ty)));
2428 try!(word(&mut self.s, ")"));
2433 try!(self.space_if_not_bol());
2434 try!(self.word_space("->"));
2435 try!(self.print_type(&ty));
2444 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2445 try!(self.maybe_print_comment(pat.span.lo));
2446 try!(self.ann.pre(self, NodePat(pat)));
2447 /* Pat isn't normalized, but the beauty of it
2448 is that it doesn't matter */
2450 PatKind::Wild => try!(word(&mut self.s, "_")),
2451 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2452 match binding_mode {
2453 ast::BindingMode::ByRef(mutbl) => {
2454 try!(self.word_nbsp("ref"));
2455 try!(self.print_mutability(mutbl));
2457 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2458 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2459 try!(self.word_nbsp("mut"));
2462 try!(self.print_ident(path1.node));
2463 if let Some(ref p) = *sub {
2464 try!(word(&mut self.s, "@"));
2465 try!(self.print_pat(&p));
2468 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2469 try!(self.print_path(path, true, 0));
2471 if let Some(ddpos) = ddpos {
2472 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2474 try!(self.word_space(","));
2476 try!(word(&mut self.s, ".."));
2477 if ddpos != elts.len() {
2478 try!(word(&mut self.s, ","));
2479 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2482 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2484 try!(self.pclose());
2486 PatKind::Path(ref path) => {
2487 try!(self.print_path(path, true, 0));
2489 PatKind::QPath(ref qself, ref path) => {
2490 try!(self.print_qpath(path, qself, false));
2492 PatKind::Struct(ref path, ref fields, etc) => {
2493 try!(self.print_path(path, true, 0));
2495 try!(self.word_space("{"));
2496 try!(self.commasep_cmnt(
2497 Consistent, &fields[..],
2499 try!(s.cbox(INDENT_UNIT));
2500 if !f.node.is_shorthand {
2501 try!(s.print_ident(f.node.ident));
2502 try!(s.word_nbsp(":"));
2504 try!(s.print_pat(&f.node.pat));
2507 |f| f.node.pat.span));
2509 if !fields.is_empty() { try!(self.word_space(",")); }
2510 try!(word(&mut self.s, ".."));
2512 try!(space(&mut self.s));
2513 try!(word(&mut self.s, "}"));
2515 PatKind::Tuple(ref elts, ddpos) => {
2517 if let Some(ddpos) = ddpos {
2518 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2520 try!(self.word_space(","));
2522 try!(word(&mut self.s, ".."));
2523 if ddpos != elts.len() {
2524 try!(word(&mut self.s, ","));
2525 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2528 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2529 if elts.len() == 1 {
2530 try!(word(&mut self.s, ","));
2533 try!(self.pclose());
2535 PatKind::Box(ref inner) => {
2536 try!(word(&mut self.s, "box "));
2537 try!(self.print_pat(&inner));
2539 PatKind::Ref(ref inner, mutbl) => {
2540 try!(word(&mut self.s, "&"));
2541 if mutbl == ast::Mutability::Mutable {
2542 try!(word(&mut self.s, "mut "));
2544 try!(self.print_pat(&inner));
2546 PatKind::Lit(ref e) => try!(self.print_expr(&**e)),
2547 PatKind::Range(ref begin, ref end) => {
2548 try!(self.print_expr(&begin));
2549 try!(space(&mut self.s));
2550 try!(word(&mut self.s, "..."));
2551 try!(self.print_expr(&end));
2553 PatKind::Vec(ref before, ref slice, ref after) => {
2554 try!(word(&mut self.s, "["));
2555 try!(self.commasep(Inconsistent,
2557 |s, p| s.print_pat(&p)));
2558 if let Some(ref p) = *slice {
2559 if !before.is_empty() { try!(self.word_space(",")); }
2560 if p.node != PatKind::Wild {
2561 try!(self.print_pat(&p));
2563 try!(word(&mut self.s, ".."));
2564 if !after.is_empty() { try!(self.word_space(",")); }
2566 try!(self.commasep(Inconsistent,
2568 |s, p| s.print_pat(&p)));
2569 try!(word(&mut self.s, "]"));
2571 PatKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2573 self.ann.post(self, NodePat(pat))
2576 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2577 // I have no idea why this check is necessary, but here it
2579 if arm.attrs.is_empty() {
2580 try!(space(&mut self.s));
2582 try!(self.cbox(INDENT_UNIT));
2584 try!(self.print_outer_attributes(&arm.attrs));
2585 let mut first = true;
2586 for p in &arm.pats {
2590 try!(space(&mut self.s));
2591 try!(self.word_space("|"));
2593 try!(self.print_pat(&p));
2595 try!(space(&mut self.s));
2596 if let Some(ref e) = arm.guard {
2597 try!(self.word_space("if"));
2598 try!(self.print_expr(&e));
2599 try!(space(&mut self.s));
2601 try!(self.word_space("=>"));
2603 match arm.body.node {
2604 ast::ExprKind::Block(ref blk) => {
2605 // the block will close the pattern's ibox
2606 try!(self.print_block_unclosed_indent(&blk, INDENT_UNIT));
2608 // If it is a user-provided unsafe block, print a comma after it
2609 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2610 try!(word(&mut self.s, ","));
2614 try!(self.end()); // close the ibox for the pattern
2615 try!(self.print_expr(&arm.body));
2616 try!(word(&mut self.s, ","));
2619 self.end() // close enclosing cbox
2622 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2623 match explicit_self.node {
2624 SelfKind::Value(m) => {
2625 try!(self.print_mutability(m));
2626 word(&mut self.s, "self")
2628 SelfKind::Region(ref lt, m) => {
2629 try!(word(&mut self.s, "&"));
2630 try!(self.print_opt_lifetime(lt));
2631 try!(self.print_mutability(m));
2632 word(&mut self.s, "self")
2634 SelfKind::Explicit(ref typ, m) => {
2635 try!(self.print_mutability(m));
2636 try!(word(&mut self.s, "self"));
2637 try!(self.word_space(":"));
2638 self.print_type(&typ)
2643 pub fn print_fn(&mut self,
2645 unsafety: ast::Unsafety,
2646 constness: ast::Constness,
2648 name: Option<ast::Ident>,
2649 generics: &ast::Generics,
2650 vis: &ast::Visibility) -> io::Result<()> {
2651 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2653 if let Some(name) = name {
2655 try!(self.print_ident(name));
2657 try!(self.print_generics(generics));
2658 try!(self.print_fn_args_and_ret(decl));
2659 self.print_where_clause(&generics.where_clause)
2662 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2665 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false)));
2667 try!(word(&mut self.s, ", ..."));
2669 try!(self.pclose());
2671 self.print_fn_output(decl)
2674 pub fn print_fn_block_args(
2678 try!(word(&mut self.s, "|"));
2679 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true)));
2680 try!(word(&mut self.s, "|"));
2682 if let ast::FunctionRetTy::Default(..) = decl.output {
2686 try!(self.space_if_not_bol());
2687 try!(self.word_space("->"));
2689 ast::FunctionRetTy::Ty(ref ty) => {
2690 try!(self.print_type(&ty));
2691 self.maybe_print_comment(ty.span.lo)
2693 ast::FunctionRetTy::Default(..) => unreachable!(),
2694 ast::FunctionRetTy::None(span) => {
2695 try!(self.word_nbsp("!"));
2696 self.maybe_print_comment(span.lo)
2701 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2703 match capture_clause {
2704 ast::CaptureBy::Value => self.word_space("move"),
2705 ast::CaptureBy::Ref => Ok(()),
2709 pub fn print_bounds(&mut self,
2711 bounds: &[ast::TyParamBound])
2713 if !bounds.is_empty() {
2714 try!(word(&mut self.s, prefix));
2715 let mut first = true;
2716 for bound in bounds {
2721 try!(self.word_space("+"));
2725 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2726 self.print_poly_trait_ref(tref)
2728 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2729 try!(word(&mut self.s, "?"));
2730 self.print_poly_trait_ref(tref)
2732 RegionTyParamBound(ref lt) => {
2733 self.print_lifetime(lt)
2743 pub fn print_lifetime(&mut self,
2744 lifetime: &ast::Lifetime)
2747 self.print_name(lifetime.name)
2750 pub fn print_lifetime_def(&mut self,
2751 lifetime: &ast::LifetimeDef)
2754 try!(self.print_lifetime(&lifetime.lifetime));
2756 for v in &lifetime.bounds {
2757 try!(word(&mut self.s, sep));
2758 try!(self.print_lifetime(v));
2764 pub fn print_generics(&mut self,
2765 generics: &ast::Generics)
2768 let total = generics.lifetimes.len() + generics.ty_params.len();
2773 try!(word(&mut self.s, "<"));
2775 let mut ints = Vec::new();
2780 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2781 if idx < generics.lifetimes.len() {
2782 let lifetime = &generics.lifetimes[idx];
2783 s.print_lifetime_def(lifetime)
2785 let idx = idx - generics.lifetimes.len();
2786 let param = &generics.ty_params[idx];
2787 s.print_ty_param(param)
2791 try!(word(&mut self.s, ">"));
2795 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2796 try!(self.print_ident(param.ident));
2797 try!(self.print_bounds(":", ¶m.bounds));
2798 match param.default {
2799 Some(ref default) => {
2800 try!(space(&mut self.s));
2801 try!(self.word_space("="));
2802 self.print_type(&default)
2808 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2810 if where_clause.predicates.is_empty() {
2814 try!(space(&mut self.s));
2815 try!(self.word_space("where"));
2817 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2819 try!(self.word_space(","));
2823 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2827 try!(self.print_formal_lifetime_list(bound_lifetimes));
2828 try!(self.print_type(&bounded_ty));
2829 try!(self.print_bounds(":", bounds));
2831 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2834 try!(self.print_lifetime(lifetime));
2835 try!(word(&mut self.s, ":"));
2837 for (i, bound) in bounds.iter().enumerate() {
2838 try!(self.print_lifetime(bound));
2841 try!(word(&mut self.s, ":"));
2845 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2846 try!(self.print_path(path, false, 0));
2847 try!(space(&mut self.s));
2848 try!(self.word_space("="));
2849 try!(self.print_type(&ty));
2857 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2859 ast::ViewPathSimple(ident, ref path) => {
2860 try!(self.print_path(path, false, 0));
2862 if path.segments.last().unwrap().identifier.name !=
2864 try!(space(&mut self.s));
2865 try!(self.word_space("as"));
2866 try!(self.print_ident(ident));
2872 ast::ViewPathGlob(ref path) => {
2873 try!(self.print_path(path, false, 0));
2874 word(&mut self.s, "::*")
2877 ast::ViewPathList(ref path, ref idents) => {
2878 if path.segments.is_empty() {
2879 try!(word(&mut self.s, "{"));
2881 try!(self.print_path(path, false, 0));
2882 try!(word(&mut self.s, "::{"));
2884 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2886 ast::PathListItemKind::Ident { name, rename, .. } => {
2887 try!(s.print_ident(name));
2888 if let Some(ident) = rename {
2889 try!(space(&mut s.s));
2890 try!(s.word_space("as"));
2891 try!(s.print_ident(ident));
2895 ast::PathListItemKind::Mod { rename, .. } => {
2896 try!(word(&mut s.s, "self"));
2897 if let Some(ident) = rename {
2898 try!(space(&mut s.s));
2899 try!(s.word_space("as"));
2900 try!(s.print_ident(ident));
2906 word(&mut self.s, "}")
2911 pub fn print_mutability(&mut self,
2912 mutbl: ast::Mutability) -> io::Result<()> {
2914 ast::Mutability::Mutable => self.word_nbsp("mut"),
2915 ast::Mutability::Immutable => Ok(()),
2919 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2920 try!(self.print_mutability(mt.mutbl));
2921 self.print_type(&mt.ty)
2924 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2925 try!(self.ibox(INDENT_UNIT));
2926 match input.ty.node {
2927 ast::TyKind::Infer if is_closure => try!(self.print_pat(&input.pat)),
2929 if let Some(eself) = input.to_self() {
2930 try!(self.print_explicit_self(&eself));
2932 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2933 ident.node.name == keywords::Invalid.name()
2938 try!(self.print_pat(&input.pat));
2939 try!(word(&mut self.s, ":"));
2940 try!(space(&mut self.s));
2942 try!(self.print_type(&input.ty));
2949 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2950 if let ast::FunctionRetTy::Default(..) = decl.output {
2954 try!(self.space_if_not_bol());
2955 try!(self.ibox(INDENT_UNIT));
2956 try!(self.word_space("->"));
2958 ast::FunctionRetTy::None(_) =>
2959 try!(self.word_nbsp("!")),
2960 ast::FunctionRetTy::Default(..) => unreachable!(),
2961 ast::FunctionRetTy::Ty(ref ty) =>
2962 try!(self.print_type(&ty))
2967 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2972 pub fn print_ty_fn(&mut self,
2974 unsafety: ast::Unsafety,
2976 name: Option<ast::Ident>,
2977 generics: &ast::Generics)
2979 try!(self.ibox(INDENT_UNIT));
2980 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2981 try!(word(&mut self.s, "for"));
2982 try!(self.print_generics(generics));
2984 let generics = ast::Generics {
2985 lifetimes: Vec::new(),
2986 ty_params: P::new(),
2987 where_clause: ast::WhereClause {
2988 id: ast::DUMMY_NODE_ID,
2989 predicates: Vec::new(),
2992 try!(self.print_fn(decl,
2994 ast::Constness::NotConst,
2998 &ast::Visibility::Inherited));
3002 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
3003 next_pos: Option<BytePos>)
3005 let cm = match self.cm {
3009 if let Some(ref cmnt) = self.next_comment() {
3010 if (*cmnt).style != comments::Trailing { return Ok(()) }
3011 let span_line = cm.lookup_char_pos(span.hi);
3012 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3013 let mut next = (*cmnt).pos + BytePos(1);
3014 if let Some(p) = next_pos {
3017 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3018 span_line.line == comment_line.line {
3019 self.print_comment(cmnt)?;
3020 self.cur_cmnt_and_lit.cur_cmnt += 1;
3026 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3027 // If there aren't any remaining comments, then we need to manually
3028 // make sure there is a line break at the end.
3029 if self.next_comment().is_none() {
3030 try!(hardbreak(&mut self.s));
3033 match self.next_comment() {
3035 try!(self.print_comment(cmnt));
3036 self.cur_cmnt_and_lit.cur_cmnt += 1;
3044 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3045 opt_abi: Option<Abi>)
3048 Some(Abi::Rust) => Ok(()),
3050 try!(self.word_nbsp("extern"));
3051 self.word_nbsp(&abi.to_string())
3057 pub fn print_extern_opt_abi(&mut self,
3058 opt_abi: Option<Abi>) -> io::Result<()> {
3061 try!(self.word_nbsp("extern"));
3062 self.word_nbsp(&abi.to_string())
3068 pub fn print_fn_header_info(&mut self,
3069 unsafety: ast::Unsafety,
3070 constness: ast::Constness,
3072 vis: &ast::Visibility) -> io::Result<()> {
3073 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3076 ast::Constness::NotConst => {}
3077 ast::Constness::Const => try!(self.word_nbsp("const"))
3080 try!(self.print_unsafety(unsafety));
3082 if abi != Abi::Rust {
3083 try!(self.word_nbsp("extern"));
3084 try!(self.word_nbsp(&abi.to_string()));
3087 word(&mut self.s, "fn")
3090 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3092 ast::Unsafety::Normal => Ok(()),
3093 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3098 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3109 fn test_fun_to_string() {
3110 let abba_ident = token::str_to_ident("abba");
3112 let decl = ast::FnDecl {
3114 output: ast::FunctionRetTy::Default(codemap::DUMMY_SP),
3117 let generics = ast::Generics::default();
3118 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3119 ast::Constness::NotConst,
3120 abba_ident, &generics),
3125 fn test_variant_to_string() {
3126 let ident = token::str_to_ident("principal_skinner");
3128 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3131 // making this up as I go.... ?
3132 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3136 let varstr = variant_to_string(&var);
3137 assert_eq!(varstr, "principal_skinner");