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::{mod, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
15 use ast::{FnOnceUnboxedClosureKind};
16 use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound};
17 use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
18 use ast::{UnboxedClosureKind};
20 use owned_slice::OwnedSlice;
21 use attr::{AttrMetaMethods, AttributeMethods};
22 use codemap::{mod, CodeMap, BytePos};
24 use parse::token::{mod, BinOpToken, Token};
25 use parse::lexer::comments;
27 use print::pp::{mod, break_offset, word, space, zerobreak, hardbreak};
28 use print::pp::{Breaks, Consistent, Inconsistent, eof};
31 use std::{ascii, mem};
32 use std::io::{mod, IoResult};
34 pub enum AnnNode<'a> {
35 NodeIdent(&'a ast::Ident),
36 NodeName(&'a ast::Name),
37 NodeBlock(&'a ast::Block),
38 NodeItem(&'a ast::Item),
39 NodeExpr(&'a ast::Expr),
40 NodePat(&'a ast::Pat),
44 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
45 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
50 impl Copy for NoAnn {}
52 impl PpAnn for NoAnn {}
54 pub struct CurrentCommentAndLiteral {
59 impl Copy for CurrentCommentAndLiteral {}
61 pub struct State<'a> {
63 cm: Option<&'a CodeMap>,
64 comments: Option<Vec<comments::Comment> >,
65 literals: Option<Vec<comments::Literal> >,
66 cur_cmnt_and_lit: CurrentCommentAndLiteral,
67 boxes: Vec<pp::Breaks>,
69 encode_idents_with_hygiene: bool,
72 pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> {
73 static NO_ANN: NoAnn = NoAnn;
74 rust_printer_annotated(writer, &NO_ANN)
77 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>,
78 ann: &'a PpAnn) -> State<'a> {
80 s: pp::mk_printer(writer, default_columns),
84 cur_cmnt_and_lit: CurrentCommentAndLiteral {
90 encode_idents_with_hygiene: false,
94 #[allow(non_upper_case_globals)]
95 pub const indent_unit: uint = 4u;
97 #[allow(non_upper_case_globals)]
98 pub const default_columns: uint = 78u;
100 /// Requires you to pass an input filename and reader so that
101 /// it can scan the input text for comments and literals to
103 pub fn print_crate<'a>(cm: &'a CodeMap,
104 span_diagnostic: &diagnostic::SpanHandler,
107 input: &mut io::Reader,
108 out: Box<io::Writer+'static>,
110 is_expanded: bool) -> IoResult<()> {
111 let mut s = State::new_from_input(cm,
118 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
119 try!(s.print_remaining_comments());
124 pub fn new_from_input(cm: &'a CodeMap,
125 span_diagnostic: &diagnostic::SpanHandler,
127 input: &mut io::Reader,
128 out: Box<io::Writer+'static>,
130 is_expanded: bool) -> State<'a> {
131 let (cmnts, lits) = comments::gather_comments_and_literals(
141 // If the code is post expansion, don't use the table of
142 // literals, since it doesn't correspond with the literals
143 // in the AST anymore.
144 if is_expanded { None } else { Some(lits) })
147 pub fn new(cm: &'a CodeMap,
148 out: Box<io::Writer+'static>,
150 comments: Option<Vec<comments::Comment>>,
151 literals: Option<Vec<comments::Literal>>) -> State<'a> {
153 s: pp::mk_printer(out, default_columns),
157 cur_cmnt_and_lit: CurrentCommentAndLiteral {
163 encode_idents_with_hygiene: false,
168 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
169 use std::raw::TraitObject;
170 let mut s = rust_printer(box Vec::new());
172 eof(&mut s.s).unwrap();
174 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
175 // that we "know" to be a `Vec<u8>` that works around the lack of checked
177 let obj: &TraitObject = mem::transmute(&s.s.out);
178 mem::transmute::<*mut (), &Vec<u8>>(obj.data)
180 String::from_utf8(wr.clone()).unwrap()
183 pub fn binop_to_string(op: BinOpToken) -> &'static str {
189 token::Percent => "%",
198 pub fn token_to_string(tok: &Token) -> String {
200 token::Eq => "=".into_string(),
201 token::Lt => "<".into_string(),
202 token::Le => "<=".into_string(),
203 token::EqEq => "==".into_string(),
204 token::Ne => "!=".into_string(),
205 token::Ge => ">=".into_string(),
206 token::Gt => ">".into_string(),
207 token::Not => "!".into_string(),
208 token::Tilde => "~".into_string(),
209 token::OrOr => "||".into_string(),
210 token::AndAnd => "&&".into_string(),
211 token::BinOp(op) => binop_to_string(op).into_string(),
212 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
214 /* Structural symbols */
215 token::At => "@".into_string(),
216 token::Dot => ".".into_string(),
217 token::DotDot => "..".into_string(),
218 token::DotDotDot => "...".into_string(),
219 token::Comma => ",".into_string(),
220 token::Semi => ";".into_string(),
221 token::Colon => ":".into_string(),
222 token::ModSep => "::".into_string(),
223 token::RArrow => "->".into_string(),
224 token::LArrow => "<-".into_string(),
225 token::FatArrow => "=>".into_string(),
226 token::OpenDelim(token::Paren) => "(".into_string(),
227 token::CloseDelim(token::Paren) => ")".into_string(),
228 token::OpenDelim(token::Bracket) => "[".into_string(),
229 token::CloseDelim(token::Bracket) => "]".into_string(),
230 token::OpenDelim(token::Brace) => "{".into_string(),
231 token::CloseDelim(token::Brace) => "}".into_string(),
232 token::Pound => "#".into_string(),
233 token::Dollar => "$".into_string(),
234 token::Question => "?".into_string(),
237 token::Literal(lit, suf) => {
238 let mut out = match lit {
239 token::Byte(b) => format!("b'{}'", b.as_str()),
240 token::Char(c) => format!("'{}'", c.as_str()),
241 token::Float(c) => c.as_str().into_string(),
242 token::Integer(c) => c.as_str().into_string(),
243 token::Str_(s) => format!("\"{}\"", s.as_str()),
244 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
247 token::Binary(v) => format!("b\"{}\"", v.as_str()),
248 token::BinaryRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
253 if let Some(s) = suf {
254 out.push_str(s.as_str())
260 /* Name components */
261 token::Ident(s, _) => token::get_ident(s).get().into_string(),
262 token::Lifetime(s) => format!("{}", token::get_ident(s)),
263 token::Underscore => "_".into_string(),
266 token::DocComment(s) => s.as_str().into_string(),
267 token::SubstNt(s, _) => format!("${}", s),
268 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
269 token::Eof => "<eof>".into_string(),
270 token::Whitespace => " ".into_string(),
271 token::Comment => "/* */".into_string(),
272 token::Shebang(s) => format!("/* shebang: {}*/", s.as_str()),
274 token::Interpolated(ref nt) => match *nt {
275 token::NtExpr(ref e) => expr_to_string(&**e),
276 token::NtMeta(ref e) => meta_item_to_string(&**e),
277 token::NtTy(ref e) => ty_to_string(&**e),
278 token::NtPath(ref e) => path_to_string(&**e),
279 token::NtItem(..) => "an interpolated item".into_string(),
280 token::NtBlock(..) => "an interpolated block".into_string(),
281 token::NtStmt(..) => "an interpolated statement".into_string(),
282 token::NtPat(..) => "an interpolated pattern".into_string(),
283 token::NtIdent(..) => "an interpolated identifier".into_string(),
284 token::NtTT(..) => "an interpolated tt".into_string(),
289 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
290 // after we revise the syntax::ext::quote::ToToken impls to go directly
291 // to token-trees instead of thing -> string -> token-trees.
293 macro_rules! thing_to_string_impls {
294 ($to_string:ident) => {
296 pub fn ty_to_string(ty: &ast::Ty) -> String {
297 $to_string(|s| s.print_type(ty))
300 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
301 $to_string(|s| s.print_bounds("", bounds))
304 pub fn pat_to_string(pat: &ast::Pat) -> String {
305 $to_string(|s| s.print_pat(pat))
308 pub fn arm_to_string(arm: &ast::Arm) -> String {
309 $to_string(|s| s.print_arm(arm))
312 pub fn expr_to_string(e: &ast::Expr) -> String {
313 $to_string(|s| s.print_expr(e))
316 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
317 $to_string(|s| s.print_lifetime(e))
320 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
321 $to_string(|s| s.print_tt(tt))
324 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
325 $to_string(|s| s.print_tts(tts))
328 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
329 $to_string(|s| s.print_stmt(stmt))
332 pub fn item_to_string(i: &ast::Item) -> String {
333 $to_string(|s| s.print_item(i))
336 pub fn view_item_to_string(i: &ast::ViewItem) -> String {
337 $to_string(|s| s.print_view_item(i))
340 pub fn generics_to_string(generics: &ast::Generics) -> String {
341 $to_string(|s| s.print_generics(generics))
344 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
345 $to_string(|s| s.print_ty_method(p))
348 pub fn method_to_string(p: &ast::Method) -> String {
349 $to_string(|s| s.print_method(p))
352 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
353 $to_string(|s| s.print_fn_block_args(p, None))
356 pub fn path_to_string(p: &ast::Path) -> String {
357 $to_string(|s| s.print_path(p, false))
360 pub fn ident_to_string(id: &ast::Ident) -> String {
361 $to_string(|s| s.print_ident(*id))
364 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
365 opt_explicit_self: Option<&ast::ExplicitSelf_>,
366 generics: &ast::Generics) -> String {
368 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
369 name, generics, opt_explicit_self, ast::Inherited));
370 try!(s.end()); // Close the head box
371 s.end() // Close the outer box
375 pub fn block_to_string(blk: &ast::Block) -> String {
377 // containing cbox, will be closed by print-block at }
378 try!(s.cbox(indent_unit));
379 // head-ibox, will be closed by print-block after {
385 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
386 $to_string(|s| s.print_meta_item(mi))
389 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
390 $to_string(|s| s.print_attribute(attr))
393 pub fn lit_to_string(l: &ast::Lit) -> String {
394 $to_string(|s| s.print_literal(l))
397 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
398 $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
401 pub fn variant_to_string(var: &ast::Variant) -> String {
402 $to_string(|s| s.print_variant(var))
405 pub fn arg_to_string(arg: &ast::Arg) -> String {
406 $to_string(|s| s.print_arg(arg))
409 pub fn mac_to_string(arg: &ast::Mac) -> String {
410 $to_string(|s| s.print_mac(arg))
415 thing_to_string_impls!(to_string)
417 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
418 // after we revise the syntax::ext::quote::ToToken impls to go directly
419 // to token-trees instea of thing -> string -> token-trees.
421 pub mod with_hygiene {
424 use std::io::IoResult;
425 use super::indent_unit;
427 // This function is the trick that all the rest of the routines
429 pub fn to_string_hyg(f: |&mut super::State| -> IoResult<()>) -> String {
430 super::to_string(|s| {
431 s.encode_idents_with_hygiene = true;
436 thing_to_string_impls!(to_string_hyg)
439 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
441 ast::Public => format!("pub {}", s),
442 ast::Inherited => s.to_string()
446 fn needs_parentheses(expr: &ast::Expr) -> bool {
448 ast::ExprAssign(..) | ast::ExprBinary(..) |
449 ast::ExprClosure(..) | ast::ExprProc(..) |
450 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
456 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
457 self.boxes.push(pp::Inconsistent);
458 pp::ibox(&mut self.s, u)
461 pub fn end(&mut self) -> IoResult<()> {
462 self.boxes.pop().unwrap();
466 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
467 self.boxes.push(pp::Consistent);
468 pp::cbox(&mut self.s, u)
472 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
474 pp::rbox(&mut self.s, u, b)
477 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
479 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
480 try!(word(&mut self.s, w));
484 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
485 try!(word(&mut self.s, w));
489 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
491 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
493 pub fn head(&mut self, w: &str) -> IoResult<()> {
494 // outer-box is consistent
495 try!(self.cbox(indent_unit));
496 // head-box is inconsistent
497 try!(self.ibox(w.len() + 1));
498 // keyword that starts the head
500 try!(self.word_nbsp(w));
505 pub fn bopen(&mut self) -> IoResult<()> {
506 try!(word(&mut self.s, "{"));
507 self.end() // close the head-box
510 pub fn bclose_(&mut self, span: codemap::Span,
511 indented: uint) -> IoResult<()> {
512 self.bclose_maybe_open(span, indented, true)
514 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
515 indented: uint, close_box: bool) -> IoResult<()> {
516 try!(self.maybe_print_comment(span.hi));
517 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
518 try!(word(&mut self.s, "}"));
520 try!(self.end()); // close the outer-box
524 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
525 self.bclose_(span, indent_unit)
528 pub fn is_begin(&mut self) -> bool {
529 match self.s.last_token() { pp::Begin(_) => true, _ => false }
532 pub fn is_end(&mut self) -> bool {
533 match self.s.last_token() { pp::End => true, _ => false }
536 // is this the beginning of a line?
537 pub fn is_bol(&mut self) -> bool {
538 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
541 pub fn in_cbox(&self) -> bool {
542 match self.boxes.last() {
543 Some(&last_box) => last_box == pp::Consistent,
548 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
550 try!(hardbreak(&mut self.s))
554 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
555 if !self.is_bol() { try!(space(&mut self.s)); }
558 pub fn break_offset_if_not_bol(&mut self, n: uint,
559 off: int) -> IoResult<()> {
561 break_offset(&mut self.s, n, off)
563 if off != 0 && self.s.last_token().is_hardbreak_tok() {
564 // We do something pretty sketchy here: tuck the nonzero
565 // offset-adjustment we were going to deposit along with the
566 // break into the previous hardbreak.
567 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
573 // Synthesizes a comment that was not textually present in the original source
575 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
576 try!(word(&mut self.s, "/*"));
577 try!(space(&mut self.s));
578 try!(word(&mut self.s, text.as_slice()));
579 try!(space(&mut self.s));
580 word(&mut self.s, "*/")
583 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
584 op: |&mut State, &T| -> IoResult<()>)
586 try!(self.rbox(0u, b));
587 let mut first = true;
588 for elt in elts.iter() {
589 if first { first = false; } else { try!(self.word_space(",")); }
596 pub fn commasep_cmnt<T>(
600 op: |&mut State, &T| -> IoResult<()>,
601 get_span: |&T| -> codemap::Span) -> IoResult<()> {
602 try!(self.rbox(0u, b));
603 let len = elts.len();
605 for elt in elts.iter() {
606 try!(self.maybe_print_comment(get_span(elt).hi));
610 try!(word(&mut self.s, ","));
611 try!(self.maybe_print_trailing_comment(get_span(elt),
612 Some(get_span(&elts[i]).hi)));
613 try!(self.space_if_not_bol());
619 pub fn commasep_exprs(&mut self, b: Breaks,
620 exprs: &[P<ast::Expr>]) -> IoResult<()> {
621 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
624 pub fn print_mod(&mut self, _mod: &ast::Mod,
625 attrs: &[ast::Attribute]) -> IoResult<()> {
626 try!(self.print_inner_attributes(attrs));
627 for vitem in _mod.view_items.iter() {
628 try!(self.print_view_item(vitem));
630 for item in _mod.items.iter() {
631 try!(self.print_item(&**item));
636 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
637 attrs: &[ast::Attribute]) -> IoResult<()> {
638 try!(self.print_inner_attributes(attrs));
639 for vitem in nmod.view_items.iter() {
640 try!(self.print_view_item(vitem));
642 for item in nmod.items.iter() {
643 try!(self.print_foreign_item(&**item));
648 pub fn print_opt_lifetime(&mut self,
649 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
650 for l in lifetime.iter() {
651 try!(self.print_lifetime(l));
657 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
658 try!(self.maybe_print_comment(ty.span.lo));
661 ast::TyVec(ref ty) => {
662 try!(word(&mut self.s, "["));
663 try!(self.print_type(&**ty));
664 try!(word(&mut self.s, "]"));
666 ast::TyPtr(ref mt) => {
667 try!(word(&mut self.s, "*"));
669 ast::MutMutable => try!(self.word_nbsp("mut")),
670 ast::MutImmutable => try!(self.word_nbsp("const")),
672 try!(self.print_type(&*mt.ty));
674 ast::TyRptr(ref lifetime, ref mt) => {
675 try!(word(&mut self.s, "&"));
676 try!(self.print_opt_lifetime(lifetime));
677 try!(self.print_mt(mt));
679 ast::TyTup(ref elts) => {
681 try!(self.commasep(Inconsistent, elts.as_slice(),
682 |s, ty| s.print_type(&**ty)));
684 try!(word(&mut self.s, ","));
688 ast::TyParen(ref typ) => {
690 try!(self.print_type(&**typ));
693 ast::TyBareFn(ref f) => {
694 let generics = ast::Generics {
695 lifetimes: f.lifetimes.clone(),
696 ty_params: OwnedSlice::empty(),
697 where_clause: ast::WhereClause {
698 id: ast::DUMMY_NODE_ID,
699 predicates: Vec::new(),
702 try!(self.print_ty_fn(Some(f.abi),
708 &OwnedSlice::empty(),
712 ast::TyClosure(ref f) => {
713 let generics = ast::Generics {
714 lifetimes: f.lifetimes.clone(),
715 ty_params: OwnedSlice::empty(),
716 where_clause: ast::WhereClause {
717 id: ast::DUMMY_NODE_ID,
718 predicates: Vec::new(),
721 try!(self.print_ty_fn(None,
731 ast::TyProc(ref f) => {
732 let generics = ast::Generics {
733 lifetimes: f.lifetimes.clone(),
734 ty_params: OwnedSlice::empty(),
735 where_clause: ast::WhereClause {
736 id: ast::DUMMY_NODE_ID,
737 predicates: Vec::new(),
740 try!(self.print_ty_fn(None,
750 ast::TyPath(ref path, _) => {
751 try!(self.print_path(path, false));
753 ast::TyObjectSum(ref ty, ref bounds) => {
754 try!(self.print_type(&**ty));
755 try!(self.print_bounds("+", bounds.as_slice()));
757 ast::TyPolyTraitRef(ref bounds) => {
758 try!(self.print_bounds("", bounds.as_slice()));
760 ast::TyQPath(ref qpath) => {
761 try!(word(&mut self.s, "<"));
762 try!(self.print_type(&*qpath.self_type));
763 try!(space(&mut self.s));
764 try!(self.word_space("as"));
765 try!(self.print_trait_ref(&*qpath.trait_ref));
766 try!(word(&mut self.s, ">"));
767 try!(word(&mut self.s, "::"));
768 try!(self.print_ident(qpath.item_name));
770 ast::TyFixedLengthVec(ref ty, ref v) => {
771 try!(word(&mut self.s, "["));
772 try!(self.print_type(&**ty));
773 try!(word(&mut self.s, ", .."));
774 try!(self.print_expr(&**v));
775 try!(word(&mut self.s, "]"));
777 ast::TyTypeof(ref e) => {
778 try!(word(&mut self.s, "typeof("));
779 try!(self.print_expr(&**e));
780 try!(word(&mut self.s, ")"));
783 try!(word(&mut self.s, "_"));
789 pub fn print_foreign_item(&mut self,
790 item: &ast::ForeignItem) -> IoResult<()> {
791 try!(self.hardbreak_if_not_bol());
792 try!(self.maybe_print_comment(item.span.lo));
793 try!(self.print_outer_attributes(item.attrs.as_slice()));
795 ast::ForeignItemFn(ref decl, ref generics) => {
796 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
798 try!(self.end()); // end head-ibox
799 try!(word(&mut self.s, ";"));
800 self.end() // end the outer fn box
802 ast::ForeignItemStatic(ref t, m) => {
803 try!(self.head(visibility_qualified(item.vis,
804 "static").as_slice()));
806 try!(self.word_space("mut"));
808 try!(self.print_ident(item.ident));
809 try!(self.word_space(":"));
810 try!(self.print_type(&**t));
811 try!(word(&mut self.s, ";"));
812 try!(self.end()); // end the head-ibox
813 self.end() // end the outer cbox
818 fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
821 try!(self.print_outer_attributes(typedef.attrs[]));
822 try!(self.word_space("type"));
823 try!(self.print_ty_param(&typedef.ty_param));
824 word(&mut self.s, ";")
827 fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
828 try!(self.word_space("type"));
829 try!(self.print_ident(typedef.ident));
830 try!(space(&mut self.s));
831 try!(self.word_space("="));
832 try!(self.print_type(&*typedef.typ));
833 word(&mut self.s, ";")
836 /// Pretty-print an item
837 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
838 try!(self.hardbreak_if_not_bol());
839 try!(self.maybe_print_comment(item.span.lo));
840 try!(self.print_outer_attributes(item.attrs.as_slice()));
841 try!(self.ann.pre(self, NodeItem(item)));
843 ast::ItemStatic(ref ty, m, ref expr) => {
844 try!(self.head(visibility_qualified(item.vis,
845 "static").as_slice()));
846 if m == ast::MutMutable {
847 try!(self.word_space("mut"));
849 try!(self.print_ident(item.ident));
850 try!(self.word_space(":"));
851 try!(self.print_type(&**ty));
852 try!(space(&mut self.s));
853 try!(self.end()); // end the head-ibox
855 try!(self.word_space("="));
856 try!(self.print_expr(&**expr));
857 try!(word(&mut self.s, ";"));
858 try!(self.end()); // end the outer cbox
860 ast::ItemConst(ref ty, ref expr) => {
861 try!(self.head(visibility_qualified(item.vis,
862 "const").as_slice()));
863 try!(self.print_ident(item.ident));
864 try!(self.word_space(":"));
865 try!(self.print_type(&**ty));
866 try!(space(&mut self.s));
867 try!(self.end()); // end the head-ibox
869 try!(self.word_space("="));
870 try!(self.print_expr(&**expr));
871 try!(word(&mut self.s, ";"));
872 try!(self.end()); // end the outer cbox
874 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
884 try!(word(&mut self.s, " "));
885 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
887 ast::ItemMod(ref _mod) => {
888 try!(self.head(visibility_qualified(item.vis,
890 try!(self.print_ident(item.ident));
893 try!(self.print_mod(_mod, item.attrs.as_slice()));
894 try!(self.bclose(item.span));
896 ast::ItemForeignMod(ref nmod) => {
897 try!(self.head("extern"));
898 try!(self.word_nbsp(nmod.abi.to_string().as_slice()));
900 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
901 try!(self.bclose(item.span));
903 ast::ItemTy(ref ty, ref params) => {
904 try!(self.ibox(indent_unit));
906 try!(self.word_nbsp(visibility_qualified(item.vis,
907 "type").as_slice()));
908 try!(self.print_ident(item.ident));
909 try!(self.print_generics(params));
910 try!(self.end()); // end the inner ibox
912 try!(space(&mut self.s));
913 try!(self.word_space("="));
914 try!(self.print_type(&**ty));
915 try!(self.print_where_clause(params));
916 try!(word(&mut self.s, ";"));
917 try!(self.end()); // end the outer ibox
919 ast::ItemEnum(ref enum_definition, ref params) => {
920 try!(self.print_enum_def(
928 ast::ItemStruct(ref struct_def, ref generics) => {
929 try!(self.head(visibility_qualified(item.vis,"struct").as_slice()));
930 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
933 ast::ItemImpl(ref generics,
937 try!(self.head(visibility_qualified(item.vis,
938 "impl").as_slice()));
939 if generics.is_parameterized() {
940 try!(self.print_generics(generics));
941 try!(space(&mut self.s));
946 try!(self.print_trait_ref(t));
947 try!(space(&mut self.s));
948 try!(self.word_space("for"));
953 try!(self.print_type(&**ty));
954 try!(self.print_where_clause(generics));
956 try!(space(&mut self.s));
958 try!(self.print_inner_attributes(item.attrs.as_slice()));
959 for impl_item in impl_items.iter() {
961 ast::MethodImplItem(ref meth) => {
962 try!(self.print_method(&**meth));
964 ast::TypeImplItem(ref typ) => {
965 try!(self.print_typedef(&**typ));
969 try!(self.bclose(item.span));
971 ast::ItemTrait(ref generics, ref unbound, ref bounds, ref methods) => {
972 try!(self.head(visibility_qualified(item.vis,
973 "trait").as_slice()));
974 try!(self.print_ident(item.ident));
975 try!(self.print_generics(generics));
976 if let &Some(ref tref) = unbound {
977 try!(space(&mut self.s));
978 try!(self.word_space("for"));
979 try!(self.print_trait_ref(tref));
980 try!(word(&mut self.s, "?"));
982 try!(self.print_bounds(":", bounds.as_slice()));
983 try!(self.print_where_clause(generics));
984 try!(word(&mut self.s, " "));
986 for meth in methods.iter() {
987 try!(self.print_trait_method(meth));
989 try!(self.bclose(item.span));
991 // I think it's reasonable to hide the context here:
992 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
994 try!(self.print_visibility(item.vis));
995 try!(self.print_path(pth, false));
996 try!(word(&mut self.s, "! "));
997 try!(self.print_ident(item.ident));
998 try!(self.cbox(indent_unit));
1000 try!(self.print_tts(tts.as_slice()));
1001 try!(self.pclose());
1005 self.ann.post(self, NodeItem(item))
1008 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
1009 self.print_path(&t.path, false)
1012 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
1013 if !t.bound_lifetimes.is_empty() {
1014 try!(word(&mut self.s, "for<"));
1015 for lifetime_def in t.bound_lifetimes.iter() {
1016 try!(self.print_lifetime_def(lifetime_def));
1018 try!(word(&mut self.s, ">"));
1021 self.print_trait_ref(&t.trait_ref)
1024 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1025 generics: &ast::Generics, ident: ast::Ident,
1026 span: codemap::Span,
1027 visibility: ast::Visibility) -> IoResult<()> {
1028 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
1029 try!(self.print_ident(ident));
1030 try!(self.print_generics(generics));
1031 try!(self.print_where_clause(generics));
1032 try!(space(&mut self.s));
1033 self.print_variants(enum_definition.variants.as_slice(), span)
1036 pub fn print_variants(&mut self,
1037 variants: &[P<ast::Variant>],
1038 span: codemap::Span) -> IoResult<()> {
1040 for v in variants.iter() {
1041 try!(self.space_if_not_bol());
1042 try!(self.maybe_print_comment(v.span.lo));
1043 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
1044 try!(self.ibox(indent_unit));
1045 try!(self.print_variant(&**v));
1046 try!(word(&mut self.s, ","));
1048 try!(self.maybe_print_trailing_comment(v.span, None));
1053 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
1055 ast::Public => self.word_nbsp("pub"),
1056 ast::Inherited => Ok(())
1060 pub fn print_struct(&mut self,
1061 struct_def: &ast::StructDef,
1062 generics: &ast::Generics,
1064 span: codemap::Span) -> IoResult<()> {
1065 try!(self.print_ident(ident));
1066 try!(self.print_generics(generics));
1067 if ast_util::struct_def_is_tuple_like(struct_def) {
1068 if !struct_def.fields.is_empty() {
1071 Inconsistent, struct_def.fields.as_slice(),
1073 match field.node.kind {
1074 ast::NamedField(..) => panic!("unexpected named field"),
1075 ast::UnnamedField(vis) => {
1076 try!(s.print_visibility(vis));
1077 try!(s.maybe_print_comment(field.span.lo));
1078 s.print_type(&*field.node.ty)
1083 try!(self.pclose());
1085 try!(word(&mut self.s, ";"));
1087 self.end() // close the outer-box
1091 try!(self.hardbreak_if_not_bol());
1093 for field in struct_def.fields.iter() {
1094 match field.node.kind {
1095 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1096 ast::NamedField(ident, visibility) => {
1097 try!(self.hardbreak_if_not_bol());
1098 try!(self.maybe_print_comment(field.span.lo));
1099 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
1100 try!(self.print_visibility(visibility));
1101 try!(self.print_ident(ident));
1102 try!(self.word_nbsp(":"));
1103 try!(self.print_type(&*field.node.ty));
1104 try!(word(&mut self.s, ","));
1113 /// This doesn't deserve to be called "pretty" printing, but it should be
1114 /// meaning-preserving. A quick hack that might help would be to look at the
1115 /// spans embedded in the TTs to decide where to put spaces and newlines.
1116 /// But it'd be better to parse these according to the grammar of the
1117 /// appropriate macro, transcribe back into the grammar we just parsed from,
1118 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1119 /// expression arguments as expressions). It can be done! I think.
1120 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1122 ast::TtToken(_, ref tk) => {
1123 try!(word(&mut self.s, token_to_string(tk).as_slice()));
1125 parse::token::DocComment(..) => {
1126 hardbreak(&mut self.s)
1131 ast::TtDelimited(_, ref delimed) => {
1132 try!(word(&mut self.s, token_to_string(&delimed.open_token()).as_slice()));
1133 try!(space(&mut self.s));
1134 try!(self.print_tts(delimed.tts.as_slice()));
1135 try!(space(&mut self.s));
1136 word(&mut self.s, token_to_string(&delimed.close_token()).as_slice())
1138 ast::TtSequence(_, ref seq) => {
1139 try!(word(&mut self.s, "$("));
1140 for tt_elt in seq.tts.iter() {
1141 try!(self.print_tt(tt_elt));
1143 try!(word(&mut self.s, ")"));
1144 match seq.separator {
1146 try!(word(&mut self.s, token_to_string(tk).as_slice()));
1151 ast::ZeroOrMore => word(&mut self.s, "*"),
1152 ast::OneOrMore => word(&mut self.s, "+"),
1158 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1160 for (i, tt) in tts.iter().enumerate() {
1162 try!(space(&mut self.s));
1164 try!(self.print_tt(tt));
1169 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1170 try!(self.print_visibility(v.node.vis));
1172 ast::TupleVariantKind(ref args) => {
1173 try!(self.print_ident(v.node.name));
1174 if !args.is_empty() {
1176 try!(self.commasep(Consistent,
1178 |s, arg| s.print_type(&*arg.ty)));
1179 try!(self.pclose());
1182 ast::StructVariantKind(ref struct_def) => {
1183 try!(self.head(""));
1184 let generics = ast_util::empty_generics();
1185 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1188 match v.node.disr_expr {
1190 try!(space(&mut self.s));
1191 try!(self.word_space("="));
1192 self.print_expr(&**d)
1198 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1199 try!(self.hardbreak_if_not_bol());
1200 try!(self.maybe_print_comment(m.span.lo));
1201 try!(self.print_outer_attributes(m.attrs.as_slice()));
1202 try!(self.print_ty_fn(None,
1208 &OwnedSlice::empty(),
1210 Some(&m.explicit_self.node)));
1211 word(&mut self.s, ";")
1214 pub fn print_trait_method(&mut self,
1215 m: &ast::TraitItem) -> IoResult<()> {
1217 RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1218 ProvidedMethod(ref m) => self.print_method(&**m),
1219 TypeTraitItem(ref t) => self.print_associated_type(&**t),
1223 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1225 MethodImplItem(ref m) => self.print_method(&**m),
1226 TypeImplItem(ref td) => self.print_typedef(&**td),
1230 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1231 try!(self.hardbreak_if_not_bol());
1232 try!(self.maybe_print_comment(meth.span.lo));
1233 try!(self.print_outer_attributes(meth.attrs.as_slice()));
1235 ast::MethDecl(ident,
1243 try!(self.print_fn(&**decl,
1248 Some(&explicit_self.node),
1250 try!(word(&mut self.s, " "));
1251 self.print_block_with_attrs(&**body, meth.attrs.as_slice())
1253 ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1255 // code copied from ItemMac:
1256 try!(self.print_path(pth, false));
1257 try!(word(&mut self.s, "! "));
1258 try!(self.cbox(indent_unit));
1260 try!(self.print_tts(tts.as_slice()));
1261 try!(self.pclose());
1267 pub fn print_outer_attributes(&mut self,
1268 attrs: &[ast::Attribute]) -> IoResult<()> {
1270 for attr in attrs.iter() {
1271 match attr.node.style {
1273 try!(self.print_attribute(attr));
1276 _ => {/* fallthrough */ }
1280 try!(self.hardbreak_if_not_bol());
1285 pub fn print_inner_attributes(&mut self,
1286 attrs: &[ast::Attribute]) -> IoResult<()> {
1288 for attr in attrs.iter() {
1289 match attr.node.style {
1291 try!(self.print_attribute(attr));
1294 _ => {/* fallthrough */ }
1298 try!(self.hardbreak_if_not_bol());
1303 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1304 try!(self.hardbreak_if_not_bol());
1305 try!(self.maybe_print_comment(attr.span.lo));
1306 if attr.node.is_sugared_doc {
1307 word(&mut self.s, attr.value_str().unwrap().get())
1309 match attr.node.style {
1310 ast::AttrInner => try!(word(&mut self.s, "#![")),
1311 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1313 try!(self.print_meta_item(&*attr.meta()));
1314 word(&mut self.s, "]")
1319 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1320 try!(self.maybe_print_comment(st.span.lo));
1322 ast::StmtDecl(ref decl, _) => {
1323 try!(self.print_decl(&**decl));
1325 ast::StmtExpr(ref expr, _) => {
1326 try!(self.space_if_not_bol());
1327 try!(self.print_expr(&**expr));
1329 ast::StmtSemi(ref expr, _) => {
1330 try!(self.space_if_not_bol());
1331 try!(self.print_expr(&**expr));
1332 try!(word(&mut self.s, ";"));
1334 ast::StmtMac(ref mac, semi) => {
1335 try!(self.space_if_not_bol());
1336 try!(self.print_mac(mac));
1338 try!(word(&mut self.s, ";"));
1342 if parse::classify::stmt_ends_with_semi(&st.node) {
1343 try!(word(&mut self.s, ";"));
1345 self.maybe_print_trailing_comment(st.span, None)
1348 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1349 self.print_block_with_attrs(blk, &[])
1352 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1353 self.print_block_unclosed_indent(blk, indent_unit)
1356 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1357 indented: uint) -> IoResult<()> {
1358 self.print_block_maybe_unclosed(blk, indented, &[], false)
1361 pub fn print_block_with_attrs(&mut self,
1363 attrs: &[ast::Attribute]) -> IoResult<()> {
1364 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1367 pub fn print_block_maybe_unclosed(&mut self,
1370 attrs: &[ast::Attribute],
1371 close_box: bool) -> IoResult<()> {
1373 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1374 ast::DefaultBlock => ()
1376 try!(self.maybe_print_comment(blk.span.lo));
1377 try!(self.ann.pre(self, NodeBlock(blk)));
1380 try!(self.print_inner_attributes(attrs));
1382 for vi in blk.view_items.iter() {
1383 try!(self.print_view_item(vi));
1385 for st in blk.stmts.iter() {
1386 try!(self.print_stmt(&**st));
1390 try!(self.space_if_not_bol());
1391 try!(self.print_expr(&**expr));
1392 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1396 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1397 self.ann.post(self, NodeBlock(blk))
1400 fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1404 // "another else-if"
1405 ast::ExprIf(ref i, ref then, ref e) => {
1406 try!(self.cbox(indent_unit - 1u));
1407 try!(self.ibox(0u));
1408 try!(word(&mut self.s, " else if "));
1409 try!(self.print_expr(&**i));
1410 try!(space(&mut self.s));
1411 try!(self.print_block(&**then));
1412 self.print_else(e.as_ref().map(|e| &**e))
1414 // "another else-if-let"
1415 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1416 try!(self.cbox(indent_unit - 1u));
1417 try!(self.ibox(0u));
1418 try!(word(&mut self.s, " else if let "));
1419 try!(self.print_pat(&**pat));
1420 try!(space(&mut self.s));
1421 try!(self.word_space("="));
1422 try!(self.print_expr(&**expr));
1423 try!(space(&mut self.s));
1424 try!(self.print_block(&**then));
1425 self.print_else(e.as_ref().map(|e| &**e))
1428 ast::ExprBlock(ref b) => {
1429 try!(self.cbox(indent_unit - 1u));
1430 try!(self.ibox(0u));
1431 try!(word(&mut self.s, " else "));
1432 self.print_block(&**b)
1434 // BLEAH, constraints would be great here
1436 panic!("print_if saw if with weird alternative");
1444 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1445 elseopt: Option<&ast::Expr>) -> IoResult<()> {
1446 try!(self.head("if"));
1447 try!(self.print_expr(test));
1448 try!(space(&mut self.s));
1449 try!(self.print_block(blk));
1450 self.print_else(elseopt)
1453 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1454 elseopt: Option<&ast::Expr>) -> IoResult<()> {
1455 try!(self.head("if let"));
1456 try!(self.print_pat(pat));
1457 try!(space(&mut self.s));
1458 try!(self.word_space("="));
1459 try!(self.print_expr(expr));
1460 try!(space(&mut self.s));
1461 try!(self.print_block(blk));
1462 self.print_else(elseopt)
1465 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1467 // I think it's reasonable to hide the ctxt here:
1468 ast::MacInvocTT(ref pth, ref tts, _) => {
1469 try!(self.print_path(pth, false));
1470 try!(word(&mut self.s, "!"));
1472 try!(self.print_tts(tts.as_slice()));
1479 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1481 try!(self.commasep_exprs(Inconsistent, args));
1485 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1486 let needs_par = needs_parentheses(expr);
1490 try!(self.print_expr(expr));
1492 try!(self.pclose());
1497 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1498 try!(self.maybe_print_comment(expr.span.lo));
1499 try!(self.ibox(indent_unit));
1500 try!(self.ann.pre(self, NodeExpr(expr)));
1502 ast::ExprBox(ref p, ref e) => {
1503 try!(word(&mut self.s, "box"));
1504 try!(word(&mut self.s, "("));
1505 try!(self.print_expr(&**p));
1506 try!(self.word_space(")"));
1507 try!(self.print_expr(&**e));
1509 ast::ExprVec(ref exprs) => {
1510 try!(self.ibox(indent_unit));
1511 try!(word(&mut self.s, "["));
1512 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1513 try!(word(&mut self.s, "]"));
1517 ast::ExprRepeat(ref element, ref count) => {
1518 try!(self.ibox(indent_unit));
1519 try!(word(&mut self.s, "["));
1520 try!(self.print_expr(&**element));
1521 try!(word(&mut self.s, ","));
1522 try!(word(&mut self.s, ".."));
1523 try!(self.print_expr(&**count));
1524 try!(word(&mut self.s, "]"));
1528 ast::ExprStruct(ref path, ref fields, ref wth) => {
1529 try!(self.print_path(path, true));
1530 try!(word(&mut self.s, "{"));
1531 try!(self.commasep_cmnt(
1535 try!(s.ibox(indent_unit));
1536 try!(s.print_ident(field.ident.node));
1537 try!(s.word_space(":"));
1538 try!(s.print_expr(&*field.expr));
1544 try!(self.ibox(indent_unit));
1545 if !fields.is_empty() {
1546 try!(word(&mut self.s, ","));
1547 try!(space(&mut self.s));
1549 try!(word(&mut self.s, ".."));
1550 try!(self.print_expr(&**expr));
1553 _ => try!(word(&mut self.s, ","))
1555 try!(word(&mut self.s, "}"));
1557 ast::ExprTup(ref exprs) => {
1559 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1560 if exprs.len() == 1 {
1561 try!(word(&mut self.s, ","));
1563 try!(self.pclose());
1565 ast::ExprCall(ref func, ref args) => {
1566 try!(self.print_expr_maybe_paren(&**func));
1567 try!(self.print_call_post(args.as_slice()));
1569 ast::ExprMethodCall(ident, ref tys, ref args) => {
1570 let base_args = args.slice_from(1);
1571 try!(self.print_expr(&*args[0]));
1572 try!(word(&mut self.s, "."));
1573 try!(self.print_ident(ident.node));
1575 try!(word(&mut self.s, "::<"));
1576 try!(self.commasep(Inconsistent, tys.as_slice(),
1577 |s, ty| s.print_type(&**ty)));
1578 try!(word(&mut self.s, ">"));
1580 try!(self.print_call_post(base_args));
1582 ast::ExprBinary(op, ref lhs, ref rhs) => {
1583 try!(self.print_expr(&**lhs));
1584 try!(space(&mut self.s));
1585 try!(self.word_space(ast_util::binop_to_string(op)));
1586 try!(self.print_expr(&**rhs));
1588 ast::ExprUnary(op, ref expr) => {
1589 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1590 try!(self.print_expr_maybe_paren(&**expr));
1592 ast::ExprAddrOf(m, ref expr) => {
1593 try!(word(&mut self.s, "&"));
1594 try!(self.print_mutability(m));
1595 try!(self.print_expr_maybe_paren(&**expr));
1597 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1598 ast::ExprCast(ref expr, ref ty) => {
1599 try!(self.print_expr(&**expr));
1600 try!(space(&mut self.s));
1601 try!(self.word_space("as"));
1602 try!(self.print_type(&**ty));
1604 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1605 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1607 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1608 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1610 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1611 for ident in opt_ident.iter() {
1612 try!(self.print_ident(*ident));
1613 try!(self.word_space(":"));
1615 try!(self.head("while"));
1616 try!(self.print_expr(&**test));
1617 try!(space(&mut self.s));
1618 try!(self.print_block(&**blk));
1620 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1621 for ident in opt_ident.iter() {
1622 try!(self.print_ident(*ident));
1623 try!(self.word_space(":"));
1625 try!(self.head("while let"));
1626 try!(self.print_pat(&**pat));
1627 try!(space(&mut self.s));
1628 try!(self.word_space("="));
1629 try!(self.print_expr(&**expr));
1630 try!(space(&mut self.s));
1631 try!(self.print_block(&**blk));
1633 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1634 for ident in opt_ident.iter() {
1635 try!(self.print_ident(*ident));
1636 try!(self.word_space(":"));
1638 try!(self.head("for"));
1639 try!(self.print_pat(&**pat));
1640 try!(space(&mut self.s));
1641 try!(self.word_space("in"));
1642 try!(self.print_expr(&**iter));
1643 try!(space(&mut self.s));
1644 try!(self.print_block(&**blk));
1646 ast::ExprLoop(ref blk, opt_ident) => {
1647 for ident in opt_ident.iter() {
1648 try!(self.print_ident(*ident));
1649 try!(self.word_space(":"));
1651 try!(self.head("loop"));
1652 try!(space(&mut self.s));
1653 try!(self.print_block(&**blk));
1655 ast::ExprMatch(ref expr, ref arms, _) => {
1656 try!(self.cbox(indent_unit));
1658 try!(self.word_nbsp("match"));
1659 try!(self.print_expr(&**expr));
1660 try!(space(&mut self.s));
1662 for arm in arms.iter() {
1663 try!(self.print_arm(arm));
1665 try!(self.bclose_(expr.span, indent_unit));
1667 ast::ExprClosure(capture_clause, opt_kind, ref decl, ref body) => {
1668 try!(self.print_capture_clause(capture_clause));
1670 try!(self.print_fn_block_args(&**decl, opt_kind));
1671 try!(space(&mut self.s));
1673 if !body.stmts.is_empty() || !body.expr.is_some() {
1674 try!(self.print_block_unclosed(&**body));
1676 // we extract the block, so as not to create another set of boxes
1677 match body.expr.as_ref().unwrap().node {
1678 ast::ExprBlock(ref blk) => {
1679 try!(self.print_block_unclosed(&**blk));
1682 // this is a bare expression
1683 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1684 try!(self.end()); // need to close a box
1688 // a box will be closed by print_expr, but we didn't want an overall
1689 // wrapper so we closed the corresponding opening. so create an
1690 // empty box to satisfy the close.
1693 ast::ExprProc(ref decl, ref body) => {
1694 // in do/for blocks we don't want to show an empty
1695 // argument list, but at this point we don't know which
1698 // if !decl.inputs.is_empty() {
1699 try!(self.print_proc_args(&**decl));
1700 try!(space(&mut self.s));
1702 assert!(body.stmts.is_empty());
1703 assert!(body.expr.is_some());
1704 // we extract the block, so as not to create another set of boxes
1705 match body.expr.as_ref().unwrap().node {
1706 ast::ExprBlock(ref blk) => {
1707 try!(self.print_block_unclosed(&**blk));
1710 // this is a bare expression
1711 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1712 try!(self.end()); // need to close a box
1715 // a box will be closed by print_expr, but we didn't want an overall
1716 // wrapper so we closed the corresponding opening. so create an
1717 // empty box to satisfy the close.
1720 ast::ExprBlock(ref blk) => {
1721 // containing cbox, will be closed by print-block at }
1722 try!(self.cbox(indent_unit));
1723 // head-box, will be closed by print-block after {
1724 try!(self.ibox(0u));
1725 try!(self.print_block(&**blk));
1727 ast::ExprAssign(ref lhs, ref rhs) => {
1728 try!(self.print_expr(&**lhs));
1729 try!(space(&mut self.s));
1730 try!(self.word_space("="));
1731 try!(self.print_expr(&**rhs));
1733 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1734 try!(self.print_expr(&**lhs));
1735 try!(space(&mut self.s));
1736 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1737 try!(self.word_space("="));
1738 try!(self.print_expr(&**rhs));
1740 ast::ExprField(ref expr, id) => {
1741 try!(self.print_expr(&**expr));
1742 try!(word(&mut self.s, "."));
1743 try!(self.print_ident(id.node));
1745 ast::ExprTupField(ref expr, id) => {
1746 try!(self.print_expr(&**expr));
1747 try!(word(&mut self.s, "."));
1748 try!(self.print_uint(id.node));
1750 ast::ExprIndex(ref expr, ref index) => {
1751 try!(self.print_expr(&**expr));
1752 try!(word(&mut self.s, "["));
1753 try!(self.print_expr(&**index));
1754 try!(word(&mut self.s, "]"));
1756 ast::ExprSlice(ref e, ref start, ref end, ref mutbl) => {
1757 try!(self.print_expr(&**e));
1758 try!(word(&mut self.s, "["));
1759 if mutbl == &ast::MutMutable {
1760 try!(word(&mut self.s, "mut"));
1761 if start.is_some() || end.is_some() {
1762 try!(space(&mut self.s));
1765 if let &Some(ref e) = start {
1766 try!(self.print_expr(&**e));
1768 if start.is_some() || end.is_some() {
1769 try!(word(&mut self.s, ".."));
1771 if let &Some(ref e) = end {
1772 try!(self.print_expr(&**e));
1774 try!(word(&mut self.s, "]"));
1776 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1777 ast::ExprBreak(opt_ident) => {
1778 try!(word(&mut self.s, "break"));
1779 try!(space(&mut self.s));
1780 for ident in opt_ident.iter() {
1781 try!(self.print_ident(*ident));
1782 try!(space(&mut self.s));
1785 ast::ExprAgain(opt_ident) => {
1786 try!(word(&mut self.s, "continue"));
1787 try!(space(&mut self.s));
1788 for ident in opt_ident.iter() {
1789 try!(self.print_ident(*ident));
1790 try!(space(&mut self.s))
1793 ast::ExprRet(ref result) => {
1794 try!(word(&mut self.s, "return"));
1797 try!(word(&mut self.s, " "));
1798 try!(self.print_expr(&**expr));
1803 ast::ExprInlineAsm(ref a) => {
1805 try!(word(&mut self.s, "__volatile__ asm!"));
1807 try!(word(&mut self.s, "asm!"));
1810 try!(self.print_string(a.asm.get(), a.asm_str_style));
1811 try!(self.word_space(":"));
1813 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1814 |s, &(ref co, ref o, is_rw)| {
1815 match co.get().slice_shift_char() {
1816 Some(('=', operand)) if is_rw => {
1817 try!(s.print_string(format!("+{}", operand).as_slice(),
1820 _ => try!(s.print_string(co.get(), ast::CookedStr))
1823 try!(s.print_expr(&**o));
1827 try!(space(&mut self.s));
1828 try!(self.word_space(":"));
1830 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1831 |s, &(ref co, ref o)| {
1832 try!(s.print_string(co.get(), ast::CookedStr));
1834 try!(s.print_expr(&**o));
1838 try!(space(&mut self.s));
1839 try!(self.word_space(":"));
1841 try!(self.commasep(Inconsistent, a.clobbers.as_slice(),
1843 try!(s.print_string(co.get(), ast::CookedStr));
1846 try!(self.pclose());
1848 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1849 ast::ExprParen(ref e) => {
1851 try!(self.print_expr(&**e));
1852 try!(self.pclose());
1855 try!(self.ann.post(self, NodeExpr(expr)));
1859 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1860 try!(self.print_pat(&*loc.pat));
1862 ast::TyInfer => Ok(()),
1864 try!(self.word_space(":"));
1865 self.print_type(&*loc.ty)
1870 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1871 try!(self.maybe_print_comment(decl.span.lo));
1873 ast::DeclLocal(ref loc) => {
1874 try!(self.space_if_not_bol());
1875 try!(self.ibox(indent_unit));
1876 try!(self.word_nbsp("let"));
1878 try!(self.ibox(indent_unit));
1879 try!(self.print_local_decl(&**loc));
1881 if let Some(ref init) = loc.init {
1883 try!(self.word_space("="));
1884 try!(self.print_expr(&**init));
1888 ast::DeclItem(ref item) => self.print_item(&**item)
1892 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1893 if self.encode_idents_with_hygiene {
1894 let encoded = ident.encode_with_hygiene();
1895 try!(word(&mut self.s, encoded.as_slice()))
1897 try!(word(&mut self.s, token::get_ident(ident).get()))
1899 self.ann.post(self, NodeIdent(&ident))
1902 pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1903 word(&mut self.s, i.to_string().as_slice())
1906 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1907 try!(word(&mut self.s, token::get_name(name).get()));
1908 self.ann.post(self, NodeName(&name))
1911 pub fn print_for_decl(&mut self, loc: &ast::Local,
1912 coll: &ast::Expr) -> IoResult<()> {
1913 try!(self.print_local_decl(loc));
1914 try!(space(&mut self.s));
1915 try!(self.word_space("in"));
1916 self.print_expr(coll)
1919 fn print_path(&mut self,
1921 colons_before_params: bool)
1924 try!(self.maybe_print_comment(path.span.lo));
1926 try!(word(&mut self.s, "::"));
1929 let mut first = true;
1930 for segment in path.segments.iter() {
1934 try!(word(&mut self.s, "::"))
1937 try!(self.print_ident(segment.identifier));
1939 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1945 fn print_path_parameters(&mut self,
1946 parameters: &ast::PathParameters,
1947 colons_before_params: bool)
1950 if parameters.is_empty() {
1954 if colons_before_params {
1955 try!(word(&mut self.s, "::"))
1959 ast::AngleBracketedParameters(ref data) => {
1960 try!(word(&mut self.s, "<"));
1962 let mut comma = false;
1963 for lifetime in data.lifetimes.iter() {
1965 try!(self.word_space(","))
1967 try!(self.print_lifetime(lifetime));
1971 if !data.types.is_empty() {
1973 try!(self.word_space(","))
1977 data.types.as_slice(),
1978 |s, ty| s.print_type(&**ty)));
1981 try!(word(&mut self.s, ">"))
1984 ast::ParenthesizedParameters(ref data) => {
1985 try!(word(&mut self.s, "("));
1988 data.inputs.as_slice(),
1989 |s, ty| s.print_type(&**ty)));
1990 try!(word(&mut self.s, ")"));
1995 try!(self.word_space("->"));
1996 try!(self.print_type(&**ty));
2005 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
2006 try!(self.maybe_print_comment(pat.span.lo));
2007 try!(self.ann.pre(self, NodePat(pat)));
2008 /* Pat isn't normalized, but the beauty of it
2009 is that it doesn't matter */
2011 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2012 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2013 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2014 match binding_mode {
2015 ast::BindByRef(mutbl) => {
2016 try!(self.word_nbsp("ref"));
2017 try!(self.print_mutability(mutbl));
2019 ast::BindByValue(ast::MutImmutable) => {}
2020 ast::BindByValue(ast::MutMutable) => {
2021 try!(self.word_nbsp("mut"));
2024 try!(self.print_ident(path1.node));
2027 try!(word(&mut self.s, "@"));
2028 try!(self.print_pat(&**p));
2033 ast::PatEnum(ref path, ref args_) => {
2034 try!(self.print_path(path, true));
2036 None => try!(word(&mut self.s, "(..)")),
2038 if !args.is_empty() {
2040 try!(self.commasep(Inconsistent, args.as_slice(),
2041 |s, p| s.print_pat(&**p)));
2042 try!(self.pclose());
2047 ast::PatStruct(ref path, ref fields, etc) => {
2048 try!(self.print_path(path, true));
2050 try!(self.word_space("{"));
2051 try!(self.commasep_cmnt(
2052 Consistent, fields.as_slice(),
2054 try!(s.cbox(indent_unit));
2055 if !f.node.is_shorthand {
2056 try!(s.print_ident(f.node.ident));
2057 try!(s.word_nbsp(":"));
2059 try!(s.print_pat(&*f.node.pat));
2062 |f| f.node.pat.span));
2064 if fields.len() != 0u { try!(self.word_space(",")); }
2065 try!(word(&mut self.s, ".."));
2067 try!(space(&mut self.s));
2068 try!(word(&mut self.s, "}"));
2070 ast::PatTup(ref elts) => {
2072 try!(self.commasep(Inconsistent,
2074 |s, p| s.print_pat(&**p)));
2075 if elts.len() == 1 {
2076 try!(word(&mut self.s, ","));
2078 try!(self.pclose());
2080 ast::PatBox(ref inner) => {
2081 try!(word(&mut self.s, "box "));
2082 try!(self.print_pat(&**inner));
2084 ast::PatRegion(ref inner) => {
2085 try!(word(&mut self.s, "&"));
2086 try!(self.print_pat(&**inner));
2088 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2089 ast::PatRange(ref begin, ref end) => {
2090 try!(self.print_expr(&**begin));
2091 try!(space(&mut self.s));
2092 try!(word(&mut self.s, "..."));
2093 try!(self.print_expr(&**end));
2095 ast::PatVec(ref before, ref slice, ref after) => {
2096 try!(word(&mut self.s, "["));
2097 try!(self.commasep(Inconsistent,
2099 |s, p| s.print_pat(&**p)));
2100 for p in slice.iter() {
2101 if !before.is_empty() { try!(self.word_space(",")); }
2102 try!(self.print_pat(&**p));
2104 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2105 // this case is handled by print_pat
2107 _ => try!(word(&mut self.s, "..")),
2109 if !after.is_empty() { try!(self.word_space(",")); }
2111 try!(self.commasep(Inconsistent,
2113 |s, p| s.print_pat(&**p)));
2114 try!(word(&mut self.s, "]"));
2116 ast::PatMac(ref m) => try!(self.print_mac(m)),
2118 self.ann.post(self, NodePat(pat))
2121 fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2122 // I have no idea why this check is necessary, but here it
2124 if arm.attrs.is_empty() {
2125 try!(space(&mut self.s));
2127 try!(self.cbox(indent_unit));
2128 try!(self.ibox(0u));
2129 try!(self.print_outer_attributes(arm.attrs.as_slice()));
2130 let mut first = true;
2131 for p in arm.pats.iter() {
2135 try!(space(&mut self.s));
2136 try!(self.word_space("|"));
2138 try!(self.print_pat(&**p));
2140 try!(space(&mut self.s));
2141 if let Some(ref e) = arm.guard {
2142 try!(self.word_space("if"));
2143 try!(self.print_expr(&**e));
2144 try!(space(&mut self.s));
2146 try!(self.word_space("=>"));
2148 match arm.body.node {
2149 ast::ExprBlock(ref blk) => {
2150 // the block will close the pattern's ibox
2151 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2153 // If it is a user-provided unsafe block, print a comma after it
2154 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2155 try!(word(&mut self.s, ","));
2159 try!(self.end()); // close the ibox for the pattern
2160 try!(self.print_expr(&*arm.body));
2161 try!(word(&mut self.s, ","));
2164 self.end() // close enclosing cbox
2167 // Returns whether it printed anything
2168 fn print_explicit_self(&mut self,
2169 explicit_self: &ast::ExplicitSelf_,
2170 mutbl: ast::Mutability) -> IoResult<bool> {
2171 try!(self.print_mutability(mutbl));
2172 match *explicit_self {
2173 ast::SelfStatic => { return Ok(false); }
2174 ast::SelfValue(_) => {
2175 try!(word(&mut self.s, "self"));
2177 ast::SelfRegion(ref lt, m, _) => {
2178 try!(word(&mut self.s, "&"));
2179 try!(self.print_opt_lifetime(lt));
2180 try!(self.print_mutability(m));
2181 try!(word(&mut self.s, "self"));
2183 ast::SelfExplicit(ref typ, _) => {
2184 try!(word(&mut self.s, "self"));
2185 try!(self.word_space(":"));
2186 try!(self.print_type(&**typ));
2192 pub fn print_fn(&mut self,
2194 fn_style: Option<ast::FnStyle>,
2197 generics: &ast::Generics,
2198 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2199 vis: ast::Visibility) -> IoResult<()> {
2200 try!(self.head(""));
2201 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
2203 try!(self.print_ident(name));
2204 try!(self.print_generics(generics));
2205 try!(self.print_fn_args_and_ret(decl, opt_explicit_self))
2206 self.print_where_clause(generics)
2209 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2210 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2212 // It is unfortunate to duplicate the commasep logic, but we want the
2213 // self type and the args all in the same box.
2214 try!(self.rbox(0u, Inconsistent));
2215 let mut first = true;
2216 for &explicit_self in opt_explicit_self.iter() {
2217 let m = match explicit_self {
2218 &ast::SelfStatic => ast::MutImmutable,
2219 _ => match decl.inputs[0].pat.node {
2220 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2221 _ => ast::MutImmutable
2224 first = !try!(self.print_explicit_self(explicit_self, m));
2227 // HACK(eddyb) ignore the separately printed self argument.
2228 let args = if first {
2229 decl.inputs.as_slice()
2231 decl.inputs.slice_from(1)
2234 for arg in args.iter() {
2235 if first { first = false; } else { try!(self.word_space(",")); }
2236 try!(self.print_arg(arg));
2242 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2243 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2246 try!(self.print_fn_args(decl, opt_explicit_self));
2248 try!(word(&mut self.s, ", ..."));
2250 try!(self.pclose());
2252 self.print_fn_output(decl)
2255 pub fn print_fn_block_args(
2258 unboxed_closure_kind: Option<UnboxedClosureKind>)
2260 try!(word(&mut self.s, "|"));
2261 match unboxed_closure_kind {
2263 Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2264 Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2265 Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2267 try!(self.print_fn_args(decl, None));
2268 try!(word(&mut self.s, "|"));
2270 if let ast::Return(ref ty) = decl.output {
2271 if ty.node == ast::TyInfer {
2272 return self.maybe_print_comment(ty.span.lo);
2276 try!(self.space_if_not_bol());
2277 try!(self.word_space("->"));
2279 ast::Return(ref ty) => {
2280 try!(self.print_type(&**ty));
2281 self.maybe_print_comment(ty.span.lo)
2283 ast::NoReturn(span) => {
2284 try!(self.word_nbsp("!"));
2285 self.maybe_print_comment(span.lo)
2290 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2292 match capture_clause {
2293 ast::CaptureByValue => self.word_space("move"),
2294 ast::CaptureByRef => Ok(()),
2298 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2299 try!(word(&mut self.s, "proc"));
2300 try!(word(&mut self.s, "("));
2301 try!(self.print_fn_args(decl, None));
2302 try!(word(&mut self.s, ")"));
2304 if let ast::Return(ref ty) = decl.output {
2305 if ty.node == ast::TyInfer {
2306 return self.maybe_print_comment(ty.span.lo);
2310 try!(self.space_if_not_bol());
2311 try!(self.word_space("->"));
2313 ast::Return(ref ty) => {
2314 try!(self.print_type(&**ty));
2315 self.maybe_print_comment(ty.span.lo)
2317 ast::NoReturn(span) => {
2318 try!(self.word_nbsp("!"));
2319 self.maybe_print_comment(span.lo)
2324 pub fn print_bounds(&mut self,
2326 bounds: &[ast::TyParamBound])
2328 if !bounds.is_empty() {
2329 try!(word(&mut self.s, prefix));
2330 let mut first = true;
2331 for bound in bounds.iter() {
2336 try!(self.word_space("+"));
2340 TraitTyParamBound(ref tref) => {
2341 self.print_poly_trait_ref(tref)
2343 RegionTyParamBound(ref lt) => {
2344 self.print_lifetime(lt)
2354 pub fn print_lifetime(&mut self,
2355 lifetime: &ast::Lifetime)
2358 self.print_name(lifetime.name)
2361 pub fn print_lifetime_def(&mut self,
2362 lifetime: &ast::LifetimeDef)
2365 try!(self.print_lifetime(&lifetime.lifetime));
2367 for v in lifetime.bounds.iter() {
2368 try!(word(&mut self.s, sep));
2369 try!(self.print_lifetime(v));
2375 pub fn print_generics(&mut self,
2376 generics: &ast::Generics)
2379 let total = generics.lifetimes.len() + generics.ty_params.len();
2384 try!(word(&mut self.s, "<"));
2386 let mut ints = Vec::new();
2387 for i in range(0u, total) {
2391 try!(self.commasep(Inconsistent, ints.as_slice(), |s, &idx| {
2392 if idx < generics.lifetimes.len() {
2393 let lifetime = &generics.lifetimes[idx];
2394 s.print_lifetime_def(lifetime)
2396 let idx = idx - generics.lifetimes.len();
2397 let param = &generics.ty_params[idx];
2398 s.print_ty_param(param)
2402 try!(word(&mut self.s, ">"));
2406 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
2407 if let Some(ref tref) = param.unbound {
2408 try!(self.print_trait_ref(tref));
2409 try!(self.word_space("?"));
2411 try!(self.print_ident(param.ident));
2412 try!(self.print_bounds(":", param.bounds.as_slice()));
2413 match param.default {
2414 Some(ref default) => {
2415 try!(space(&mut self.s));
2416 try!(self.word_space("="));
2417 self.print_type(&**default)
2423 pub fn print_where_clause(&mut self, generics: &ast::Generics)
2425 if generics.where_clause.predicates.len() == 0 {
2429 try!(space(&mut self.s));
2430 try!(self.word_space("where"));
2432 for (i, predicate) in generics.where_clause
2437 try!(self.word_space(","));
2440 try!(self.print_ident(predicate.ident));
2441 try!(self.print_bounds(":", predicate.bounds.as_slice()));
2447 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2448 try!(self.ibox(indent_unit));
2450 ast::MetaWord(ref name) => {
2451 try!(word(&mut self.s, name.get()));
2453 ast::MetaNameValue(ref name, ref value) => {
2454 try!(self.word_space(name.get()));
2455 try!(self.word_space("="));
2456 try!(self.print_literal(value));
2458 ast::MetaList(ref name, ref items) => {
2459 try!(word(&mut self.s, name.get()));
2461 try!(self.commasep(Consistent,
2463 |s, i| s.print_meta_item(&**i)));
2464 try!(self.pclose());
2470 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2472 ast::ViewPathSimple(ident, ref path, _) => {
2473 try!(self.print_path(path, false));
2475 // FIXME(#6993) can't compare identifiers directly here
2476 if path.segments.last().unwrap().identifier.name !=
2478 try!(space(&mut self.s));
2479 try!(self.word_space("as"));
2480 try!(self.print_ident(ident));
2486 ast::ViewPathGlob(ref path, _) => {
2487 try!(self.print_path(path, false));
2488 word(&mut self.s, "::*")
2491 ast::ViewPathList(ref path, ref idents, _) => {
2492 if path.segments.is_empty() {
2493 try!(word(&mut self.s, "{"));
2495 try!(self.print_path(path, false));
2496 try!(word(&mut self.s, "::{"));
2498 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2500 ast::PathListIdent { name, .. } => {
2503 ast::PathListMod { .. } => {
2504 word(&mut s.s, "mod")
2508 word(&mut self.s, "}")
2513 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2514 try!(self.hardbreak_if_not_bol());
2515 try!(self.maybe_print_comment(item.span.lo));
2516 try!(self.print_outer_attributes(item.attrs.as_slice()));
2517 try!(self.print_visibility(item.vis));
2519 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2520 try!(self.head("extern crate"));
2521 for &(ref p, style) in optional_path.iter() {
2522 try!(self.print_string(p.get(), style));
2523 try!(space(&mut self.s));
2524 try!(word(&mut self.s, "as"));
2525 try!(space(&mut self.s));
2527 try!(self.print_ident(id));
2530 ast::ViewItemUse(ref vp) => {
2531 try!(self.head("use"));
2532 try!(self.print_view_path(&**vp));
2535 try!(word(&mut self.s, ";"));
2536 try!(self.end()); // end inner head-block
2537 self.end() // end outer head-block
2540 pub fn print_mutability(&mut self,
2541 mutbl: ast::Mutability) -> IoResult<()> {
2543 ast::MutMutable => self.word_nbsp("mut"),
2544 ast::MutImmutable => Ok(()),
2548 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2549 try!(self.print_mutability(mt.mutbl));
2550 self.print_type(&*mt.ty)
2553 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2554 try!(self.ibox(indent_unit));
2555 match input.ty.node {
2556 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2558 match input.pat.node {
2559 ast::PatIdent(_, ref path1, _) if
2561 parse::token::special_idents::invalid.name => {
2565 try!(self.print_pat(&*input.pat));
2566 try!(word(&mut self.s, ":"));
2567 try!(space(&mut self.s));
2570 try!(self.print_type(&*input.ty));
2576 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2577 if let ast::Return(ref ty) = decl.output {
2579 ast::TyTup(ref tys) if tys.is_empty() => {
2580 return self.maybe_print_comment(ty.span.lo);
2586 try!(self.space_if_not_bol());
2587 try!(self.ibox(indent_unit));
2588 try!(self.word_space("->"));
2591 try!(self.word_nbsp("!")),
2592 ast::Return(ref ty) =>
2593 try!(self.print_type(&**ty))
2598 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2603 pub fn print_ty_fn(&mut self,
2604 opt_abi: Option<abi::Abi>,
2605 opt_sigil: Option<char>,
2606 fn_style: ast::FnStyle,
2607 onceness: ast::Onceness,
2609 id: Option<ast::Ident>,
2610 bounds: &OwnedSlice<ast::TyParamBound>,
2611 generics: Option<&ast::Generics>,
2612 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2614 try!(self.ibox(indent_unit));
2616 // Duplicates the logic in `print_fn_header_info()`. This is because that
2617 // function prints the sigil in the wrong place. That should be fixed.
2618 if opt_sigil == Some('~') && onceness == ast::Once {
2619 try!(word(&mut self.s, "proc"));
2620 } else if opt_sigil == Some('&') {
2621 try!(self.print_fn_style(fn_style));
2622 try!(self.print_extern_opt_abi(opt_abi));
2624 assert!(opt_sigil.is_none());
2625 try!(self.print_fn_style(fn_style));
2626 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2627 try!(word(&mut self.s, "fn"));
2632 try!(word(&mut self.s, " "));
2633 try!(self.print_ident(id));
2638 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2639 try!(zerobreak(&mut self.s));
2641 if opt_sigil == Some('&') {
2642 try!(word(&mut self.s, "|"));
2647 try!(self.print_fn_args(decl, opt_explicit_self));
2649 if opt_sigil == Some('&') {
2650 try!(word(&mut self.s, "|"));
2653 try!(word(&mut self.s, ", ..."));
2655 try!(self.pclose());
2658 try!(self.print_bounds(":", bounds.as_slice()));
2660 try!(self.print_fn_output(decl));
2663 Some(generics) => try!(self.print_where_clause(generics)),
2670 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2671 next_pos: Option<BytePos>)
2673 let cm = match self.cm {
2677 match self.next_comment() {
2679 if (*cmnt).style != comments::Trailing { return Ok(()) }
2680 let span_line = cm.lookup_char_pos(span.hi);
2681 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2682 let mut next = (*cmnt).pos + BytePos(1);
2683 match next_pos { None => (), Some(p) => next = p }
2684 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2685 span_line.line == comment_line.line {
2686 try!(self.print_comment(cmnt));
2687 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2695 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2696 // If there aren't any remaining comments, then we need to manually
2697 // make sure there is a line break at the end.
2698 if self.next_comment().is_none() {
2699 try!(hardbreak(&mut self.s));
2702 match self.next_comment() {
2704 try!(self.print_comment(cmnt));
2705 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2713 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2714 try!(self.maybe_print_comment(lit.span.lo));
2715 match self.next_lit(lit.span.lo) {
2717 return word(&mut self.s, (*ltrl).lit.as_slice());
2722 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2723 ast::LitByte(byte) => {
2724 let mut res = String::from_str("b'");
2725 ascii::escape_default(byte, |c| res.push(c as char));
2727 word(&mut self.s, res.as_slice())
2729 ast::LitChar(ch) => {
2730 let mut res = String::from_str("'");
2731 for c in ch.escape_default() {
2735 word(&mut self.s, res.as_slice())
2737 ast::LitInt(i, t) => {
2739 ast::SignedIntLit(st, ast::Plus) => {
2741 ast_util::int_ty_to_string(st, Some(i as i64)).as_slice())
2743 ast::SignedIntLit(st, ast::Minus) => {
2744 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2746 format!("-{}", istr).as_slice())
2748 ast::UnsignedIntLit(ut) => {
2749 word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
2751 ast::UnsuffixedIntLit(ast::Plus) => {
2752 word(&mut self.s, format!("{}", i).as_slice())
2754 ast::UnsuffixedIntLit(ast::Minus) => {
2755 word(&mut self.s, format!("-{}", i).as_slice())
2759 ast::LitFloat(ref f, t) => {
2764 ast_util::float_ty_to_string(t).as_slice()).as_slice())
2766 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2767 ast::LitBool(val) => {
2768 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2770 ast::LitBinary(ref v) => {
2771 let mut escaped: String = String::new();
2772 for &ch in v.iter() {
2773 ascii::escape_default(ch as u8,
2774 |ch| escaped.push(ch as char));
2776 word(&mut self.s, format!("b\"{}\"", escaped).as_slice())
2781 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2782 match self.literals {
2784 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2785 let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2786 if ltrl.pos > pos { return None; }
2787 self.cur_cmnt_and_lit.cur_lit += 1u;
2788 if ltrl.pos == pos { return Some(ltrl); }
2796 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2798 match self.next_comment() {
2800 if (*cmnt).pos < pos {
2801 try!(self.print_comment(cmnt));
2802 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2811 pub fn print_comment(&mut self,
2812 cmnt: &comments::Comment) -> IoResult<()> {
2814 comments::Mixed => {
2815 assert_eq!(cmnt.lines.len(), 1u);
2816 try!(zerobreak(&mut self.s));
2817 try!(word(&mut self.s, cmnt.lines[0].as_slice()));
2818 zerobreak(&mut self.s)
2820 comments::Isolated => {
2821 try!(self.hardbreak_if_not_bol());
2822 for line in cmnt.lines.iter() {
2823 // Don't print empty lines because they will end up as trailing
2825 if !line.is_empty() {
2826 try!(word(&mut self.s, line.as_slice()));
2828 try!(hardbreak(&mut self.s));
2832 comments::Trailing => {
2833 try!(word(&mut self.s, " "));
2834 if cmnt.lines.len() == 1u {
2835 try!(word(&mut self.s, cmnt.lines[0].as_slice()));
2836 hardbreak(&mut self.s)
2838 try!(self.ibox(0u));
2839 for line in cmnt.lines.iter() {
2840 if !line.is_empty() {
2841 try!(word(&mut self.s, line.as_slice()));
2843 try!(hardbreak(&mut self.s));
2848 comments::BlankLine => {
2849 // We need to do at least one, possibly two hardbreaks.
2850 let is_semi = match self.s.last_token() {
2851 pp::String(s, _) => ";" == s,
2854 if is_semi || self.is_begin() || self.is_end() {
2855 try!(hardbreak(&mut self.s));
2857 hardbreak(&mut self.s)
2862 pub fn print_string(&mut self, st: &str,
2863 style: ast::StrStyle) -> IoResult<()> {
2864 let st = match style {
2866 (format!("\"{}\"", st.escape_default()))
2869 (format!("r{delim}\"{string}\"{delim}",
2870 delim="#".repeat(n),
2874 word(&mut self.s, st.as_slice())
2877 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2878 match self.comments {
2879 Some(ref cmnts) => {
2880 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2881 Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2890 pub fn print_opt_fn_style(&mut self,
2891 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2892 match opt_fn_style {
2893 Some(fn_style) => self.print_fn_style(fn_style),
2898 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2899 opt_abi: Option<abi::Abi>)
2902 Some(abi::Rust) => Ok(()),
2904 try!(self.word_nbsp("extern"));
2905 self.word_nbsp(abi.to_string().as_slice())
2911 pub fn print_extern_opt_abi(&mut self,
2912 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2915 try!(self.word_nbsp("extern"));
2916 self.word_nbsp(abi.to_string().as_slice())
2922 pub fn print_fn_header_info(&mut self,
2923 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2924 opt_fn_style: Option<ast::FnStyle>,
2926 vis: ast::Visibility) -> IoResult<()> {
2927 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2928 try!(self.print_opt_fn_style(opt_fn_style));
2930 if abi != abi::Rust {
2931 try!(self.word_nbsp("extern"));
2932 try!(self.word_nbsp(abi.to_string().as_slice()));
2935 word(&mut self.s, "fn")
2938 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2940 ast::NormalFn => Ok(()),
2941 ast::UnsafeFn => self.word_nbsp("unsafe"),
2957 fn test_fun_to_string() {
2958 let abba_ident = token::str_to_ident("abba");
2960 let decl = ast::FnDecl {
2962 output: ast::Return(P(ast::Ty {id: 0,
2963 node: ast::TyTup(vec![]),
2964 span: codemap::DUMMY_SP})),
2967 let generics = ast_util::empty_generics();
2968 assert_eq!(fun_to_string(&decl, ast::NormalFn, abba_ident,
2974 fn test_variant_to_string() {
2975 let ident = token::str_to_ident("principal_skinner");
2977 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2980 // making this up as I go.... ?
2981 kind: ast::TupleVariantKind(Vec::new()),
2987 let varstr = variant_to_string(&var);
2988 assert_eq!(varstr, "pub principal_skinner");
2992 fn test_signed_int_to_string() {
2993 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
2994 let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
2995 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
2996 lit_to_string(&codemap::dummy_spanned(neg_int)));