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::Pound => "#".to_string(),
246 token::Dollar => "$".to_string(),
247 token::Question => "?".to_string(),
250 token::Literal(lit, suf) => {
251 let mut out = match lit {
252 token::Byte(b) => format!("b'{}'", b),
253 token::Char(c) => format!("'{}'", c),
254 token::Float(c) => c.to_string(),
255 token::Integer(c) => c.to_string(),
256 token::Str_(s) => format!("\"{}\"", s),
257 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
258 delim=repeat("#", n),
260 token::ByteStr(v) => format!("b\"{}\"", v),
261 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
262 delim=repeat("#", n),
266 if let Some(s) = suf {
267 out.push_str(&s.as_str())
273 /* Name components */
274 token::Ident(s) => s.to_string(),
275 token::Lifetime(s) => s.to_string(),
276 token::Underscore => "_".to_string(),
279 token::DocComment(s) => s.to_string(),
280 token::SubstNt(s) => format!("${}", s),
281 token::MatchNt(s, t) => format!("${}:{}", s, t),
282 token::Eof => "<eof>".to_string(),
283 token::Whitespace => " ".to_string(),
284 token::Comment => "/* */".to_string(),
285 token::Shebang(s) => format!("/* shebang: {}*/", s),
287 token::SpecialVarNt(var) => format!("${}", var.as_str()),
289 token::Interpolated(ref nt) => match *nt {
290 token::NtExpr(ref e) => expr_to_string(&e),
291 token::NtMeta(ref e) => meta_item_to_string(&e),
292 token::NtTy(ref e) => ty_to_string(&e),
293 token::NtPath(ref e) => path_to_string(&e),
294 token::NtItem(ref e) => item_to_string(&e),
295 token::NtBlock(ref e) => block_to_string(&e),
296 token::NtStmt(ref e) => stmt_to_string(&e),
297 token::NtPat(ref e) => pat_to_string(&e),
298 token::NtIdent(ref e) => ident_to_string(e.node),
299 token::NtTT(ref e) => tt_to_string(&e),
300 token::NtArm(ref e) => arm_to_string(&e),
301 token::NtImplItem(ref e) => impl_item_to_string(&e),
302 token::NtTraitItem(ref e) => trait_item_to_string(&e),
303 token::NtGenerics(ref e) => generics_to_string(&e),
304 token::NtWhereClause(ref e) => where_clause_to_string(&e),
305 token::NtArg(ref e) => arg_to_string(&e),
310 pub fn ty_to_string(ty: &ast::Ty) -> String {
311 to_string(|s| s.print_type(ty))
314 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
315 to_string(|s| s.print_bounds("", bounds))
318 pub fn pat_to_string(pat: &ast::Pat) -> String {
319 to_string(|s| s.print_pat(pat))
322 pub fn arm_to_string(arm: &ast::Arm) -> String {
323 to_string(|s| s.print_arm(arm))
326 pub fn expr_to_string(e: &ast::Expr) -> String {
327 to_string(|s| s.print_expr(e))
330 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
331 to_string(|s| s.print_lifetime(e))
334 pub fn tt_to_string(tt: &tokenstream::TokenTree) -> String {
335 to_string(|s| s.print_tt(tt))
338 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
339 to_string(|s| s.print_tts(tts))
342 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
343 to_string(|s| s.print_stmt(stmt))
346 pub fn attr_to_string(attr: &ast::Attribute) -> String {
347 to_string(|s| s.print_attribute(attr))
350 pub fn item_to_string(i: &ast::Item) -> String {
351 to_string(|s| s.print_item(i))
354 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
355 to_string(|s| s.print_impl_item(i))
358 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
359 to_string(|s| s.print_trait_item(i))
362 pub fn generics_to_string(generics: &ast::Generics) -> String {
363 to_string(|s| s.print_generics(generics))
366 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
367 to_string(|s| s.print_where_clause(i))
370 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
371 to_string(|s| s.print_fn_block_args(p))
374 pub fn path_to_string(p: &ast::Path) -> String {
375 to_string(|s| s.print_path(p, false, 0))
378 pub fn ident_to_string(id: ast::Ident) -> String {
379 to_string(|s| s.print_ident(id))
382 pub fn fun_to_string(decl: &ast::FnDecl,
383 unsafety: ast::Unsafety,
384 constness: ast::Constness,
386 generics: &ast::Generics)
390 try!(s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
391 generics, &ast::Visibility::Inherited));
392 try!(s.end()); // Close the head box
393 s.end() // Close the outer box
397 pub fn block_to_string(blk: &ast::Block) -> String {
399 // containing cbox, will be closed by print-block at }
400 try!(s.cbox(INDENT_UNIT));
401 // head-ibox, will be closed by print-block after {
407 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
408 to_string(|s| s.print_meta_item(mi))
411 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
412 to_string(|s| s.print_attribute(attr))
415 pub fn lit_to_string(l: &ast::Lit) -> String {
416 to_string(|s| s.print_literal(l))
419 pub fn variant_to_string(var: &ast::Variant) -> String {
420 to_string(|s| s.print_variant(var))
423 pub fn arg_to_string(arg: &ast::Arg) -> String {
424 to_string(|s| s.print_arg(arg, false))
427 pub fn mac_to_string(arg: &ast::Mac) -> String {
428 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
431 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
433 ast::Visibility::Public => format!("pub {}", s),
434 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
435 ast::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
436 ast::Visibility::Inherited => s.to_string()
440 fn needs_parentheses(expr: &ast::Expr) -> bool {
442 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
443 ast::ExprKind::Closure(..) |
444 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
445 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
450 pub trait PrintState<'a> {
451 fn writer(&mut self) -> &mut pp::Printer<'a>;
452 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
453 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
454 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
455 fn literals(&self) -> &Option<Vec<comments::Literal>>;
457 fn word_space(&mut self, w: &str) -> io::Result<()> {
458 try!(word(self.writer(), w));
462 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
464 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
466 fn is_begin(&mut self) -> bool {
467 match self.writer().last_token() {
468 pp::Token::Begin(_) => true,
473 fn is_end(&mut self) -> bool {
474 match self.writer().last_token() {
475 pp::Token::End => true,
480 // is this the beginning of a line?
481 fn is_bol(&mut self) -> bool {
482 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
485 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
487 try!(hardbreak(self.writer()))
493 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
494 self.boxes().push(b);
495 pp::rbox(self.writer(), u, b)
498 fn ibox(&mut self, u: usize) -> io::Result<()> {
499 self.boxes().push(pp::Breaks::Inconsistent);
500 pp::ibox(self.writer(), u)
503 fn end(&mut self) -> io::Result<()> {
504 self.boxes().pop().unwrap();
505 pp::end(self.writer())
508 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
509 where F: FnMut(&mut Self, &T) -> io::Result<()>,
511 try!(self.rbox(0, b));
512 let mut first = true;
514 if first { first = false; } else { try!(self.word_space(",")); }
520 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
521 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
523 let mut result = None;
525 if let &Some(ref lits) = self.literals()
527 while cur_lit < lits.len() {
528 let ltrl = (*lits)[cur_lit].clone();
529 if ltrl.pos > pos { break; }
538 self.cur_cmnt_and_lit().cur_lit = cur_lit;
542 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
544 match self.next_comment() {
546 if (*cmnt).pos < pos {
547 try!(self.print_comment(cmnt));
548 self.cur_cmnt_and_lit().cur_cmnt += 1;
557 fn print_comment(&mut self,
558 cmnt: &comments::Comment) -> io::Result<()> {
561 assert_eq!(cmnt.lines.len(), 1);
562 try!(zerobreak(self.writer()));
563 try!(word(self.writer(), &cmnt.lines[0]));
564 zerobreak(self.writer())
566 comments::Isolated => {
567 try!(self.hardbreak_if_not_bol());
568 for line in &cmnt.lines {
569 // Don't print empty lines because they will end up as trailing
571 if !line.is_empty() {
572 try!(word(self.writer(), &line[..]));
574 try!(hardbreak(self.writer()));
578 comments::Trailing => {
579 try!(word(self.writer(), " "));
580 if cmnt.lines.len() == 1 {
581 try!(word(self.writer(), &cmnt.lines[0]));
582 hardbreak(self.writer())
585 for line in &cmnt.lines {
586 if !line.is_empty() {
587 try!(word(self.writer(), &line[..]));
589 try!(hardbreak(self.writer()));
594 comments::BlankLine => {
595 // We need to do at least one, possibly two hardbreaks.
596 let is_semi = match self.writer().last_token() {
597 pp::Token::String(s, _) => ";" == s,
600 if is_semi || self.is_begin() || self.is_end() {
601 try!(hardbreak(self.writer()));
603 hardbreak(self.writer())
608 fn next_comment(&mut self) -> Option<comments::Comment> {
609 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
610 match *self.comments() {
612 if cur_cmnt < cmnts.len() {
613 Some(cmnts[cur_cmnt].clone())
622 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
623 try!(self.maybe_print_comment(lit.span.lo));
624 match self.next_lit(lit.span.lo) {
626 return word(self.writer(), &(*ltrl).lit);
631 ast::LitKind::Str(ref st, style) => self.print_string(&st, style),
632 ast::LitKind::Byte(byte) => {
633 let mut res = String::from("b'");
634 res.extend(ascii::escape_default(byte).map(|c| c as char));
636 word(self.writer(), &res[..])
638 ast::LitKind::Char(ch) => {
639 let mut res = String::from("'");
640 res.extend(ch.escape_default());
642 word(self.writer(), &res[..])
644 ast::LitKind::Int(i, t) => {
646 ast::LitIntType::Signed(st) => {
648 &st.val_to_string(i as i64))
650 ast::LitIntType::Unsigned(ut) => {
651 word(self.writer(), &ut.val_to_string(i))
653 ast::LitIntType::Unsuffixed => {
654 word(self.writer(), &format!("{}", i))
658 ast::LitKind::Float(ref f, t) => {
665 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
666 ast::LitKind::Bool(val) => {
667 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
669 ast::LitKind::ByteStr(ref v) => {
670 let mut escaped: String = String::new();
671 for &ch in v.iter() {
672 escaped.extend(ascii::escape_default(ch)
673 .map(|c| c as char));
675 word(self.writer(), &format!("b\"{}\"", escaped))
680 fn print_string(&mut self, st: &str,
681 style: ast::StrStyle) -> io::Result<()> {
682 let st = match style {
683 ast::StrStyle::Cooked => {
684 (format!("\"{}\"", st.escape_default()))
686 ast::StrStyle::Raw(n) => {
687 (format!("r{delim}\"{string}\"{delim}",
688 delim=repeat("#", n),
692 word(self.writer(), &st[..])
695 fn print_inner_attributes(&mut self,
696 attrs: &[ast::Attribute]) -> io::Result<()> {
697 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
700 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
701 attrs: &[ast::Attribute])
703 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
706 fn print_outer_attributes(&mut self,
707 attrs: &[ast::Attribute]) -> io::Result<()> {
708 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
711 fn print_inner_attributes_inline(&mut self,
712 attrs: &[ast::Attribute]) -> io::Result<()> {
713 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
716 fn print_outer_attributes_inline(&mut self,
717 attrs: &[ast::Attribute]) -> io::Result<()> {
718 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
721 fn print_either_attributes(&mut self,
722 attrs: &[ast::Attribute],
723 kind: ast::AttrStyle,
725 trailing_hardbreak: bool) -> io::Result<()> {
728 if attr.node.style == kind {
729 try!(self.print_attribute_inline(attr, is_inline));
736 if count > 0 && trailing_hardbreak && !is_inline {
737 try!(self.hardbreak_if_not_bol());
742 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
743 self.print_attribute_inline(attr, false)
746 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
747 is_inline: bool) -> io::Result<()> {
749 try!(self.hardbreak_if_not_bol());
751 try!(self.maybe_print_comment(attr.span.lo));
752 if attr.node.is_sugared_doc {
753 try!(word(self.writer(), &attr.value_str().unwrap()));
754 hardbreak(self.writer())
756 match attr.node.style {
757 ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
758 ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
760 try!(self.print_meta_item(&attr.meta()));
761 word(self.writer(), "]")
765 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
766 try!(self.ibox(INDENT_UNIT));
768 ast::MetaItemKind::Word(ref name) => {
769 try!(word(self.writer(), &name));
771 ast::MetaItemKind::NameValue(ref name, ref value) => {
772 try!(self.word_space(&name[..]));
773 try!(self.word_space("="));
774 try!(self.print_literal(value));
776 ast::MetaItemKind::List(ref name, ref items) => {
777 try!(word(self.writer(), &name));
779 try!(self.commasep(Consistent,
781 |s, i| s.print_meta_item(&i)));
788 fn space_if_not_bol(&mut self) -> io::Result<()> {
789 if !self.is_bol() { try!(space(self.writer())); }
793 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
796 impl<'a> PrintState<'a> for State<'a> {
797 fn writer(&mut self) -> &mut pp::Printer<'a> {
801 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
805 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
809 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
810 &mut self.cur_cmnt_and_lit
813 fn literals(&self) -> &Option<Vec<comments::Literal>> {
819 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
820 self.boxes.push(pp::Breaks::Consistent);
821 pp::cbox(&mut self.s, u)
824 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
825 try!(word(&mut self.s, w));
829 pub fn head(&mut self, w: &str) -> io::Result<()> {
830 // outer-box is consistent
831 try!(self.cbox(INDENT_UNIT));
832 // head-box is inconsistent
833 try!(self.ibox(w.len() + 1));
834 // keyword that starts the head
836 try!(self.word_nbsp(w));
841 pub fn bopen(&mut self) -> io::Result<()> {
842 try!(word(&mut self.s, "{"));
843 self.end() // close the head-box
846 pub fn bclose_(&mut self, span: syntax_pos::Span,
847 indented: usize) -> io::Result<()> {
848 self.bclose_maybe_open(span, indented, true)
850 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
851 indented: usize, close_box: bool) -> io::Result<()> {
852 try!(self.maybe_print_comment(span.hi));
853 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
854 try!(word(&mut self.s, "}"));
856 try!(self.end()); // close the outer-box
860 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
861 self.bclose_(span, INDENT_UNIT)
864 pub fn in_cbox(&self) -> bool {
865 match self.boxes.last() {
866 Some(&last_box) => last_box == pp::Breaks::Consistent,
871 pub fn break_offset_if_not_bol(&mut self, n: usize,
872 off: isize) -> io::Result<()> {
874 break_offset(&mut self.s, n, off)
876 if off != 0 && self.s.last_token().is_hardbreak_tok() {
877 // We do something pretty sketchy here: tuck the nonzero
878 // offset-adjustment we were going to deposit along with the
879 // break into the previous hardbreak.
880 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
886 // Synthesizes a comment that was not textually present in the original source
888 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
889 try!(word(&mut self.s, "/*"));
890 try!(space(&mut self.s));
891 try!(word(&mut self.s, &text[..]));
892 try!(space(&mut self.s));
893 word(&mut self.s, "*/")
898 pub fn commasep_cmnt<T, F, G>(&mut self,
902 mut get_span: G) -> io::Result<()> where
903 F: FnMut(&mut State, &T) -> io::Result<()>,
904 G: FnMut(&T) -> syntax_pos::Span,
906 try!(self.rbox(0, b));
907 let len = elts.len();
910 try!(self.maybe_print_comment(get_span(elt).hi));
914 try!(word(&mut self.s, ","));
915 try!(self.maybe_print_trailing_comment(get_span(elt),
916 Some(get_span(&elts[i]).hi)));
917 try!(self.space_if_not_bol());
923 pub fn commasep_exprs(&mut self, b: Breaks,
924 exprs: &[P<ast::Expr>]) -> io::Result<()> {
925 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
928 pub fn print_mod(&mut self, _mod: &ast::Mod,
929 attrs: &[ast::Attribute]) -> io::Result<()> {
930 try!(self.print_inner_attributes(attrs));
931 for item in &_mod.items {
932 try!(self.print_item(&item));
937 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
938 attrs: &[ast::Attribute]) -> io::Result<()> {
939 try!(self.print_inner_attributes(attrs));
940 for item in &nmod.items {
941 try!(self.print_foreign_item(item));
946 pub fn print_opt_lifetime(&mut self,
947 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
948 if let Some(l) = *lifetime {
949 try!(self.print_lifetime(&l));
955 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
956 try!(self.maybe_print_comment(ty.span.lo));
959 ast::TyKind::Vec(ref ty) => {
960 try!(word(&mut self.s, "["));
961 try!(self.print_type(&ty));
962 try!(word(&mut self.s, "]"));
964 ast::TyKind::Ptr(ref mt) => {
965 try!(word(&mut self.s, "*"));
967 ast::Mutability::Mutable => try!(self.word_nbsp("mut")),
968 ast::Mutability::Immutable => try!(self.word_nbsp("const")),
970 try!(self.print_type(&mt.ty));
972 ast::TyKind::Rptr(ref lifetime, ref mt) => {
973 try!(word(&mut self.s, "&"));
974 try!(self.print_opt_lifetime(lifetime));
975 try!(self.print_mt(mt));
977 ast::TyKind::Tup(ref elts) => {
979 try!(self.commasep(Inconsistent, &elts[..],
980 |s, ty| s.print_type(&ty)));
982 try!(word(&mut self.s, ","));
986 ast::TyKind::Paren(ref typ) => {
988 try!(self.print_type(&typ));
991 ast::TyKind::BareFn(ref f) => {
992 let generics = ast::Generics {
993 lifetimes: f.lifetimes.clone(),
995 where_clause: ast::WhereClause {
996 id: ast::DUMMY_NODE_ID,
997 predicates: Vec::new(),
1000 try!(self.print_ty_fn(f.abi,
1006 ast::TyKind::Path(None, ref path) => {
1007 try!(self.print_path(path, false, 0));
1009 ast::TyKind::Path(Some(ref qself), ref path) => {
1010 try!(self.print_qpath(path, qself, false))
1012 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1013 try!(self.print_type(&ty));
1014 try!(self.print_bounds("+", &bounds[..]));
1016 ast::TyKind::PolyTraitRef(ref bounds) => {
1017 try!(self.print_bounds("", &bounds[..]));
1019 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1020 try!(word(&mut self.s, "["));
1021 try!(self.print_type(&ty));
1022 try!(word(&mut self.s, "; "));
1023 try!(self.print_expr(&v));
1024 try!(word(&mut self.s, "]"));
1026 ast::TyKind::Typeof(ref e) => {
1027 try!(word(&mut self.s, "typeof("));
1028 try!(self.print_expr(&e));
1029 try!(word(&mut self.s, ")"));
1031 ast::TyKind::Infer => {
1032 try!(word(&mut self.s, "_"));
1034 ast::TyKind::ImplicitSelf => {
1035 try!(word(&mut self.s, "Self"));
1037 ast::TyKind::Mac(ref m) => {
1038 try!(self.print_mac(m, token::Paren));
1044 pub fn print_foreign_item(&mut self,
1045 item: &ast::ForeignItem) -> io::Result<()> {
1046 try!(self.hardbreak_if_not_bol());
1047 try!(self.maybe_print_comment(item.span.lo));
1048 try!(self.print_outer_attributes(&item.attrs));
1050 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1051 try!(self.head(""));
1052 try!(self.print_fn(decl, ast::Unsafety::Normal,
1053 ast::Constness::NotConst,
1054 Abi::Rust, Some(item.ident),
1055 generics, &item.vis));
1056 try!(self.end()); // end head-ibox
1057 try!(word(&mut self.s, ";"));
1058 self.end() // end the outer fn box
1060 ast::ForeignItemKind::Static(ref t, m) => {
1061 try!(self.head(&visibility_qualified(&item.vis, "static")));
1063 try!(self.word_space("mut"));
1065 try!(self.print_ident(item.ident));
1066 try!(self.word_space(":"));
1067 try!(self.print_type(&t));
1068 try!(word(&mut self.s, ";"));
1069 try!(self.end()); // end the head-ibox
1070 self.end() // end the outer cbox
1075 fn print_associated_const(&mut self,
1078 default: Option<&ast::Expr>,
1079 vis: &ast::Visibility)
1082 try!(word(&mut self.s, &visibility_qualified(vis, "")));
1083 try!(self.word_space("const"));
1084 try!(self.print_ident(ident));
1085 try!(self.word_space(":"));
1086 try!(self.print_type(ty));
1087 if let Some(expr) = default {
1088 try!(space(&mut self.s));
1089 try!(self.word_space("="));
1090 try!(self.print_expr(expr));
1092 word(&mut self.s, ";")
1095 fn print_associated_type(&mut self,
1097 bounds: Option<&ast::TyParamBounds>,
1098 ty: Option<&ast::Ty>)
1100 try!(self.word_space("type"));
1101 try!(self.print_ident(ident));
1102 if let Some(bounds) = bounds {
1103 try!(self.print_bounds(":", bounds));
1105 if let Some(ty) = ty {
1106 try!(space(&mut self.s));
1107 try!(self.word_space("="));
1108 try!(self.print_type(ty));
1110 word(&mut self.s, ";")
1113 /// Pretty-print an item
1114 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1115 try!(self.hardbreak_if_not_bol());
1116 try!(self.maybe_print_comment(item.span.lo));
1117 try!(self.print_outer_attributes(&item.attrs));
1118 try!(self.ann.pre(self, NodeItem(item)));
1120 ast::ItemKind::ExternCrate(ref optional_path) => {
1121 try!(self.head(&visibility_qualified(&item.vis, "extern crate")));
1122 if let Some(p) = *optional_path {
1123 let val = p.as_str();
1124 if val.contains("-") {
1125 try!(self.print_string(&val, ast::StrStyle::Cooked));
1127 try!(self.print_name(p));
1129 try!(space(&mut self.s));
1130 try!(word(&mut self.s, "as"));
1131 try!(space(&mut self.s));
1133 try!(self.print_ident(item.ident));
1134 try!(word(&mut self.s, ";"));
1135 try!(self.end()); // end inner head-block
1136 try!(self.end()); // end outer head-block
1138 ast::ItemKind::Use(ref vp) => {
1139 try!(self.head(&visibility_qualified(&item.vis, "use")));
1140 try!(self.print_view_path(&vp));
1141 try!(word(&mut self.s, ";"));
1142 try!(self.end()); // end inner head-block
1143 try!(self.end()); // end outer head-block
1145 ast::ItemKind::Static(ref ty, m, ref expr) => {
1146 try!(self.head(&visibility_qualified(&item.vis, "static")));
1147 if m == ast::Mutability::Mutable {
1148 try!(self.word_space("mut"));
1150 try!(self.print_ident(item.ident));
1151 try!(self.word_space(":"));
1152 try!(self.print_type(&ty));
1153 try!(space(&mut self.s));
1154 try!(self.end()); // end the head-ibox
1156 try!(self.word_space("="));
1157 try!(self.print_expr(&expr));
1158 try!(word(&mut self.s, ";"));
1159 try!(self.end()); // end the outer cbox
1161 ast::ItemKind::Const(ref ty, ref expr) => {
1162 try!(self.head(&visibility_qualified(&item.vis, "const")));
1163 try!(self.print_ident(item.ident));
1164 try!(self.word_space(":"));
1165 try!(self.print_type(&ty));
1166 try!(space(&mut self.s));
1167 try!(self.end()); // end the head-ibox
1169 try!(self.word_space("="));
1170 try!(self.print_expr(&expr));
1171 try!(word(&mut self.s, ";"));
1172 try!(self.end()); // end the outer cbox
1174 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1175 try!(self.head(""));
1185 try!(word(&mut self.s, " "));
1186 try!(self.print_block_with_attrs(&body, &item.attrs));
1188 ast::ItemKind::Mod(ref _mod) => {
1189 try!(self.head(&visibility_qualified(&item.vis, "mod")));
1190 try!(self.print_ident(item.ident));
1193 try!(self.print_mod(_mod, &item.attrs));
1194 try!(self.bclose(item.span));
1196 ast::ItemKind::ForeignMod(ref nmod) => {
1197 try!(self.head("extern"));
1198 try!(self.word_nbsp(&nmod.abi.to_string()));
1200 try!(self.print_foreign_mod(nmod, &item.attrs));
1201 try!(self.bclose(item.span));
1203 ast::ItemKind::Ty(ref ty, ref params) => {
1204 try!(self.ibox(INDENT_UNIT));
1206 try!(self.word_nbsp(&visibility_qualified(&item.vis, "type")));
1207 try!(self.print_ident(item.ident));
1208 try!(self.print_generics(params));
1209 try!(self.end()); // end the inner ibox
1211 try!(self.print_where_clause(¶ms.where_clause));
1212 try!(space(&mut self.s));
1213 try!(self.word_space("="));
1214 try!(self.print_type(&ty));
1215 try!(word(&mut self.s, ";"));
1216 try!(self.end()); // end the outer ibox
1218 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1219 try!(self.print_enum_def(
1227 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1228 try!(self.head(&visibility_qualified(&item.vis, "struct")));
1229 try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
1232 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1233 try!(self.head(""));
1234 try!(self.print_visibility(&item.vis));
1235 try!(self.print_unsafety(unsafety));
1236 try!(self.word_nbsp("impl"));
1237 try!(self.print_trait_ref(trait_ref));
1238 try!(space(&mut self.s));
1239 try!(self.word_space("for"));
1240 try!(self.word_space(".."));
1242 try!(self.bclose(item.span));
1244 ast::ItemKind::Impl(unsafety,
1249 ref impl_items) => {
1250 try!(self.head(""));
1251 try!(self.print_visibility(&item.vis));
1252 try!(self.print_unsafety(unsafety));
1253 try!(self.word_nbsp("impl"));
1255 if generics.is_parameterized() {
1256 try!(self.print_generics(generics));
1257 try!(space(&mut self.s));
1261 ast::ImplPolarity::Negative => {
1262 try!(word(&mut self.s, "!"));
1269 try!(self.print_trait_ref(t));
1270 try!(space(&mut self.s));
1271 try!(self.word_space("for"));
1276 try!(self.print_type(&ty));
1277 try!(self.print_where_clause(&generics.where_clause));
1279 try!(space(&mut self.s));
1281 try!(self.print_inner_attributes(&item.attrs));
1282 for impl_item in impl_items {
1283 try!(self.print_impl_item(impl_item));
1285 try!(self.bclose(item.span));
1287 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1288 try!(self.head(""));
1289 try!(self.print_visibility(&item.vis));
1290 try!(self.print_unsafety(unsafety));
1291 try!(self.word_nbsp("trait"));
1292 try!(self.print_ident(item.ident));
1293 try!(self.print_generics(generics));
1294 let mut real_bounds = Vec::with_capacity(bounds.len());
1295 for b in bounds.iter() {
1296 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1297 try!(space(&mut self.s));
1298 try!(self.word_space("for ?"));
1299 try!(self.print_trait_ref(&ptr.trait_ref));
1301 real_bounds.push(b.clone());
1304 try!(self.print_bounds(":", &real_bounds[..]));
1305 try!(self.print_where_clause(&generics.where_clause));
1306 try!(word(&mut self.s, " "));
1308 for trait_item in trait_items {
1309 try!(self.print_trait_item(trait_item));
1311 try!(self.bclose(item.span));
1313 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1314 try!(self.print_visibility(&item.vis));
1315 try!(self.print_path(&node.path, false, 0));
1316 try!(word(&mut self.s, "! "));
1317 try!(self.print_ident(item.ident));
1318 try!(self.cbox(INDENT_UNIT));
1320 try!(self.print_tts(&node.tts[..]));
1321 try!(self.pclose());
1322 try!(word(&mut self.s, ";"));
1326 self.ann.post(self, NodeItem(item))
1329 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1330 self.print_path(&t.path, false, 0)
1333 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1334 if !lifetimes.is_empty() {
1335 try!(word(&mut self.s, "for<"));
1336 let mut comma = false;
1337 for lifetime_def in lifetimes {
1339 try!(self.word_space(","))
1341 try!(self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds));
1344 try!(word(&mut self.s, ">"));
1349 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1350 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1351 self.print_trait_ref(&t.trait_ref)
1354 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1355 generics: &ast::Generics, ident: ast::Ident,
1356 span: syntax_pos::Span,
1357 visibility: &ast::Visibility) -> io::Result<()> {
1358 try!(self.head(&visibility_qualified(visibility, "enum")));
1359 try!(self.print_ident(ident));
1360 try!(self.print_generics(generics));
1361 try!(self.print_where_clause(&generics.where_clause));
1362 try!(space(&mut self.s));
1363 self.print_variants(&enum_definition.variants, span)
1366 pub fn print_variants(&mut self,
1367 variants: &[ast::Variant],
1368 span: syntax_pos::Span) -> io::Result<()> {
1371 try!(self.space_if_not_bol());
1372 try!(self.maybe_print_comment(v.span.lo));
1373 try!(self.print_outer_attributes(&v.node.attrs));
1374 try!(self.ibox(INDENT_UNIT));
1375 try!(self.print_variant(v));
1376 try!(word(&mut self.s, ","));
1378 try!(self.maybe_print_trailing_comment(v.span, None));
1383 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1385 ast::Visibility::Public => self.word_nbsp("pub"),
1386 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1387 ast::Visibility::Restricted { ref path, .. } =>
1388 self.word_nbsp(&format!("pub({})", path)),
1389 ast::Visibility::Inherited => Ok(())
1393 pub fn print_struct(&mut self,
1394 struct_def: &ast::VariantData,
1395 generics: &ast::Generics,
1397 span: syntax_pos::Span,
1398 print_finalizer: bool) -> io::Result<()> {
1399 try!(self.print_ident(ident));
1400 try!(self.print_generics(generics));
1401 if !struct_def.is_struct() {
1402 if struct_def.is_tuple() {
1405 Inconsistent, struct_def.fields(),
1407 try!(s.maybe_print_comment(field.span.lo));
1408 try!(s.print_outer_attributes(&field.attrs));
1409 try!(s.print_visibility(&field.vis));
1410 s.print_type(&field.ty)
1413 try!(self.pclose());
1415 try!(self.print_where_clause(&generics.where_clause));
1416 if print_finalizer {
1417 try!(word(&mut self.s, ";"));
1420 self.end() // close the outer-box
1422 try!(self.print_where_clause(&generics.where_clause));
1425 try!(self.hardbreak_if_not_bol());
1427 for field in struct_def.fields() {
1428 try!(self.hardbreak_if_not_bol());
1429 try!(self.maybe_print_comment(field.span.lo));
1430 try!(self.print_outer_attributes(&field.attrs));
1431 try!(self.print_visibility(&field.vis));
1432 try!(self.print_ident(field.ident.unwrap()));
1433 try!(self.word_nbsp(":"));
1434 try!(self.print_type(&field.ty));
1435 try!(word(&mut self.s, ","));
1442 /// This doesn't deserve to be called "pretty" printing, but it should be
1443 /// meaning-preserving. A quick hack that might help would be to look at the
1444 /// spans embedded in the TTs to decide where to put spaces and newlines.
1445 /// But it'd be better to parse these according to the grammar of the
1446 /// appropriate macro, transcribe back into the grammar we just parsed from,
1447 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1448 /// expression arguments as expressions). It can be done! I think.
1449 pub fn print_tt(&mut self, tt: &tokenstream::TokenTree) -> io::Result<()> {
1451 TokenTree::Token(_, ref tk) => {
1452 try!(word(&mut self.s, &token_to_string(tk)));
1454 parse::token::DocComment(..) => {
1455 hardbreak(&mut self.s)
1460 TokenTree::Delimited(_, ref delimed) => {
1461 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1462 try!(space(&mut self.s));
1463 try!(self.print_tts(&delimed.tts));
1464 try!(space(&mut self.s));
1465 word(&mut self.s, &token_to_string(&delimed.close_token()))
1467 TokenTree::Sequence(_, ref seq) => {
1468 try!(word(&mut self.s, "$("));
1469 for tt_elt in &seq.tts {
1470 try!(self.print_tt(tt_elt));
1472 try!(word(&mut self.s, ")"));
1473 match seq.separator {
1475 try!(word(&mut self.s, &token_to_string(tk)));
1480 tokenstream::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1481 tokenstream::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1487 pub fn print_tts(&mut self, tts: &[tokenstream::TokenTree]) -> io::Result<()> {
1489 for (i, tt) in tts.iter().enumerate() {
1491 try!(space(&mut self.s));
1493 try!(self.print_tt(tt));
1498 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1499 try!(self.head(""));
1500 let generics = ast::Generics::default();
1501 try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
1502 match v.node.disr_expr {
1504 try!(space(&mut self.s));
1505 try!(self.word_space("="));
1512 pub fn print_method_sig(&mut self,
1515 vis: &ast::Visibility)
1517 self.print_fn(&m.decl,
1526 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1528 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1529 try!(self.hardbreak_if_not_bol());
1530 try!(self.maybe_print_comment(ti.span.lo));
1531 try!(self.print_outer_attributes(&ti.attrs));
1533 ast::TraitItemKind::Const(ref ty, ref default) => {
1534 try!(self.print_associated_const(ti.ident, &ty,
1535 default.as_ref().map(|expr| &**expr),
1536 &ast::Visibility::Inherited));
1538 ast::TraitItemKind::Method(ref sig, ref body) => {
1540 try!(self.head(""));
1542 try!(self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited));
1543 if let Some(ref body) = *body {
1545 try!(self.print_block_with_attrs(body, &ti.attrs));
1547 try!(word(&mut self.s, ";"));
1550 ast::TraitItemKind::Type(ref bounds, ref default) => {
1551 try!(self.print_associated_type(ti.ident, Some(bounds),
1552 default.as_ref().map(|ty| &**ty)));
1554 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1555 // code copied from ItemKind::Mac:
1556 self.print_path(&node.path, false, 0)?;
1557 word(&mut self.s, "! ")?;
1558 self.cbox(INDENT_UNIT)?;
1560 self.print_tts(&node.tts[..])?;
1562 word(&mut self.s, ";")?;
1566 self.ann.post(self, NodeSubItem(ti.id))
1569 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1570 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1571 try!(self.hardbreak_if_not_bol());
1572 try!(self.maybe_print_comment(ii.span.lo));
1573 try!(self.print_outer_attributes(&ii.attrs));
1574 if let ast::Defaultness::Default = ii.defaultness {
1575 try!(self.word_nbsp("default"));
1578 ast::ImplItemKind::Const(ref ty, ref expr) => {
1579 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis));
1581 ast::ImplItemKind::Method(ref sig, ref body) => {
1582 try!(self.head(""));
1583 try!(self.print_method_sig(ii.ident, sig, &ii.vis));
1585 try!(self.print_block_with_attrs(body, &ii.attrs));
1587 ast::ImplItemKind::Type(ref ty) => {
1588 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1590 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1591 // code copied from ItemKind::Mac:
1592 try!(self.print_path(&node.path, false, 0));
1593 try!(word(&mut self.s, "! "));
1594 try!(self.cbox(INDENT_UNIT));
1596 try!(self.print_tts(&node.tts[..]));
1597 try!(self.pclose());
1598 try!(word(&mut self.s, ";"));
1602 self.ann.post(self, NodeSubItem(ii.id))
1605 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1606 try!(self.maybe_print_comment(st.span.lo));
1608 ast::StmtKind::Local(ref loc) => {
1609 try!(self.print_outer_attributes(&loc.attrs));
1610 try!(self.space_if_not_bol());
1611 try!(self.ibox(INDENT_UNIT));
1612 try!(self.word_nbsp("let"));
1614 try!(self.ibox(INDENT_UNIT));
1615 try!(self.print_local_decl(&loc));
1617 if let Some(ref init) = loc.init {
1619 try!(self.word_space("="));
1620 try!(self.print_expr(&init));
1622 try!(word(&mut self.s, ";"));
1625 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1626 ast::StmtKind::Expr(ref expr) => {
1627 try!(self.space_if_not_bol());
1628 try!(self.print_expr_outer_attr_style(&expr, false));
1629 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1630 try!(word(&mut self.s, ";"));
1633 ast::StmtKind::Semi(ref expr) => {
1634 try!(self.space_if_not_bol());
1635 try!(self.print_expr_outer_attr_style(&expr, false));
1636 try!(word(&mut self.s, ";"));
1638 ast::StmtKind::Mac(ref mac) => {
1639 let (ref mac, style, ref attrs) = **mac;
1640 try!(self.space_if_not_bol());
1641 try!(self.print_outer_attributes(&attrs));
1642 let delim = match style {
1643 ast::MacStmtStyle::Braces => token::Brace,
1646 try!(self.print_mac(&mac, delim));
1648 ast::MacStmtStyle::Braces => {}
1649 _ => try!(word(&mut self.s, ";")),
1653 self.maybe_print_trailing_comment(st.span, None)
1656 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1657 self.print_block_with_attrs(blk, &[])
1660 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1661 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1664 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1665 attrs: &[ast::Attribute])
1667 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1670 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1671 indented: usize) -> io::Result<()> {
1672 self.print_block_maybe_unclosed(blk, indented, &[], false)
1675 pub fn print_block_with_attrs(&mut self,
1677 attrs: &[ast::Attribute]) -> io::Result<()> {
1678 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1681 pub fn print_block_maybe_unclosed(&mut self,
1684 attrs: &[ast::Attribute],
1685 close_box: bool) -> io::Result<()> {
1687 BlockCheckMode::Unsafe(..) => try!(self.word_space("unsafe")),
1688 BlockCheckMode::Default => ()
1690 try!(self.maybe_print_comment(blk.span.lo));
1691 try!(self.ann.pre(self, NodeBlock(blk)));
1694 try!(self.print_inner_attributes(attrs));
1696 for (i, st) in blk.stmts.iter().enumerate() {
1698 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1699 try!(self.space_if_not_bol());
1700 try!(self.print_expr_outer_attr_style(&expr, false));
1701 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1703 _ => try!(self.print_stmt(st)),
1707 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1708 self.ann.post(self, NodeBlock(blk))
1711 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1715 // "another else-if"
1716 ast::ExprKind::If(ref i, ref then, ref e) => {
1717 try!(self.cbox(INDENT_UNIT - 1));
1719 try!(word(&mut self.s, " else if "));
1720 try!(self.print_expr(&i));
1721 try!(space(&mut self.s));
1722 try!(self.print_block(&then));
1723 self.print_else(e.as_ref().map(|e| &**e))
1725 // "another else-if-let"
1726 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1727 try!(self.cbox(INDENT_UNIT - 1));
1729 try!(word(&mut self.s, " else if let "));
1730 try!(self.print_pat(&pat));
1731 try!(space(&mut self.s));
1732 try!(self.word_space("="));
1733 try!(self.print_expr(&expr));
1734 try!(space(&mut self.s));
1735 try!(self.print_block(&then));
1736 self.print_else(e.as_ref().map(|e| &**e))
1739 ast::ExprKind::Block(ref b) => {
1740 try!(self.cbox(INDENT_UNIT - 1));
1742 try!(word(&mut self.s, " else "));
1743 self.print_block(&b)
1745 // BLEAH, constraints would be great here
1747 panic!("print_if saw if with weird alternative");
1755 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1756 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1757 try!(self.head("if"));
1758 try!(self.print_expr(test));
1759 try!(space(&mut self.s));
1760 try!(self.print_block(blk));
1761 self.print_else(elseopt)
1764 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1765 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1766 try!(self.head("if let"));
1767 try!(self.print_pat(pat));
1768 try!(space(&mut self.s));
1769 try!(self.word_space("="));
1770 try!(self.print_expr(expr));
1771 try!(space(&mut self.s));
1772 try!(self.print_block(blk));
1773 self.print_else(elseopt)
1776 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1778 try!(self.print_path(&m.node.path, false, 0));
1779 try!(word(&mut self.s, "!"));
1781 token::Paren => try!(self.popen()),
1782 token::Bracket => try!(word(&mut self.s, "[")),
1784 try!(self.head(""));
1788 try!(self.print_tts(&m.node.tts));
1790 token::Paren => self.pclose(),
1791 token::Bracket => word(&mut self.s, "]"),
1792 token::Brace => self.bclose(m.span),
1797 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1799 try!(self.commasep_exprs(Inconsistent, args));
1803 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1804 binop: ast::BinOp) -> bool {
1805 match sub_expr.node {
1806 ast::ExprKind::Binary(ref sub_op, _, _) => {
1807 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1808 AssocOp::from_ast_binop(binop.node).precedence() {
1818 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1819 let needs_par = needs_parentheses(expr);
1823 try!(self.print_expr(expr));
1825 try!(self.pclose());
1830 fn print_expr_in_place(&mut self,
1832 expr: &ast::Expr) -> io::Result<()> {
1833 try!(self.print_expr_maybe_paren(place));
1834 try!(space(&mut self.s));
1835 try!(self.word_space("<-"));
1836 self.print_expr_maybe_paren(expr)
1839 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1840 attrs: &[Attribute]) -> io::Result<()> {
1841 try!(self.ibox(INDENT_UNIT));
1842 try!(word(&mut self.s, "["));
1843 try!(self.print_inner_attributes_inline(attrs));
1844 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1845 try!(word(&mut self.s, "]"));
1849 fn print_expr_repeat(&mut self,
1850 element: &ast::Expr,
1852 attrs: &[Attribute]) -> io::Result<()> {
1853 try!(self.ibox(INDENT_UNIT));
1854 try!(word(&mut self.s, "["));
1855 try!(self.print_inner_attributes_inline(attrs));
1856 try!(self.print_expr(element));
1857 try!(self.word_space(";"));
1858 try!(self.print_expr(count));
1859 try!(word(&mut self.s, "]"));
1863 fn print_expr_struct(&mut self,
1865 fields: &[ast::Field],
1866 wth: &Option<P<ast::Expr>>,
1867 attrs: &[Attribute]) -> io::Result<()> {
1868 try!(self.print_path(path, true, 0));
1869 try!(word(&mut self.s, "{"));
1870 try!(self.print_inner_attributes_inline(attrs));
1871 try!(self.commasep_cmnt(
1875 try!(s.ibox(INDENT_UNIT));
1876 try!(s.print_ident(field.ident.node));
1877 try!(s.word_space(":"));
1878 try!(s.print_expr(&field.expr));
1884 try!(self.ibox(INDENT_UNIT));
1885 if !fields.is_empty() {
1886 try!(word(&mut self.s, ","));
1887 try!(space(&mut self.s));
1889 try!(word(&mut self.s, ".."));
1890 try!(self.print_expr(&expr));
1893 _ => if !fields.is_empty() {
1894 try!(word(&mut self.s, ","))
1897 try!(word(&mut self.s, "}"));
1901 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1902 attrs: &[Attribute]) -> io::Result<()> {
1904 try!(self.print_inner_attributes_inline(attrs));
1905 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1906 if exprs.len() == 1 {
1907 try!(word(&mut self.s, ","));
1912 fn print_expr_call(&mut self,
1914 args: &[P<ast::Expr>]) -> io::Result<()> {
1915 try!(self.print_expr_maybe_paren(func));
1916 self.print_call_post(args)
1919 fn print_expr_method_call(&mut self,
1920 ident: ast::SpannedIdent,
1922 args: &[P<ast::Expr>]) -> io::Result<()> {
1923 let base_args = &args[1..];
1924 try!(self.print_expr(&args[0]));
1925 try!(word(&mut self.s, "."));
1926 try!(self.print_ident(ident.node));
1927 if !tys.is_empty() {
1928 try!(word(&mut self.s, "::<"));
1929 try!(self.commasep(Inconsistent, tys,
1930 |s, ty| s.print_type(&ty)));
1931 try!(word(&mut self.s, ">"));
1933 self.print_call_post(base_args)
1936 fn print_expr_binary(&mut self,
1939 rhs: &ast::Expr) -> io::Result<()> {
1940 if self.check_expr_bin_needs_paren(lhs, op) {
1941 try!(self.print_expr_maybe_paren(lhs));
1943 try!(self.print_expr(lhs));
1945 try!(space(&mut self.s));
1946 try!(self.word_space(op.node.to_string()));
1947 if self.check_expr_bin_needs_paren(rhs, op) {
1948 self.print_expr_maybe_paren(rhs)
1950 self.print_expr(rhs)
1954 fn print_expr_unary(&mut self,
1956 expr: &ast::Expr) -> io::Result<()> {
1957 try!(word(&mut self.s, ast::UnOp::to_string(op)));
1958 self.print_expr_maybe_paren(expr)
1961 fn print_expr_addr_of(&mut self,
1962 mutability: ast::Mutability,
1963 expr: &ast::Expr) -> io::Result<()> {
1964 try!(word(&mut self.s, "&"));
1965 try!(self.print_mutability(mutability));
1966 self.print_expr_maybe_paren(expr)
1969 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1970 self.print_expr_outer_attr_style(expr, true)
1973 fn print_expr_outer_attr_style(&mut self,
1975 is_inline: bool) -> io::Result<()> {
1976 try!(self.maybe_print_comment(expr.span.lo));
1978 let attrs = &expr.attrs;
1980 try!(self.print_outer_attributes_inline(attrs));
1982 try!(self.print_outer_attributes(attrs));
1985 try!(self.ibox(INDENT_UNIT));
1986 try!(self.ann.pre(self, NodeExpr(expr)));
1988 ast::ExprKind::Box(ref expr) => {
1989 try!(self.word_space("box"));
1990 try!(self.print_expr(expr));
1992 ast::ExprKind::InPlace(ref place, ref expr) => {
1993 try!(self.print_expr_in_place(place, expr));
1995 ast::ExprKind::Vec(ref exprs) => {
1996 try!(self.print_expr_vec(&exprs[..], attrs));
1998 ast::ExprKind::Repeat(ref element, ref count) => {
1999 try!(self.print_expr_repeat(&element, &count, attrs));
2001 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2002 try!(self.print_expr_struct(path, &fields[..], wth, attrs));
2004 ast::ExprKind::Tup(ref exprs) => {
2005 try!(self.print_expr_tup(&exprs[..], attrs));
2007 ast::ExprKind::Call(ref func, ref args) => {
2008 try!(self.print_expr_call(&func, &args[..]));
2010 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2011 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
2013 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2014 try!(self.print_expr_binary(op, &lhs, &rhs));
2016 ast::ExprKind::Unary(op, ref expr) => {
2017 try!(self.print_expr_unary(op, &expr));
2019 ast::ExprKind::AddrOf(m, ref expr) => {
2020 try!(self.print_expr_addr_of(m, &expr));
2022 ast::ExprKind::Lit(ref lit) => {
2023 try!(self.print_literal(&lit));
2025 ast::ExprKind::Cast(ref expr, ref ty) => {
2026 if let ast::ExprKind::Cast(..) = expr.node {
2027 try!(self.print_expr(&expr));
2029 try!(self.print_expr_maybe_paren(&expr));
2031 try!(space(&mut self.s));
2032 try!(self.word_space("as"));
2033 try!(self.print_type(&ty));
2035 ast::ExprKind::Type(ref expr, ref ty) => {
2036 try!(self.print_expr(&expr));
2037 try!(self.word_space(":"));
2038 try!(self.print_type(&ty));
2040 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2041 try!(self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)));
2043 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2044 try!(self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e)));
2046 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2047 if let Some(ident) = opt_ident {
2048 try!(self.print_ident(ident.node));
2049 try!(self.word_space(":"));
2051 try!(self.head("while"));
2052 try!(self.print_expr(&test));
2053 try!(space(&mut self.s));
2054 try!(self.print_block_with_attrs(&blk, attrs));
2056 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2057 if let Some(ident) = opt_ident {
2058 try!(self.print_ident(ident.node));
2059 try!(self.word_space(":"));
2061 try!(self.head("while let"));
2062 try!(self.print_pat(&pat));
2063 try!(space(&mut self.s));
2064 try!(self.word_space("="));
2065 try!(self.print_expr(&expr));
2066 try!(space(&mut self.s));
2067 try!(self.print_block_with_attrs(&blk, attrs));
2069 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2070 if let Some(ident) = opt_ident {
2071 try!(self.print_ident(ident.node));
2072 try!(self.word_space(":"));
2074 try!(self.head("for"));
2075 try!(self.print_pat(&pat));
2076 try!(space(&mut self.s));
2077 try!(self.word_space("in"));
2078 try!(self.print_expr(&iter));
2079 try!(space(&mut self.s));
2080 try!(self.print_block_with_attrs(&blk, attrs));
2082 ast::ExprKind::Loop(ref blk, opt_ident) => {
2083 if let Some(ident) = opt_ident {
2084 try!(self.print_ident(ident.node));
2085 try!(self.word_space(":"));
2087 try!(self.head("loop"));
2088 try!(space(&mut self.s));
2089 try!(self.print_block_with_attrs(&blk, attrs));
2091 ast::ExprKind::Match(ref expr, ref arms) => {
2092 try!(self.cbox(INDENT_UNIT));
2094 try!(self.word_nbsp("match"));
2095 try!(self.print_expr(&expr));
2096 try!(space(&mut self.s));
2098 try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
2100 try!(self.print_arm(arm));
2102 try!(self.bclose_(expr.span, INDENT_UNIT));
2104 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2105 try!(self.print_capture_clause(capture_clause));
2107 try!(self.print_fn_block_args(&decl));
2108 try!(space(&mut self.s));
2110 let default_return = match decl.output {
2111 ast::FunctionRetTy::Default(..) => true,
2115 match body.stmts.last().map(|stmt| &stmt.node) {
2116 Some(&ast::StmtKind::Expr(ref i_expr)) if default_return &&
2117 body.stmts.len() == 1 => {
2118 // we extract the block, so as not to create another set of boxes
2119 if let ast::ExprKind::Block(ref blk) = i_expr.node {
2120 try!(self.print_block_unclosed_with_attrs(&blk, &i_expr.attrs));
2122 // this is a bare expression
2123 try!(self.print_expr(&i_expr));
2124 try!(self.end()); // need to close a box
2127 _ => try!(self.print_block_unclosed(&body)),
2130 // a box will be closed by print_expr, but we didn't want an overall
2131 // wrapper so we closed the corresponding opening. so create an
2132 // empty box to satisfy the close.
2135 ast::ExprKind::Block(ref blk) => {
2136 // containing cbox, will be closed by print-block at }
2137 try!(self.cbox(INDENT_UNIT));
2138 // head-box, will be closed by print-block after {
2140 try!(self.print_block_with_attrs(&blk, attrs));
2142 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2143 try!(self.print_expr(&lhs));
2144 try!(space(&mut self.s));
2145 try!(self.word_space("="));
2146 try!(self.print_expr(&rhs));
2148 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2149 try!(self.print_expr(&lhs));
2150 try!(space(&mut self.s));
2151 try!(word(&mut self.s, op.node.to_string()));
2152 try!(self.word_space("="));
2153 try!(self.print_expr(&rhs));
2155 ast::ExprKind::Field(ref expr, id) => {
2156 try!(self.print_expr(&expr));
2157 try!(word(&mut self.s, "."));
2158 try!(self.print_ident(id.node));
2160 ast::ExprKind::TupField(ref expr, id) => {
2161 try!(self.print_expr(&expr));
2162 try!(word(&mut self.s, "."));
2163 try!(self.print_usize(id.node));
2165 ast::ExprKind::Index(ref expr, ref index) => {
2166 try!(self.print_expr(&expr));
2167 try!(word(&mut self.s, "["));
2168 try!(self.print_expr(&index));
2169 try!(word(&mut self.s, "]"));
2171 ast::ExprKind::Range(ref start, ref end, limits) => {
2172 if let &Some(ref e) = start {
2173 try!(self.print_expr(&e));
2175 if limits == ast::RangeLimits::HalfOpen {
2176 try!(word(&mut self.s, ".."));
2178 try!(word(&mut self.s, "..."));
2180 if let &Some(ref e) = end {
2181 try!(self.print_expr(&e));
2184 ast::ExprKind::Path(None, ref path) => {
2185 try!(self.print_path(path, true, 0))
2187 ast::ExprKind::Path(Some(ref qself), ref path) => {
2188 try!(self.print_qpath(path, qself, true))
2190 ast::ExprKind::Break(opt_ident) => {
2191 try!(word(&mut self.s, "break"));
2192 try!(space(&mut self.s));
2193 if let Some(ident) = opt_ident {
2194 try!(self.print_ident(ident.node));
2195 try!(space(&mut self.s));
2198 ast::ExprKind::Continue(opt_ident) => {
2199 try!(word(&mut self.s, "continue"));
2200 try!(space(&mut self.s));
2201 if let Some(ident) = opt_ident {
2202 try!(self.print_ident(ident.node));
2203 try!(space(&mut self.s))
2206 ast::ExprKind::Ret(ref result) => {
2207 try!(word(&mut self.s, "return"));
2210 try!(word(&mut self.s, " "));
2211 try!(self.print_expr(&expr));
2216 ast::ExprKind::InlineAsm(ref a) => {
2217 try!(word(&mut self.s, "asm!"));
2219 try!(self.print_string(&a.asm, a.asm_str_style));
2220 try!(self.word_space(":"));
2222 try!(self.commasep(Inconsistent, &a.outputs,
2224 let mut ch = out.constraint.chars();
2226 Some('=') if out.is_rw => {
2227 try!(s.print_string(&format!("+{}", ch.as_str()),
2228 ast::StrStyle::Cooked))
2230 _ => try!(s.print_string(&out.constraint,
2231 ast::StrStyle::Cooked))
2234 try!(s.print_expr(&out.expr));
2238 try!(space(&mut self.s));
2239 try!(self.word_space(":"));
2241 try!(self.commasep(Inconsistent, &a.inputs,
2242 |s, &(ref co, ref o)| {
2243 try!(s.print_string(&co, ast::StrStyle::Cooked));
2245 try!(s.print_expr(&o));
2249 try!(space(&mut self.s));
2250 try!(self.word_space(":"));
2252 try!(self.commasep(Inconsistent, &a.clobbers,
2254 try!(s.print_string(&co, ast::StrStyle::Cooked));
2258 let mut options = vec!();
2260 options.push("volatile");
2263 options.push("alignstack");
2265 if a.dialect == ast::AsmDialect::Intel {
2266 options.push("intel");
2269 if !options.is_empty() {
2270 try!(space(&mut self.s));
2271 try!(self.word_space(":"));
2272 try!(self.commasep(Inconsistent, &options,
2274 try!(s.print_string(co, ast::StrStyle::Cooked));
2279 try!(self.pclose());
2281 ast::ExprKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2282 ast::ExprKind::Paren(ref e) => {
2284 try!(self.print_inner_attributes_inline(attrs));
2285 try!(self.print_expr(&e));
2286 try!(self.pclose());
2288 ast::ExprKind::Try(ref e) => {
2289 try!(self.print_expr(e));
2290 try!(word(&mut self.s, "?"))
2293 try!(self.ann.post(self, NodeExpr(expr)));
2297 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2298 try!(self.print_pat(&loc.pat));
2299 if let Some(ref ty) = loc.ty {
2300 try!(self.word_space(":"));
2301 try!(self.print_type(&ty));
2306 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2307 try!(word(&mut self.s, &ident.name.as_str()));
2308 self.ann.post(self, NodeIdent(&ident))
2311 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2312 word(&mut self.s, &i.to_string())
2315 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2316 try!(word(&mut self.s, &name.as_str()));
2317 self.ann.post(self, NodeName(&name))
2320 pub fn print_for_decl(&mut self, loc: &ast::Local,
2321 coll: &ast::Expr) -> io::Result<()> {
2322 try!(self.print_local_decl(loc));
2323 try!(space(&mut self.s));
2324 try!(self.word_space("in"));
2325 self.print_expr(coll)
2328 fn print_path(&mut self,
2330 colons_before_params: bool,
2334 try!(self.maybe_print_comment(path.span.lo));
2336 let mut first = !path.global;
2337 for segment in &path.segments[..path.segments.len()-depth] {
2341 try!(word(&mut self.s, "::"))
2344 try!(self.print_ident(segment.identifier));
2346 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2352 fn print_qpath(&mut self,
2355 colons_before_params: bool)
2358 try!(word(&mut self.s, "<"));
2359 try!(self.print_type(&qself.ty));
2360 if qself.position > 0 {
2361 try!(space(&mut self.s));
2362 try!(self.word_space("as"));
2363 let depth = path.segments.len() - qself.position;
2364 try!(self.print_path(&path, false, depth));
2366 try!(word(&mut self.s, ">"));
2367 try!(word(&mut self.s, "::"));
2368 let item_segment = path.segments.last().unwrap();
2369 try!(self.print_ident(item_segment.identifier));
2370 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2373 fn print_path_parameters(&mut self,
2374 parameters: &ast::PathParameters,
2375 colons_before_params: bool)
2378 if parameters.is_empty() {
2382 if colons_before_params {
2383 try!(word(&mut self.s, "::"))
2387 ast::PathParameters::AngleBracketed(ref data) => {
2388 try!(word(&mut self.s, "<"));
2390 let mut comma = false;
2391 for lifetime in &data.lifetimes {
2393 try!(self.word_space(","))
2395 try!(self.print_lifetime(lifetime));
2399 if !data.types.is_empty() {
2401 try!(self.word_space(","))
2406 |s, ty| s.print_type(&ty)));
2410 for binding in data.bindings.iter() {
2412 try!(self.word_space(","))
2414 try!(self.print_ident(binding.ident));
2415 try!(space(&mut self.s));
2416 try!(self.word_space("="));
2417 try!(self.print_type(&binding.ty));
2421 try!(word(&mut self.s, ">"))
2424 ast::PathParameters::Parenthesized(ref data) => {
2425 try!(word(&mut self.s, "("));
2429 |s, ty| s.print_type(&ty)));
2430 try!(word(&mut self.s, ")"));
2435 try!(self.space_if_not_bol());
2436 try!(self.word_space("->"));
2437 try!(self.print_type(&ty));
2446 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2447 try!(self.maybe_print_comment(pat.span.lo));
2448 try!(self.ann.pre(self, NodePat(pat)));
2449 /* Pat isn't normalized, but the beauty of it
2450 is that it doesn't matter */
2452 PatKind::Wild => try!(word(&mut self.s, "_")),
2453 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2454 match binding_mode {
2455 ast::BindingMode::ByRef(mutbl) => {
2456 try!(self.word_nbsp("ref"));
2457 try!(self.print_mutability(mutbl));
2459 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2460 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2461 try!(self.word_nbsp("mut"));
2464 try!(self.print_ident(path1.node));
2465 if let Some(ref p) = *sub {
2466 try!(word(&mut self.s, "@"));
2467 try!(self.print_pat(&p));
2470 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2471 try!(self.print_path(path, true, 0));
2473 if let Some(ddpos) = ddpos {
2474 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2476 try!(self.word_space(","));
2478 try!(word(&mut self.s, ".."));
2479 if ddpos != elts.len() {
2480 try!(word(&mut self.s, ","));
2481 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2484 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2486 try!(self.pclose());
2488 PatKind::Path(None, ref path) => {
2489 try!(self.print_path(path, true, 0));
2491 PatKind::Path(Some(ref qself), ref path) => {
2492 try!(self.print_qpath(path, qself, false));
2494 PatKind::Struct(ref path, ref fields, etc) => {
2495 try!(self.print_path(path, true, 0));
2497 try!(self.word_space("{"));
2498 try!(self.commasep_cmnt(
2499 Consistent, &fields[..],
2501 try!(s.cbox(INDENT_UNIT));
2502 if !f.node.is_shorthand {
2503 try!(s.print_ident(f.node.ident));
2504 try!(s.word_nbsp(":"));
2506 try!(s.print_pat(&f.node.pat));
2509 |f| f.node.pat.span));
2511 if !fields.is_empty() { try!(self.word_space(",")); }
2512 try!(word(&mut self.s, ".."));
2514 try!(space(&mut self.s));
2515 try!(word(&mut self.s, "}"));
2517 PatKind::Tuple(ref elts, ddpos) => {
2519 if let Some(ddpos) = ddpos {
2520 try!(self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p)));
2522 try!(self.word_space(","));
2524 try!(word(&mut self.s, ".."));
2525 if ddpos != elts.len() {
2526 try!(word(&mut self.s, ","));
2527 try!(self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p)));
2530 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
2531 if elts.len() == 1 {
2532 try!(word(&mut self.s, ","));
2535 try!(self.pclose());
2537 PatKind::Box(ref inner) => {
2538 try!(word(&mut self.s, "box "));
2539 try!(self.print_pat(&inner));
2541 PatKind::Ref(ref inner, mutbl) => {
2542 try!(word(&mut self.s, "&"));
2543 if mutbl == ast::Mutability::Mutable {
2544 try!(word(&mut self.s, "mut "));
2546 try!(self.print_pat(&inner));
2548 PatKind::Lit(ref e) => try!(self.print_expr(&**e)),
2549 PatKind::Range(ref begin, ref end) => {
2550 try!(self.print_expr(&begin));
2551 try!(space(&mut self.s));
2552 try!(word(&mut self.s, "..."));
2553 try!(self.print_expr(&end));
2555 PatKind::Vec(ref before, ref slice, ref after) => {
2556 try!(word(&mut self.s, "["));
2557 try!(self.commasep(Inconsistent,
2559 |s, p| s.print_pat(&p)));
2560 if let Some(ref p) = *slice {
2561 if !before.is_empty() { try!(self.word_space(",")); }
2562 if p.node != PatKind::Wild {
2563 try!(self.print_pat(&p));
2565 try!(word(&mut self.s, ".."));
2566 if !after.is_empty() { try!(self.word_space(",")); }
2568 try!(self.commasep(Inconsistent,
2570 |s, p| s.print_pat(&p)));
2571 try!(word(&mut self.s, "]"));
2573 PatKind::Mac(ref m) => try!(self.print_mac(m, token::Paren)),
2575 self.ann.post(self, NodePat(pat))
2578 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2579 // I have no idea why this check is necessary, but here it
2581 if arm.attrs.is_empty() {
2582 try!(space(&mut self.s));
2584 try!(self.cbox(INDENT_UNIT));
2586 try!(self.print_outer_attributes(&arm.attrs));
2587 let mut first = true;
2588 for p in &arm.pats {
2592 try!(space(&mut self.s));
2593 try!(self.word_space("|"));
2595 try!(self.print_pat(&p));
2597 try!(space(&mut self.s));
2598 if let Some(ref e) = arm.guard {
2599 try!(self.word_space("if"));
2600 try!(self.print_expr(&e));
2601 try!(space(&mut self.s));
2603 try!(self.word_space("=>"));
2605 match arm.body.node {
2606 ast::ExprKind::Block(ref blk) => {
2607 // the block will close the pattern's ibox
2608 try!(self.print_block_unclosed_indent(&blk, INDENT_UNIT));
2610 // If it is a user-provided unsafe block, print a comma after it
2611 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2612 try!(word(&mut self.s, ","));
2616 try!(self.end()); // close the ibox for the pattern
2617 try!(self.print_expr(&arm.body));
2618 try!(word(&mut self.s, ","));
2621 self.end() // close enclosing cbox
2624 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2625 match explicit_self.node {
2626 SelfKind::Value(m) => {
2627 try!(self.print_mutability(m));
2628 word(&mut self.s, "self")
2630 SelfKind::Region(ref lt, m) => {
2631 try!(word(&mut self.s, "&"));
2632 try!(self.print_opt_lifetime(lt));
2633 try!(self.print_mutability(m));
2634 word(&mut self.s, "self")
2636 SelfKind::Explicit(ref typ, m) => {
2637 try!(self.print_mutability(m));
2638 try!(word(&mut self.s, "self"));
2639 try!(self.word_space(":"));
2640 self.print_type(&typ)
2645 pub fn print_fn(&mut self,
2647 unsafety: ast::Unsafety,
2648 constness: ast::Constness,
2650 name: Option<ast::Ident>,
2651 generics: &ast::Generics,
2652 vis: &ast::Visibility) -> io::Result<()> {
2653 try!(self.print_fn_header_info(unsafety, constness, abi, vis));
2655 if let Some(name) = name {
2657 try!(self.print_ident(name));
2659 try!(self.print_generics(generics));
2660 try!(self.print_fn_args_and_ret(decl));
2661 self.print_where_clause(&generics.where_clause)
2664 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2667 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false)));
2669 try!(word(&mut self.s, ", ..."));
2671 try!(self.pclose());
2673 self.print_fn_output(decl)
2676 pub fn print_fn_block_args(
2680 try!(word(&mut self.s, "|"));
2681 try!(self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true)));
2682 try!(word(&mut self.s, "|"));
2684 if let ast::FunctionRetTy::Default(..) = decl.output {
2688 try!(self.space_if_not_bol());
2689 try!(self.word_space("->"));
2691 ast::FunctionRetTy::Ty(ref ty) => {
2692 try!(self.print_type(&ty));
2693 self.maybe_print_comment(ty.span.lo)
2695 ast::FunctionRetTy::Default(..) => unreachable!(),
2696 ast::FunctionRetTy::None(span) => {
2697 try!(self.word_nbsp("!"));
2698 self.maybe_print_comment(span.lo)
2703 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2705 match capture_clause {
2706 ast::CaptureBy::Value => self.word_space("move"),
2707 ast::CaptureBy::Ref => Ok(()),
2711 pub fn print_bounds(&mut self,
2713 bounds: &[ast::TyParamBound])
2715 if !bounds.is_empty() {
2716 try!(word(&mut self.s, prefix));
2717 let mut first = true;
2718 for bound in bounds {
2723 try!(self.word_space("+"));
2727 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2728 self.print_poly_trait_ref(tref)
2730 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2731 try!(word(&mut self.s, "?"));
2732 self.print_poly_trait_ref(tref)
2734 RegionTyParamBound(ref lt) => {
2735 self.print_lifetime(lt)
2745 pub fn print_lifetime(&mut self,
2746 lifetime: &ast::Lifetime)
2749 self.print_name(lifetime.name)
2752 pub fn print_lifetime_bounds(&mut self,
2753 lifetime: &ast::Lifetime,
2754 bounds: &[ast::Lifetime])
2757 try!(self.print_lifetime(lifetime));
2758 if !bounds.is_empty() {
2759 try!(word(&mut self.s, ": "));
2760 for (i, bound) in bounds.iter().enumerate() {
2762 try!(word(&mut self.s, " + "));
2764 try!(self.print_lifetime(bound));
2770 pub fn print_generics(&mut self,
2771 generics: &ast::Generics)
2774 let total = generics.lifetimes.len() + generics.ty_params.len();
2779 try!(word(&mut self.s, "<"));
2781 let mut ints = Vec::new();
2786 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2787 if idx < generics.lifetimes.len() {
2788 let lifetime_def = &generics.lifetimes[idx];
2789 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2791 let idx = idx - generics.lifetimes.len();
2792 let param = &generics.ty_params[idx];
2793 s.print_ty_param(param)
2797 try!(word(&mut self.s, ">"));
2801 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2802 try!(self.print_ident(param.ident));
2803 try!(self.print_bounds(":", ¶m.bounds));
2804 match param.default {
2805 Some(ref default) => {
2806 try!(space(&mut self.s));
2807 try!(self.word_space("="));
2808 self.print_type(&default)
2814 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2816 if where_clause.predicates.is_empty() {
2820 try!(space(&mut self.s));
2821 try!(self.word_space("where"));
2823 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2825 try!(self.word_space(","));
2829 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2833 try!(self.print_formal_lifetime_list(bound_lifetimes));
2834 try!(self.print_type(&bounded_ty));
2835 try!(self.print_bounds(":", bounds));
2837 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2840 try!(self.print_lifetime_bounds(lifetime, bounds));
2842 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2843 try!(self.print_path(path, false, 0));
2844 try!(space(&mut self.s));
2845 try!(self.word_space("="));
2846 try!(self.print_type(&ty));
2854 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2856 ast::ViewPathSimple(ident, ref path) => {
2857 try!(self.print_path(path, false, 0));
2859 if path.segments.last().unwrap().identifier.name !=
2861 try!(space(&mut self.s));
2862 try!(self.word_space("as"));
2863 try!(self.print_ident(ident));
2869 ast::ViewPathGlob(ref path) => {
2870 try!(self.print_path(path, false, 0));
2871 word(&mut self.s, "::*")
2874 ast::ViewPathList(ref path, ref idents) => {
2875 if path.segments.is_empty() {
2876 try!(word(&mut self.s, "{"));
2878 try!(self.print_path(path, false, 0));
2879 try!(word(&mut self.s, "::{"));
2881 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2883 ast::PathListItemKind::Ident { name, rename, .. } => {
2884 try!(s.print_ident(name));
2885 if let Some(ident) = rename {
2886 try!(space(&mut s.s));
2887 try!(s.word_space("as"));
2888 try!(s.print_ident(ident));
2892 ast::PathListItemKind::Mod { rename, .. } => {
2893 try!(word(&mut s.s, "self"));
2894 if let Some(ident) = rename {
2895 try!(space(&mut s.s));
2896 try!(s.word_space("as"));
2897 try!(s.print_ident(ident));
2903 word(&mut self.s, "}")
2908 pub fn print_mutability(&mut self,
2909 mutbl: ast::Mutability) -> io::Result<()> {
2911 ast::Mutability::Mutable => self.word_nbsp("mut"),
2912 ast::Mutability::Immutable => Ok(()),
2916 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2917 try!(self.print_mutability(mt.mutbl));
2918 self.print_type(&mt.ty)
2921 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2922 try!(self.ibox(INDENT_UNIT));
2923 match input.ty.node {
2924 ast::TyKind::Infer if is_closure => try!(self.print_pat(&input.pat)),
2926 if let Some(eself) = input.to_self() {
2927 try!(self.print_explicit_self(&eself));
2929 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2930 ident.node.name == keywords::Invalid.name()
2935 try!(self.print_pat(&input.pat));
2936 try!(word(&mut self.s, ":"));
2937 try!(space(&mut self.s));
2939 try!(self.print_type(&input.ty));
2946 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2947 if let ast::FunctionRetTy::Default(..) = decl.output {
2951 try!(self.space_if_not_bol());
2952 try!(self.ibox(INDENT_UNIT));
2953 try!(self.word_space("->"));
2955 ast::FunctionRetTy::None(_) =>
2956 try!(self.word_nbsp("!")),
2957 ast::FunctionRetTy::Default(..) => unreachable!(),
2958 ast::FunctionRetTy::Ty(ref ty) =>
2959 try!(self.print_type(&ty))
2964 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2969 pub fn print_ty_fn(&mut self,
2971 unsafety: ast::Unsafety,
2973 name: Option<ast::Ident>,
2974 generics: &ast::Generics)
2976 try!(self.ibox(INDENT_UNIT));
2977 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2978 try!(word(&mut self.s, "for"));
2979 try!(self.print_generics(generics));
2981 let generics = ast::Generics {
2982 lifetimes: Vec::new(),
2983 ty_params: P::new(),
2984 where_clause: ast::WhereClause {
2985 id: ast::DUMMY_NODE_ID,
2986 predicates: Vec::new(),
2989 try!(self.print_fn(decl,
2991 ast::Constness::NotConst,
2995 &ast::Visibility::Inherited));
2999 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3000 next_pos: Option<BytePos>)
3002 let cm = match self.cm {
3006 if let Some(ref cmnt) = self.next_comment() {
3007 if (*cmnt).style != comments::Trailing { return Ok(()) }
3008 let span_line = cm.lookup_char_pos(span.hi);
3009 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3010 let mut next = (*cmnt).pos + BytePos(1);
3011 if let Some(p) = next_pos {
3014 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3015 span_line.line == comment_line.line {
3016 self.print_comment(cmnt)?;
3017 self.cur_cmnt_and_lit.cur_cmnt += 1;
3023 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3024 // If there aren't any remaining comments, then we need to manually
3025 // make sure there is a line break at the end.
3026 if self.next_comment().is_none() {
3027 try!(hardbreak(&mut self.s));
3030 match self.next_comment() {
3032 try!(self.print_comment(cmnt));
3033 self.cur_cmnt_and_lit.cur_cmnt += 1;
3041 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3042 opt_abi: Option<Abi>)
3045 Some(Abi::Rust) => Ok(()),
3047 try!(self.word_nbsp("extern"));
3048 self.word_nbsp(&abi.to_string())
3054 pub fn print_extern_opt_abi(&mut self,
3055 opt_abi: Option<Abi>) -> io::Result<()> {
3058 try!(self.word_nbsp("extern"));
3059 self.word_nbsp(&abi.to_string())
3065 pub fn print_fn_header_info(&mut self,
3066 unsafety: ast::Unsafety,
3067 constness: ast::Constness,
3069 vis: &ast::Visibility) -> io::Result<()> {
3070 try!(word(&mut self.s, &visibility_qualified(vis, "")));
3073 ast::Constness::NotConst => {}
3074 ast::Constness::Const => try!(self.word_nbsp("const"))
3077 try!(self.print_unsafety(unsafety));
3079 if abi != Abi::Rust {
3080 try!(self.word_nbsp("extern"));
3081 try!(self.word_nbsp(&abi.to_string()));
3084 word(&mut self.s, "fn")
3087 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3089 ast::Unsafety::Normal => Ok(()),
3090 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3095 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3107 fn test_fun_to_string() {
3108 let abba_ident = token::str_to_ident("abba");
3110 let decl = ast::FnDecl {
3112 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3115 let generics = ast::Generics::default();
3116 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3117 ast::Constness::NotConst,
3118 abba_ident, &generics),
3123 fn test_variant_to_string() {
3124 let ident = token::str_to_ident("principal_skinner");
3126 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3129 // making this up as I go.... ?
3130 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3134 let varstr = variant_to_string(&var);
3135 assert_eq!(varstr, "principal_skinner");