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, RangeEnd};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use codemap::{self, CodeMap};
20 use syntax_pos::{self, BytePos};
21 use parse::token::{self, BinOpToken, Token};
22 use parse::lexer::comments;
23 use parse::{self, ParseSess};
24 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
25 use print::pp::{Breaks, eof};
26 use print::pp::Breaks::{Consistent, Inconsistent};
29 use symbol::{Symbol, keywords};
30 use syntax_pos::DUMMY_SP;
31 use tokenstream::{self, TokenStream, 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,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
111 if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
112 // We need to print `#![no_std]` (and its feature gate) so that
113 // compiling pretty-printed source won't inject libstd again.
114 // However we don't want these attributes in the AST because
115 // of the feature gate, so we fake them up here.
117 // #![feature(prelude_import)]
118 let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
119 let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
120 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
121 s.print_attribute(&fake_attr)?;
124 let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
125 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
126 s.print_attribute(&fake_attr)?;
129 s.print_mod(&krate.module, &krate.attrs)?;
130 s.print_remaining_comments()?;
135 pub fn new_from_input(cm: &'a CodeMap,
141 is_expanded: bool) -> State<'a> {
142 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
149 // If the code is post expansion, don't use the table of
150 // literals, since it doesn't correspond with the literals
151 // in the AST anymore.
152 if is_expanded { None } else { Some(lits) })
155 pub fn new(cm: &'a CodeMap,
158 comments: Option<Vec<comments::Comment>>,
159 literals: Option<Vec<comments::Literal>>) -> State<'a> {
161 s: pp::mk_printer(out, DEFAULT_COLUMNS),
165 cur_cmnt_and_lit: CurrentCommentAndLiteral {
175 pub fn to_string<F>(f: F) -> String where
176 F: FnOnce(&mut State) -> io::Result<()>,
178 let mut wr = Vec::new();
180 let mut printer = rust_printer(Box::new(&mut wr));
181 f(&mut printer).unwrap();
182 eof(&mut printer.s).unwrap();
184 String::from_utf8(wr).unwrap()
187 pub fn binop_to_string(op: BinOpToken) -> &'static str {
193 token::Percent => "%",
202 pub fn token_to_string(tok: &Token) -> String {
204 token::Eq => "=".to_string(),
205 token::Lt => "<".to_string(),
206 token::Le => "<=".to_string(),
207 token::EqEq => "==".to_string(),
208 token::Ne => "!=".to_string(),
209 token::Ge => ">=".to_string(),
210 token::Gt => ">".to_string(),
211 token::Not => "!".to_string(),
212 token::Tilde => "~".to_string(),
213 token::OrOr => "||".to_string(),
214 token::AndAnd => "&&".to_string(),
215 token::BinOp(op) => binop_to_string(op).to_string(),
216 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
218 /* Structural symbols */
219 token::At => "@".to_string(),
220 token::Dot => ".".to_string(),
221 token::DotDot => "..".to_string(),
222 token::DotDotDot => "...".to_string(),
223 token::Comma => ",".to_string(),
224 token::Semi => ";".to_string(),
225 token::Colon => ":".to_string(),
226 token::ModSep => "::".to_string(),
227 token::RArrow => "->".to_string(),
228 token::LArrow => "<-".to_string(),
229 token::FatArrow => "=>".to_string(),
230 token::OpenDelim(token::Paren) => "(".to_string(),
231 token::CloseDelim(token::Paren) => ")".to_string(),
232 token::OpenDelim(token::Bracket) => "[".to_string(),
233 token::CloseDelim(token::Bracket) => "]".to_string(),
234 token::OpenDelim(token::Brace) => "{".to_string(),
235 token::CloseDelim(token::Brace) => "}".to_string(),
236 token::OpenDelim(token::NoDelim) => " ".to_string(),
237 token::CloseDelim(token::NoDelim) => " ".to_string(),
238 token::Pound => "#".to_string(),
239 token::Dollar => "$".to_string(),
240 token::Question => "?".to_string(),
243 token::Literal(lit, suf) => {
244 let mut out = match lit {
245 token::Byte(b) => format!("b'{}'", b),
246 token::Char(c) => format!("'{}'", c),
247 token::Float(c) => c.to_string(),
248 token::Integer(c) => c.to_string(),
249 token::Str_(s) => format!("\"{}\"", s),
250 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
251 delim=repeat("#", n),
253 token::ByteStr(v) => format!("b\"{}\"", v),
254 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
255 delim=repeat("#", n),
259 if let Some(s) = suf {
260 out.push_str(&s.as_str())
266 /* Name components */
267 token::Ident(s) => s.to_string(),
268 token::Lifetime(s) => s.to_string(),
269 token::Underscore => "_".to_string(),
272 token::DocComment(s) => s.to_string(),
273 token::SubstNt(s) => format!("${}", s),
274 token::Eof => "<eof>".to_string(),
275 token::Whitespace => " ".to_string(),
276 token::Comment => "/* */".to_string(),
277 token::Shebang(s) => format!("/* shebang: {}*/", s),
279 token::Interpolated(ref nt) => match **nt {
280 token::NtExpr(ref e) => expr_to_string(&e),
281 token::NtMeta(ref e) => meta_item_to_string(&e),
282 token::NtTy(ref e) => ty_to_string(&e),
283 token::NtPath(ref e) => path_to_string(&e),
284 token::NtItem(ref e) => item_to_string(&e),
285 token::NtBlock(ref e) => block_to_string(&e),
286 token::NtStmt(ref e) => stmt_to_string(&e),
287 token::NtPat(ref e) => pat_to_string(&e),
288 token::NtIdent(ref e) => ident_to_string(e.node),
289 token::NtTT(ref tree) => tt_to_string(tree.clone()),
290 token::NtArm(ref e) => arm_to_string(&e),
291 token::NtImplItem(ref e) => impl_item_to_string(&e),
292 token::NtTraitItem(ref e) => trait_item_to_string(&e),
293 token::NtGenerics(ref e) => generics_to_string(&e),
294 token::NtWhereClause(ref e) => where_clause_to_string(&e),
295 token::NtArg(ref e) => arg_to_string(&e),
300 pub fn ty_to_string(ty: &ast::Ty) -> String {
301 to_string(|s| s.print_type(ty))
304 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
305 to_string(|s| s.print_bounds("", bounds))
308 pub fn pat_to_string(pat: &ast::Pat) -> String {
309 to_string(|s| s.print_pat(pat))
312 pub fn arm_to_string(arm: &ast::Arm) -> String {
313 to_string(|s| s.print_arm(arm))
316 pub fn expr_to_string(e: &ast::Expr) -> String {
317 to_string(|s| s.print_expr(e))
320 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
321 to_string(|s| s.print_lifetime(e))
324 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
325 to_string(|s| s.print_tt(tt))
328 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
329 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
332 pub fn tokens_to_string(tokens: TokenStream) -> String {
333 to_string(|s| s.print_tts(tokens))
336 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
337 to_string(|s| s.print_stmt(stmt))
340 pub fn attr_to_string(attr: &ast::Attribute) -> String {
341 to_string(|s| s.print_attribute(attr))
344 pub fn item_to_string(i: &ast::Item) -> String {
345 to_string(|s| s.print_item(i))
348 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
349 to_string(|s| s.print_impl_item(i))
352 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
353 to_string(|s| s.print_trait_item(i))
356 pub fn generics_to_string(generics: &ast::Generics) -> String {
357 to_string(|s| s.print_generics(generics))
360 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
361 to_string(|s| s.print_where_clause(i))
364 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
365 to_string(|s| s.print_fn_block_args(p))
368 pub fn path_to_string(p: &ast::Path) -> String {
369 to_string(|s| s.print_path(p, false, 0, false))
372 pub fn ident_to_string(id: ast::Ident) -> String {
373 to_string(|s| s.print_ident(id))
376 pub fn fun_to_string(decl: &ast::FnDecl,
377 unsafety: ast::Unsafety,
378 constness: ast::Constness,
380 generics: &ast::Generics)
384 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
385 generics, &ast::Visibility::Inherited)?;
386 s.end()?; // Close the head box
387 s.end() // Close the outer box
391 pub fn block_to_string(blk: &ast::Block) -> String {
393 // containing cbox, will be closed by print-block at }
394 s.cbox(INDENT_UNIT)?;
395 // head-ibox, will be closed by print-block after {
401 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
402 to_string(|s| s.print_meta_list_item(li))
405 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
406 to_string(|s| s.print_meta_item(mi))
409 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
410 to_string(|s| s.print_attribute(attr))
413 pub fn lit_to_string(l: &ast::Lit) -> String {
414 to_string(|s| s.print_literal(l))
417 pub fn variant_to_string(var: &ast::Variant) -> String {
418 to_string(|s| s.print_variant(var))
421 pub fn arg_to_string(arg: &ast::Arg) -> String {
422 to_string(|s| s.print_arg(arg, false))
425 pub fn mac_to_string(arg: &ast::Mac) -> String {
426 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
429 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 ast::Visibility::Public => format!("pub {}", s),
432 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
433 ast::Visibility::Restricted { ref path, .. } =>
434 format!("pub({}) {}", to_string(|s| s.print_path(path, false, 0, true)), s),
435 ast::Visibility::Inherited => s.to_string()
439 fn needs_parentheses(expr: &ast::Expr) -> bool {
441 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
442 ast::ExprKind::Closure(..) |
443 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
444 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
449 pub trait PrintState<'a> {
450 fn writer(&mut self) -> &mut pp::Printer<'a>;
451 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
452 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
453 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
454 fn literals(&self) -> &Option<Vec<comments::Literal>>;
456 fn word_space(&mut self, w: &str) -> io::Result<()> {
457 word(self.writer(), w)?;
461 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
463 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
465 fn is_begin(&mut self) -> bool {
466 match self.writer().last_token() {
467 pp::Token::Begin(_) => true,
472 fn is_end(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::End => true,
479 // is this the beginning of a line?
480 fn is_bol(&mut self) -> bool {
481 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
484 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
486 hardbreak(self.writer())?
492 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
493 self.boxes().push(b);
494 pp::rbox(self.writer(), u, b)
497 fn ibox(&mut self, u: usize) -> io::Result<()> {
498 self.boxes().push(pp::Breaks::Inconsistent);
499 pp::ibox(self.writer(), u)
502 fn end(&mut self) -> io::Result<()> {
503 self.boxes().pop().unwrap();
504 pp::end(self.writer())
507 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
508 where F: FnMut(&mut Self, &T) -> io::Result<()>,
511 let mut first = true;
513 if first { first = false; } else { self.word_space(",")?; }
519 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
520 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
522 let mut result = None;
524 if let &Some(ref lits) = self.literals()
526 while cur_lit < lits.len() {
527 let ltrl = (*lits)[cur_lit].clone();
528 if ltrl.pos > pos { break; }
537 self.cur_cmnt_and_lit().cur_lit = cur_lit;
541 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
542 while let Some(ref cmnt) = self.next_comment() {
544 self.print_comment(cmnt)?;
545 self.cur_cmnt_and_lit().cur_cmnt += 1;
553 fn print_comment(&mut self,
554 cmnt: &comments::Comment) -> io::Result<()> {
557 assert_eq!(cmnt.lines.len(), 1);
558 zerobreak(self.writer())?;
559 word(self.writer(), &cmnt.lines[0])?;
560 zerobreak(self.writer())
562 comments::Isolated => {
563 self.hardbreak_if_not_bol()?;
564 for line in &cmnt.lines {
565 // Don't print empty lines because they will end up as trailing
567 if !line.is_empty() {
568 word(self.writer(), &line[..])?;
570 hardbreak(self.writer())?;
574 comments::Trailing => {
576 word(self.writer(), " ")?;
578 if cmnt.lines.len() == 1 {
579 word(self.writer(), &cmnt.lines[0])?;
580 hardbreak(self.writer())
583 for line in &cmnt.lines {
584 if !line.is_empty() {
585 word(self.writer(), &line[..])?;
587 hardbreak(self.writer())?;
592 comments::BlankLine => {
593 // We need to do at least one, possibly two hardbreaks.
594 let is_semi = match self.writer().last_token() {
595 pp::Token::String(s, _) => ";" == s,
598 if is_semi || self.is_begin() || self.is_end() {
599 hardbreak(self.writer())?;
601 hardbreak(self.writer())
606 fn next_comment(&mut self) -> Option<comments::Comment> {
607 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
608 match *self.comments() {
610 if cur_cmnt < cmnts.len() {
611 Some(cmnts[cur_cmnt].clone())
620 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
621 self.maybe_print_comment(lit.span.lo)?;
622 match self.next_lit(lit.span.lo) {
624 return word(self.writer(), &(*ltrl).lit);
629 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
630 ast::LitKind::Byte(byte) => {
631 let mut res = String::from("b'");
632 res.extend(ascii::escape_default(byte).map(|c| c as char));
634 word(self.writer(), &res[..])
636 ast::LitKind::Char(ch) => {
637 let mut res = String::from("'");
638 res.extend(ch.escape_default());
640 word(self.writer(), &res[..])
642 ast::LitKind::Int(i, t) => {
644 ast::LitIntType::Signed(st) => {
645 word(self.writer(), &st.val_to_string(i as i128))
647 ast::LitIntType::Unsigned(ut) => {
648 word(self.writer(), &ut.val_to_string(i))
650 ast::LitIntType::Unsuffixed => {
651 word(self.writer(), &format!("{}", i))
655 ast::LitKind::Float(ref f, t) => {
662 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()),
663 ast::LitKind::Bool(val) => {
664 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
666 ast::LitKind::ByteStr(ref v) => {
667 let mut escaped: String = String::new();
668 for &ch in v.iter() {
669 escaped.extend(ascii::escape_default(ch)
670 .map(|c| c as char));
672 word(self.writer(), &format!("b\"{}\"", escaped))
677 fn print_string(&mut self, st: &str,
678 style: ast::StrStyle) -> io::Result<()> {
679 let st = match style {
680 ast::StrStyle::Cooked => {
681 (format!("\"{}\"", st.escape_default()))
683 ast::StrStyle::Raw(n) => {
684 (format!("r{delim}\"{string}\"{delim}",
685 delim=repeat("#", n),
689 word(self.writer(), &st[..])
692 fn print_inner_attributes(&mut self,
693 attrs: &[ast::Attribute]) -> io::Result<()> {
694 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
697 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
698 attrs: &[ast::Attribute])
700 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
703 fn print_outer_attributes(&mut self,
704 attrs: &[ast::Attribute]) -> io::Result<()> {
705 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
708 fn print_inner_attributes_inline(&mut self,
709 attrs: &[ast::Attribute]) -> io::Result<()> {
710 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
713 fn print_outer_attributes_inline(&mut self,
714 attrs: &[ast::Attribute]) -> io::Result<()> {
715 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
718 fn print_either_attributes(&mut self,
719 attrs: &[ast::Attribute],
720 kind: ast::AttrStyle,
722 trailing_hardbreak: bool) -> io::Result<()> {
725 if attr.style == kind {
726 self.print_attribute_inline(attr, is_inline)?;
733 if count > 0 && trailing_hardbreak && !is_inline {
734 self.hardbreak_if_not_bol()?;
739 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
740 self.print_attribute_inline(attr, false)
743 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
744 is_inline: bool) -> io::Result<()> {
746 self.hardbreak_if_not_bol()?;
748 self.maybe_print_comment(attr.span.lo)?;
749 if attr.is_sugared_doc {
750 word(self.writer(), &attr.value_str().unwrap().as_str())?;
751 hardbreak(self.writer())
754 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
755 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
757 if let Some(mi) = attr.meta() {
758 self.print_meta_item(&mi)?
760 for (i, segment) in attr.path.segments.iter().enumerate() {
762 word(self.writer(), "::")?
764 if segment.identifier.name != keywords::CrateRoot.name() &&
765 segment.identifier.name != "$crate" {
766 word(self.writer(), &segment.identifier.name.as_str())?;
769 space(self.writer())?;
770 self.print_tts(attr.tokens.clone())?;
772 word(self.writer(), "]")
776 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
778 ast::NestedMetaItemKind::MetaItem(ref mi) => {
779 self.print_meta_item(mi)
781 ast::NestedMetaItemKind::Literal(ref lit) => {
782 self.print_literal(lit)
787 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
788 self.ibox(INDENT_UNIT)?;
790 ast::MetaItemKind::Word => {
791 word(self.writer(), &item.name.as_str())?;
793 ast::MetaItemKind::NameValue(ref value) => {
794 self.word_space(&item.name.as_str())?;
795 self.word_space("=")?;
796 self.print_literal(value)?;
798 ast::MetaItemKind::List(ref items) => {
799 word(self.writer(), &item.name.as_str())?;
801 self.commasep(Consistent,
803 |s, i| s.print_meta_list_item(&i))?;
810 /// This doesn't deserve to be called "pretty" printing, but it should be
811 /// meaning-preserving. A quick hack that might help would be to look at the
812 /// spans embedded in the TTs to decide where to put spaces and newlines.
813 /// But it'd be better to parse these according to the grammar of the
814 /// appropriate macro, transcribe back into the grammar we just parsed from,
815 /// and then pretty-print the resulting AST nodes (so, e.g., we print
816 /// expression arguments as expressions). It can be done! I think.
817 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
819 TokenTree::Token(_, ref tk) => {
820 word(self.writer(), &token_to_string(tk))?;
822 parse::token::DocComment(..) => {
823 hardbreak(self.writer())
828 TokenTree::Delimited(_, ref delimed) => {
829 word(self.writer(), &token_to_string(&delimed.open_token()))?;
830 space(self.writer())?;
831 self.print_tts(delimed.stream())?;
832 space(self.writer())?;
833 word(self.writer(), &token_to_string(&delimed.close_token()))
838 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
840 for (i, tt) in tts.into_trees().enumerate() {
842 space(self.writer())?;
849 fn space_if_not_bol(&mut self) -> io::Result<()> {
850 if !self.is_bol() { space(self.writer())?; }
854 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
857 impl<'a> PrintState<'a> for State<'a> {
858 fn writer(&mut self) -> &mut pp::Printer<'a> {
862 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
866 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
870 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
871 &mut self.cur_cmnt_and_lit
874 fn literals(&self) -> &Option<Vec<comments::Literal>> {
880 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
881 self.boxes.push(pp::Breaks::Consistent);
882 pp::cbox(&mut self.s, u)
885 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
886 word(&mut self.s, w)?;
890 pub fn head(&mut self, w: &str) -> io::Result<()> {
891 // outer-box is consistent
892 self.cbox(INDENT_UNIT)?;
893 // head-box is inconsistent
894 self.ibox(w.len() + 1)?;
895 // keyword that starts the head
902 pub fn bopen(&mut self) -> io::Result<()> {
903 word(&mut self.s, "{")?;
904 self.end() // close the head-box
907 pub fn bclose_(&mut self, span: syntax_pos::Span,
908 indented: usize) -> io::Result<()> {
909 self.bclose_maybe_open(span, indented, true)
911 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
912 indented: usize, close_box: bool) -> io::Result<()> {
913 self.maybe_print_comment(span.hi)?;
914 self.break_offset_if_not_bol(1, -(indented as isize))?;
915 word(&mut self.s, "}")?;
917 self.end()?; // close the outer-box
921 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
922 self.bclose_(span, INDENT_UNIT)
925 pub fn in_cbox(&self) -> bool {
926 match self.boxes.last() {
927 Some(&last_box) => last_box == pp::Breaks::Consistent,
932 pub fn break_offset_if_not_bol(&mut self, n: usize,
933 off: isize) -> io::Result<()> {
935 break_offset(&mut self.s, n, off)
937 if off != 0 && self.s.last_token().is_hardbreak_tok() {
938 // We do something pretty sketchy here: tuck the nonzero
939 // offset-adjustment we were going to deposit along with the
940 // break into the previous hardbreak.
941 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
947 // Synthesizes a comment that was not textually present in the original source
949 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
950 word(&mut self.s, "/*")?;
952 word(&mut self.s, &text[..])?;
954 word(&mut self.s, "*/")
959 pub fn commasep_cmnt<T, F, G>(&mut self,
963 mut get_span: G) -> io::Result<()> where
964 F: FnMut(&mut State, &T) -> io::Result<()>,
965 G: FnMut(&T) -> syntax_pos::Span,
968 let len = elts.len();
971 self.maybe_print_comment(get_span(elt).hi)?;
975 word(&mut self.s, ",")?;
976 self.maybe_print_trailing_comment(get_span(elt),
977 Some(get_span(&elts[i]).hi))?;
978 self.space_if_not_bol()?;
984 pub fn commasep_exprs(&mut self, b: Breaks,
985 exprs: &[P<ast::Expr>]) -> io::Result<()> {
986 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
989 pub fn print_mod(&mut self, _mod: &ast::Mod,
990 attrs: &[ast::Attribute]) -> io::Result<()> {
991 self.print_inner_attributes(attrs)?;
992 for item in &_mod.items {
993 self.print_item(&item)?;
998 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
999 attrs: &[ast::Attribute]) -> io::Result<()> {
1000 self.print_inner_attributes(attrs)?;
1001 for item in &nmod.items {
1002 self.print_foreign_item(item)?;
1007 pub fn print_opt_lifetime(&mut self,
1008 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1009 if let Some(l) = *lifetime {
1010 self.print_lifetime(&l)?;
1016 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1017 self.maybe_print_comment(ty.span.lo)?;
1020 ast::TyKind::Slice(ref ty) => {
1021 word(&mut self.s, "[")?;
1022 self.print_type(&ty)?;
1023 word(&mut self.s, "]")?;
1025 ast::TyKind::Ptr(ref mt) => {
1026 word(&mut self.s, "*")?;
1028 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1029 ast::Mutability::Immutable => self.word_nbsp("const")?,
1031 self.print_type(&mt.ty)?;
1033 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1034 word(&mut self.s, "&")?;
1035 self.print_opt_lifetime(lifetime)?;
1038 ast::TyKind::Never => {
1039 word(&mut self.s, "!")?;
1041 ast::TyKind::Tup(ref elts) => {
1043 self.commasep(Inconsistent, &elts[..],
1044 |s, ty| s.print_type(&ty))?;
1045 if elts.len() == 1 {
1046 word(&mut self.s, ",")?;
1050 ast::TyKind::Paren(ref typ) => {
1052 self.print_type(&typ)?;
1055 ast::TyKind::BareFn(ref f) => {
1056 let generics = ast::Generics {
1057 lifetimes: f.lifetimes.clone(),
1058 ty_params: Vec::new(),
1059 where_clause: ast::WhereClause {
1060 id: ast::DUMMY_NODE_ID,
1061 predicates: Vec::new(),
1063 span: syntax_pos::DUMMY_SP,
1065 self.print_ty_fn(f.abi,
1071 ast::TyKind::Path(None, ref path) => {
1072 self.print_path(path, false, 0, false)?;
1074 ast::TyKind::Path(Some(ref qself), ref path) => {
1075 self.print_qpath(path, qself, false)?
1077 ast::TyKind::TraitObject(ref bounds) => {
1078 self.print_bounds("", &bounds[..])?;
1080 ast::TyKind::ImplTrait(ref bounds) => {
1081 self.print_bounds("impl ", &bounds[..])?;
1083 ast::TyKind::Array(ref ty, ref v) => {
1084 word(&mut self.s, "[")?;
1085 self.print_type(&ty)?;
1086 word(&mut self.s, "; ")?;
1087 self.print_expr(&v)?;
1088 word(&mut self.s, "]")?;
1090 ast::TyKind::Typeof(ref e) => {
1091 word(&mut self.s, "typeof(")?;
1092 self.print_expr(&e)?;
1093 word(&mut self.s, ")")?;
1095 ast::TyKind::Infer => {
1096 word(&mut self.s, "_")?;
1098 ast::TyKind::Err => {
1099 word(&mut self.s, "?")?;
1101 ast::TyKind::ImplicitSelf => {
1102 word(&mut self.s, "Self")?;
1104 ast::TyKind::Mac(ref m) => {
1105 self.print_mac(m, token::Paren)?;
1111 pub fn print_foreign_item(&mut self,
1112 item: &ast::ForeignItem) -> io::Result<()> {
1113 self.hardbreak_if_not_bol()?;
1114 self.maybe_print_comment(item.span.lo)?;
1115 self.print_outer_attributes(&item.attrs)?;
1117 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1119 self.print_fn(decl, ast::Unsafety::Normal,
1120 ast::Constness::NotConst,
1121 Abi::Rust, Some(item.ident),
1122 generics, &item.vis)?;
1123 self.end()?; // end head-ibox
1124 word(&mut self.s, ";")?;
1125 self.end() // end the outer fn box
1127 ast::ForeignItemKind::Static(ref t, m) => {
1128 self.head(&visibility_qualified(&item.vis, "static"))?;
1130 self.word_space("mut")?;
1132 self.print_ident(item.ident)?;
1133 self.word_space(":")?;
1134 self.print_type(&t)?;
1135 word(&mut self.s, ";")?;
1136 self.end()?; // end the head-ibox
1137 self.end() // end the outer cbox
1142 fn print_associated_const(&mut self,
1145 default: Option<&ast::Expr>,
1146 vis: &ast::Visibility)
1149 word(&mut self.s, &visibility_qualified(vis, ""))?;
1150 self.word_space("const")?;
1151 self.print_ident(ident)?;
1152 self.word_space(":")?;
1153 self.print_type(ty)?;
1154 if let Some(expr) = default {
1155 space(&mut self.s)?;
1156 self.word_space("=")?;
1157 self.print_expr(expr)?;
1159 word(&mut self.s, ";")
1162 fn print_associated_type(&mut self,
1164 bounds: Option<&ast::TyParamBounds>,
1165 ty: Option<&ast::Ty>)
1167 self.word_space("type")?;
1168 self.print_ident(ident)?;
1169 if let Some(bounds) = bounds {
1170 self.print_bounds(":", bounds)?;
1172 if let Some(ty) = ty {
1173 space(&mut self.s)?;
1174 self.word_space("=")?;
1175 self.print_type(ty)?;
1177 word(&mut self.s, ";")
1180 /// Pretty-print an item
1181 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1182 self.hardbreak_if_not_bol()?;
1183 self.maybe_print_comment(item.span.lo)?;
1184 self.print_outer_attributes(&item.attrs)?;
1185 self.ann.pre(self, NodeItem(item))?;
1187 ast::ItemKind::ExternCrate(ref optional_path) => {
1188 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1189 if let Some(p) = *optional_path {
1190 let val = p.as_str();
1191 if val.contains("-") {
1192 self.print_string(&val, ast::StrStyle::Cooked)?;
1194 self.print_name(p)?;
1196 space(&mut self.s)?;
1197 word(&mut self.s, "as")?;
1198 space(&mut self.s)?;
1200 self.print_ident(item.ident)?;
1201 word(&mut self.s, ";")?;
1202 self.end()?; // end inner head-block
1203 self.end()?; // end outer head-block
1205 ast::ItemKind::Use(ref vp) => {
1206 self.head(&visibility_qualified(&item.vis, "use"))?;
1207 self.print_view_path(&vp)?;
1208 word(&mut self.s, ";")?;
1209 self.end()?; // end inner head-block
1210 self.end()?; // end outer head-block
1212 ast::ItemKind::Static(ref ty, m, ref expr) => {
1213 self.head(&visibility_qualified(&item.vis, "static"))?;
1214 if m == ast::Mutability::Mutable {
1215 self.word_space("mut")?;
1217 self.print_ident(item.ident)?;
1218 self.word_space(":")?;
1219 self.print_type(&ty)?;
1220 space(&mut self.s)?;
1221 self.end()?; // end the head-ibox
1223 self.word_space("=")?;
1224 self.print_expr(&expr)?;
1225 word(&mut self.s, ";")?;
1226 self.end()?; // end the outer cbox
1228 ast::ItemKind::Const(ref ty, ref expr) => {
1229 self.head(&visibility_qualified(&item.vis, "const"))?;
1230 self.print_ident(item.ident)?;
1231 self.word_space(":")?;
1232 self.print_type(&ty)?;
1233 space(&mut self.s)?;
1234 self.end()?; // end the head-ibox
1236 self.word_space("=")?;
1237 self.print_expr(&expr)?;
1238 word(&mut self.s, ";")?;
1239 self.end()?; // end the outer cbox
1241 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1252 word(&mut self.s, " ")?;
1253 self.print_block_with_attrs(&body, &item.attrs)?;
1255 ast::ItemKind::Mod(ref _mod) => {
1256 self.head(&visibility_qualified(&item.vis, "mod"))?;
1257 self.print_ident(item.ident)?;
1260 self.print_mod(_mod, &item.attrs)?;
1261 self.bclose(item.span)?;
1263 ast::ItemKind::ForeignMod(ref nmod) => {
1264 self.head("extern")?;
1265 self.word_nbsp(&nmod.abi.to_string())?;
1267 self.print_foreign_mod(nmod, &item.attrs)?;
1268 self.bclose(item.span)?;
1270 ast::ItemKind::GlobalAsm(ref ga) => {
1271 self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
1272 word(&mut self.s, &ga.asm.as_str())?;
1275 ast::ItemKind::Ty(ref ty, ref params) => {
1276 self.ibox(INDENT_UNIT)?;
1278 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1279 self.print_ident(item.ident)?;
1280 self.print_generics(params)?;
1281 self.end()?; // end the inner ibox
1283 self.print_where_clause(¶ms.where_clause)?;
1284 space(&mut self.s)?;
1285 self.word_space("=")?;
1286 self.print_type(&ty)?;
1287 word(&mut self.s, ";")?;
1288 self.end()?; // end the outer ibox
1290 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1291 self.print_enum_def(
1299 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1300 self.head(&visibility_qualified(&item.vis, "struct"))?;
1301 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1303 ast::ItemKind::Union(ref struct_def, ref generics) => {
1304 self.head(&visibility_qualified(&item.vis, "union"))?;
1305 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1307 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1309 self.print_visibility(&item.vis)?;
1310 self.print_unsafety(unsafety)?;
1311 self.word_nbsp("impl")?;
1312 self.print_trait_ref(trait_ref)?;
1313 space(&mut self.s)?;
1314 self.word_space("for")?;
1315 self.word_space("..")?;
1317 self.bclose(item.span)?;
1319 ast::ItemKind::Impl(unsafety,
1324 ref impl_items) => {
1326 self.print_visibility(&item.vis)?;
1327 self.print_unsafety(unsafety)?;
1328 self.word_nbsp("impl")?;
1330 if generics.is_parameterized() {
1331 self.print_generics(generics)?;
1332 space(&mut self.s)?;
1336 ast::ImplPolarity::Negative => {
1337 word(&mut self.s, "!")?;
1342 if let Some(ref t) = *opt_trait {
1343 self.print_trait_ref(t)?;
1344 space(&mut self.s)?;
1345 self.word_space("for")?;
1348 self.print_type(&ty)?;
1349 self.print_where_clause(&generics.where_clause)?;
1351 space(&mut self.s)?;
1353 self.print_inner_attributes(&item.attrs)?;
1354 for impl_item in impl_items {
1355 self.print_impl_item(impl_item)?;
1357 self.bclose(item.span)?;
1359 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1361 self.print_visibility(&item.vis)?;
1362 self.print_unsafety(unsafety)?;
1363 self.word_nbsp("trait")?;
1364 self.print_ident(item.ident)?;
1365 self.print_generics(generics)?;
1366 let mut real_bounds = Vec::with_capacity(bounds.len());
1367 for b in bounds.iter() {
1368 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1369 space(&mut self.s)?;
1370 self.word_space("for ?")?;
1371 self.print_trait_ref(&ptr.trait_ref)?;
1373 real_bounds.push(b.clone());
1376 self.print_bounds(":", &real_bounds[..])?;
1377 self.print_where_clause(&generics.where_clause)?;
1378 word(&mut self.s, " ")?;
1380 for trait_item in trait_items {
1381 self.print_trait_item(trait_item)?;
1383 self.bclose(item.span)?;
1385 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1386 self.print_path(&node.path, false, 0, false)?;
1387 word(&mut self.s, "! ")?;
1388 self.print_ident(item.ident)?;
1389 self.cbox(INDENT_UNIT)?;
1391 self.print_tts(node.stream())?;
1393 word(&mut self.s, ";")?;
1396 ast::ItemKind::MacroDef(ref tts) => {
1397 word(&mut self.s, "macro_rules! ")?;
1398 self.print_ident(item.ident)?;
1399 self.cbox(INDENT_UNIT)?;
1401 self.print_tts(tts.clone().into())?;
1403 word(&mut self.s, ";")?;
1407 self.ann.post(self, NodeItem(item))
1410 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1411 self.print_path(&t.path, false, 0, false)
1414 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1415 if !lifetimes.is_empty() {
1416 word(&mut self.s, "for<")?;
1417 let mut comma = false;
1418 for lifetime_def in lifetimes {
1420 self.word_space(",")?
1422 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1423 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1426 word(&mut self.s, ">")?;
1431 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1432 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1433 self.print_trait_ref(&t.trait_ref)
1436 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1437 generics: &ast::Generics, ident: ast::Ident,
1438 span: syntax_pos::Span,
1439 visibility: &ast::Visibility) -> io::Result<()> {
1440 self.head(&visibility_qualified(visibility, "enum"))?;
1441 self.print_ident(ident)?;
1442 self.print_generics(generics)?;
1443 self.print_where_clause(&generics.where_clause)?;
1444 space(&mut self.s)?;
1445 self.print_variants(&enum_definition.variants, span)
1448 pub fn print_variants(&mut self,
1449 variants: &[ast::Variant],
1450 span: syntax_pos::Span) -> io::Result<()> {
1453 self.space_if_not_bol()?;
1454 self.maybe_print_comment(v.span.lo)?;
1455 self.print_outer_attributes(&v.node.attrs)?;
1456 self.ibox(INDENT_UNIT)?;
1457 self.print_variant(v)?;
1458 word(&mut self.s, ",")?;
1460 self.maybe_print_trailing_comment(v.span, None)?;
1465 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1467 ast::Visibility::Public => self.word_nbsp("pub"),
1468 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1469 ast::Visibility::Restricted { ref path, .. } => {
1470 let path = to_string(|s| s.print_path(path, false, 0, true));
1471 self.word_nbsp(&format!("pub({})", path))
1473 ast::Visibility::Inherited => Ok(())
1477 pub fn print_struct(&mut self,
1478 struct_def: &ast::VariantData,
1479 generics: &ast::Generics,
1481 span: syntax_pos::Span,
1482 print_finalizer: bool) -> io::Result<()> {
1483 self.print_ident(ident)?;
1484 self.print_generics(generics)?;
1485 if !struct_def.is_struct() {
1486 if struct_def.is_tuple() {
1489 Inconsistent, struct_def.fields(),
1491 s.maybe_print_comment(field.span.lo)?;
1492 s.print_outer_attributes(&field.attrs)?;
1493 s.print_visibility(&field.vis)?;
1494 s.print_type(&field.ty)
1499 self.print_where_clause(&generics.where_clause)?;
1500 if print_finalizer {
1501 word(&mut self.s, ";")?;
1504 self.end() // close the outer-box
1506 self.print_where_clause(&generics.where_clause)?;
1509 self.hardbreak_if_not_bol()?;
1511 for field in struct_def.fields() {
1512 self.hardbreak_if_not_bol()?;
1513 self.maybe_print_comment(field.span.lo)?;
1514 self.print_outer_attributes(&field.attrs)?;
1515 self.print_visibility(&field.vis)?;
1516 self.print_ident(field.ident.unwrap())?;
1517 self.word_nbsp(":")?;
1518 self.print_type(&field.ty)?;
1519 word(&mut self.s, ",")?;
1526 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1528 let generics = ast::Generics::default();
1529 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1530 match v.node.disr_expr {
1532 space(&mut self.s)?;
1533 self.word_space("=")?;
1540 pub fn print_method_sig(&mut self,
1543 vis: &ast::Visibility)
1545 self.print_fn(&m.decl,
1554 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1556 self.ann.pre(self, NodeSubItem(ti.id))?;
1557 self.hardbreak_if_not_bol()?;
1558 self.maybe_print_comment(ti.span.lo)?;
1559 self.print_outer_attributes(&ti.attrs)?;
1561 ast::TraitItemKind::Const(ref ty, ref default) => {
1562 self.print_associated_const(ti.ident, &ty,
1563 default.as_ref().map(|expr| &**expr),
1564 &ast::Visibility::Inherited)?;
1566 ast::TraitItemKind::Method(ref sig, ref body) => {
1570 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1571 if let Some(ref body) = *body {
1573 self.print_block_with_attrs(body, &ti.attrs)?;
1575 word(&mut self.s, ";")?;
1578 ast::TraitItemKind::Type(ref bounds, ref default) => {
1579 self.print_associated_type(ti.ident, Some(bounds),
1580 default.as_ref().map(|ty| &**ty))?;
1582 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1583 // code copied from ItemKind::Mac:
1584 self.print_path(&node.path, false, 0, false)?;
1585 word(&mut self.s, "! ")?;
1586 self.cbox(INDENT_UNIT)?;
1588 self.print_tts(node.stream())?;
1590 word(&mut self.s, ";")?;
1594 self.ann.post(self, NodeSubItem(ti.id))
1597 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1598 self.ann.pre(self, NodeSubItem(ii.id))?;
1599 self.hardbreak_if_not_bol()?;
1600 self.maybe_print_comment(ii.span.lo)?;
1601 self.print_outer_attributes(&ii.attrs)?;
1602 if let ast::Defaultness::Default = ii.defaultness {
1603 self.word_nbsp("default")?;
1606 ast::ImplItemKind::Const(ref ty, ref expr) => {
1607 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1609 ast::ImplItemKind::Method(ref sig, ref body) => {
1611 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1613 self.print_block_with_attrs(body, &ii.attrs)?;
1615 ast::ImplItemKind::Type(ref ty) => {
1616 self.print_associated_type(ii.ident, None, Some(ty))?;
1618 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1619 // code copied from ItemKind::Mac:
1620 self.print_path(&node.path, false, 0, false)?;
1621 word(&mut self.s, "! ")?;
1622 self.cbox(INDENT_UNIT)?;
1624 self.print_tts(node.stream())?;
1626 word(&mut self.s, ";")?;
1630 self.ann.post(self, NodeSubItem(ii.id))
1633 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1634 self.maybe_print_comment(st.span.lo)?;
1636 ast::StmtKind::Local(ref loc) => {
1637 self.print_outer_attributes(&loc.attrs)?;
1638 self.space_if_not_bol()?;
1639 self.ibox(INDENT_UNIT)?;
1640 self.word_nbsp("let")?;
1642 self.ibox(INDENT_UNIT)?;
1643 self.print_local_decl(&loc)?;
1645 if let Some(ref init) = loc.init {
1647 self.word_space("=")?;
1648 self.print_expr(&init)?;
1650 word(&mut self.s, ";")?;
1653 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1654 ast::StmtKind::Expr(ref expr) => {
1655 self.space_if_not_bol()?;
1656 self.print_expr_outer_attr_style(&expr, false)?;
1657 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1658 word(&mut self.s, ";")?;
1661 ast::StmtKind::Semi(ref expr) => {
1662 self.space_if_not_bol()?;
1663 self.print_expr_outer_attr_style(&expr, false)?;
1664 word(&mut self.s, ";")?;
1666 ast::StmtKind::Mac(ref mac) => {
1667 let (ref mac, style, ref attrs) = **mac;
1668 self.space_if_not_bol()?;
1669 self.print_outer_attributes(&attrs)?;
1670 let delim = match style {
1671 ast::MacStmtStyle::Braces => token::Brace,
1674 self.print_mac(&mac, delim)?;
1675 if style == ast::MacStmtStyle::Semicolon {
1676 word(&mut self.s, ";")?;
1680 self.maybe_print_trailing_comment(st.span, None)
1683 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1684 self.print_block_with_attrs(blk, &[])
1687 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1688 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1691 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1692 attrs: &[ast::Attribute])
1694 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1697 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1698 indented: usize) -> io::Result<()> {
1699 self.print_block_maybe_unclosed(blk, indented, &[], false)
1702 pub fn print_block_with_attrs(&mut self,
1704 attrs: &[ast::Attribute]) -> io::Result<()> {
1705 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1708 pub fn print_block_maybe_unclosed(&mut self,
1711 attrs: &[ast::Attribute],
1712 close_box: bool) -> io::Result<()> {
1714 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1715 BlockCheckMode::Default => ()
1717 self.maybe_print_comment(blk.span.lo)?;
1718 self.ann.pre(self, NodeBlock(blk))?;
1721 self.print_inner_attributes(attrs)?;
1723 for (i, st) in blk.stmts.iter().enumerate() {
1725 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1726 self.maybe_print_comment(st.span.lo)?;
1727 self.space_if_not_bol()?;
1728 self.print_expr_outer_attr_style(&expr, false)?;
1729 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1731 _ => self.print_stmt(st)?,
1735 self.bclose_maybe_open(blk.span, indented, close_box)?;
1736 self.ann.post(self, NodeBlock(blk))
1739 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1743 // "another else-if"
1744 ast::ExprKind::If(ref i, ref then, ref e) => {
1745 self.cbox(INDENT_UNIT - 1)?;
1747 word(&mut self.s, " else if ")?;
1748 self.print_expr(&i)?;
1749 space(&mut self.s)?;
1750 self.print_block(&then)?;
1751 self.print_else(e.as_ref().map(|e| &**e))
1753 // "another else-if-let"
1754 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1755 self.cbox(INDENT_UNIT - 1)?;
1757 word(&mut self.s, " else if let ")?;
1758 self.print_pat(&pat)?;
1759 space(&mut self.s)?;
1760 self.word_space("=")?;
1761 self.print_expr(&expr)?;
1762 space(&mut self.s)?;
1763 self.print_block(&then)?;
1764 self.print_else(e.as_ref().map(|e| &**e))
1767 ast::ExprKind::Block(ref b) => {
1768 self.cbox(INDENT_UNIT - 1)?;
1770 word(&mut self.s, " else ")?;
1771 self.print_block(&b)
1773 // BLEAH, constraints would be great here
1775 panic!("print_if saw if with weird alternative");
1783 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1784 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1786 self.print_expr(test)?;
1787 space(&mut self.s)?;
1788 self.print_block(blk)?;
1789 self.print_else(elseopt)
1792 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1793 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1794 self.head("if let")?;
1795 self.print_pat(pat)?;
1796 space(&mut self.s)?;
1797 self.word_space("=")?;
1798 self.print_expr(expr)?;
1799 space(&mut self.s)?;
1800 self.print_block(blk)?;
1801 self.print_else(elseopt)
1804 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1806 self.print_path(&m.node.path, false, 0, false)?;
1807 word(&mut self.s, "!")?;
1809 token::Paren => self.popen()?,
1810 token::Bracket => word(&mut self.s, "[")?,
1815 token::NoDelim => {}
1817 self.print_tts(m.node.stream())?;
1819 token::Paren => self.pclose(),
1820 token::Bracket => word(&mut self.s, "]"),
1821 token::Brace => self.bclose(m.span),
1822 token::NoDelim => Ok(()),
1827 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1829 self.commasep_exprs(Inconsistent, args)?;
1833 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1834 binop: ast::BinOp) -> bool {
1835 match sub_expr.node {
1836 ast::ExprKind::Binary(ref sub_op, _, _) => {
1837 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1838 AssocOp::from_ast_binop(binop.node).precedence() {
1848 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1849 let needs_par = needs_parentheses(expr);
1853 self.print_expr(expr)?;
1860 fn print_expr_in_place(&mut self,
1862 expr: &ast::Expr) -> io::Result<()> {
1863 self.print_expr_maybe_paren(place)?;
1864 space(&mut self.s)?;
1865 self.word_space("<-")?;
1866 self.print_expr_maybe_paren(expr)
1869 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1870 attrs: &[Attribute]) -> io::Result<()> {
1871 self.ibox(INDENT_UNIT)?;
1872 word(&mut self.s, "[")?;
1873 self.print_inner_attributes_inline(attrs)?;
1874 self.commasep_exprs(Inconsistent, &exprs[..])?;
1875 word(&mut self.s, "]")?;
1879 fn print_expr_repeat(&mut self,
1880 element: &ast::Expr,
1882 attrs: &[Attribute]) -> io::Result<()> {
1883 self.ibox(INDENT_UNIT)?;
1884 word(&mut self.s, "[")?;
1885 self.print_inner_attributes_inline(attrs)?;
1886 self.print_expr(element)?;
1887 self.word_space(";")?;
1888 self.print_expr(count)?;
1889 word(&mut self.s, "]")?;
1893 fn print_expr_struct(&mut self,
1895 fields: &[ast::Field],
1896 wth: &Option<P<ast::Expr>>,
1897 attrs: &[Attribute]) -> io::Result<()> {
1898 self.print_path(path, true, 0, false)?;
1899 word(&mut self.s, "{")?;
1900 self.print_inner_attributes_inline(attrs)?;
1905 s.ibox(INDENT_UNIT)?;
1906 if !field.is_shorthand {
1907 s.print_ident(field.ident.node)?;
1910 s.print_expr(&field.expr)?;
1916 self.ibox(INDENT_UNIT)?;
1917 if !fields.is_empty() {
1918 word(&mut self.s, ",")?;
1919 space(&mut self.s)?;
1921 word(&mut self.s, "..")?;
1922 self.print_expr(&expr)?;
1925 _ => if !fields.is_empty() {
1926 word(&mut self.s, ",")?
1929 word(&mut self.s, "}")?;
1933 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1934 attrs: &[Attribute]) -> io::Result<()> {
1936 self.print_inner_attributes_inline(attrs)?;
1937 self.commasep_exprs(Inconsistent, &exprs[..])?;
1938 if exprs.len() == 1 {
1939 word(&mut self.s, ",")?;
1944 fn print_expr_call(&mut self,
1946 args: &[P<ast::Expr>]) -> io::Result<()> {
1947 self.print_expr_maybe_paren(func)?;
1948 self.print_call_post(args)
1951 fn print_expr_method_call(&mut self,
1952 ident: ast::SpannedIdent,
1954 args: &[P<ast::Expr>]) -> io::Result<()> {
1955 let base_args = &args[1..];
1956 self.print_expr(&args[0])?;
1957 word(&mut self.s, ".")?;
1958 self.print_ident(ident.node)?;
1959 if !tys.is_empty() {
1960 word(&mut self.s, "::<")?;
1961 self.commasep(Inconsistent, tys,
1962 |s, ty| s.print_type(&ty))?;
1963 word(&mut self.s, ">")?;
1965 self.print_call_post(base_args)
1968 fn print_expr_binary(&mut self,
1971 rhs: &ast::Expr) -> io::Result<()> {
1972 if self.check_expr_bin_needs_paren(lhs, op) {
1973 self.print_expr_maybe_paren(lhs)?;
1975 self.print_expr(lhs)?;
1977 space(&mut self.s)?;
1978 self.word_space(op.node.to_string())?;
1979 if self.check_expr_bin_needs_paren(rhs, op) {
1980 self.print_expr_maybe_paren(rhs)
1982 self.print_expr(rhs)
1986 fn print_expr_unary(&mut self,
1988 expr: &ast::Expr) -> io::Result<()> {
1989 word(&mut self.s, ast::UnOp::to_string(op))?;
1990 self.print_expr_maybe_paren(expr)
1993 fn print_expr_addr_of(&mut self,
1994 mutability: ast::Mutability,
1995 expr: &ast::Expr) -> io::Result<()> {
1996 word(&mut self.s, "&")?;
1997 self.print_mutability(mutability)?;
1998 self.print_expr_maybe_paren(expr)
2001 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2002 self.print_expr_outer_attr_style(expr, true)
2005 fn print_expr_outer_attr_style(&mut self,
2007 is_inline: bool) -> io::Result<()> {
2008 self.maybe_print_comment(expr.span.lo)?;
2010 let attrs = &expr.attrs;
2012 self.print_outer_attributes_inline(attrs)?;
2014 self.print_outer_attributes(attrs)?;
2017 self.ibox(INDENT_UNIT)?;
2018 self.ann.pre(self, NodeExpr(expr))?;
2020 ast::ExprKind::Box(ref expr) => {
2021 self.word_space("box")?;
2022 self.print_expr(expr)?;
2024 ast::ExprKind::InPlace(ref place, ref expr) => {
2025 self.print_expr_in_place(place, expr)?;
2027 ast::ExprKind::Array(ref exprs) => {
2028 self.print_expr_vec(&exprs[..], attrs)?;
2030 ast::ExprKind::Repeat(ref element, ref count) => {
2031 self.print_expr_repeat(&element, &count, attrs)?;
2033 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2034 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2036 ast::ExprKind::Tup(ref exprs) => {
2037 self.print_expr_tup(&exprs[..], attrs)?;
2039 ast::ExprKind::Call(ref func, ref args) => {
2040 self.print_expr_call(&func, &args[..])?;
2042 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2043 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2045 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2046 self.print_expr_binary(op, &lhs, &rhs)?;
2048 ast::ExprKind::Unary(op, ref expr) => {
2049 self.print_expr_unary(op, &expr)?;
2051 ast::ExprKind::AddrOf(m, ref expr) => {
2052 self.print_expr_addr_of(m, &expr)?;
2054 ast::ExprKind::Lit(ref lit) => {
2055 self.print_literal(&lit)?;
2057 ast::ExprKind::Cast(ref expr, ref ty) => {
2058 if let ast::ExprKind::Cast(..) = expr.node {
2059 self.print_expr(&expr)?;
2061 self.print_expr_maybe_paren(&expr)?;
2063 space(&mut self.s)?;
2064 self.word_space("as")?;
2065 self.print_type(&ty)?;
2067 ast::ExprKind::Type(ref expr, ref ty) => {
2068 self.print_expr(&expr)?;
2069 self.word_space(":")?;
2070 self.print_type(&ty)?;
2072 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2073 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2075 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2076 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2078 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2079 if let Some(ident) = opt_ident {
2080 self.print_ident(ident.node)?;
2081 self.word_space(":")?;
2083 self.head("while")?;
2084 self.print_expr(&test)?;
2085 space(&mut self.s)?;
2086 self.print_block_with_attrs(&blk, attrs)?;
2088 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2089 if let Some(ident) = opt_ident {
2090 self.print_ident(ident.node)?;
2091 self.word_space(":")?;
2093 self.head("while let")?;
2094 self.print_pat(&pat)?;
2095 space(&mut self.s)?;
2096 self.word_space("=")?;
2097 self.print_expr(&expr)?;
2098 space(&mut self.s)?;
2099 self.print_block_with_attrs(&blk, attrs)?;
2101 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2102 if let Some(ident) = opt_ident {
2103 self.print_ident(ident.node)?;
2104 self.word_space(":")?;
2107 self.print_pat(&pat)?;
2108 space(&mut self.s)?;
2109 self.word_space("in")?;
2110 self.print_expr(&iter)?;
2111 space(&mut self.s)?;
2112 self.print_block_with_attrs(&blk, attrs)?;
2114 ast::ExprKind::Loop(ref blk, opt_ident) => {
2115 if let Some(ident) = opt_ident {
2116 self.print_ident(ident.node)?;
2117 self.word_space(":")?;
2120 space(&mut self.s)?;
2121 self.print_block_with_attrs(&blk, attrs)?;
2123 ast::ExprKind::Match(ref expr, ref arms) => {
2124 self.cbox(INDENT_UNIT)?;
2126 self.word_nbsp("match")?;
2127 self.print_expr(&expr)?;
2128 space(&mut self.s)?;
2130 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2132 self.print_arm(arm)?;
2134 self.bclose_(expr.span, INDENT_UNIT)?;
2136 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2137 self.print_capture_clause(capture_clause)?;
2139 self.print_fn_block_args(&decl)?;
2140 space(&mut self.s)?;
2141 self.print_expr(body)?;
2142 self.end()?; // need to close a box
2144 // a box will be closed by print_expr, but we didn't want an overall
2145 // wrapper so we closed the corresponding opening. so create an
2146 // empty box to satisfy the close.
2149 ast::ExprKind::Block(ref blk) => {
2150 // containing cbox, will be closed by print-block at }
2151 self.cbox(INDENT_UNIT)?;
2152 // head-box, will be closed by print-block after {
2154 self.print_block_with_attrs(&blk, attrs)?;
2156 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2157 self.print_expr(&lhs)?;
2158 space(&mut self.s)?;
2159 self.word_space("=")?;
2160 self.print_expr(&rhs)?;
2162 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2163 self.print_expr(&lhs)?;
2164 space(&mut self.s)?;
2165 word(&mut self.s, op.node.to_string())?;
2166 self.word_space("=")?;
2167 self.print_expr(&rhs)?;
2169 ast::ExprKind::Field(ref expr, id) => {
2170 self.print_expr(&expr)?;
2171 word(&mut self.s, ".")?;
2172 self.print_ident(id.node)?;
2174 ast::ExprKind::TupField(ref expr, id) => {
2175 self.print_expr(&expr)?;
2176 word(&mut self.s, ".")?;
2177 self.print_usize(id.node)?;
2179 ast::ExprKind::Index(ref expr, ref index) => {
2180 self.print_expr(&expr)?;
2181 word(&mut self.s, "[")?;
2182 self.print_expr(&index)?;
2183 word(&mut self.s, "]")?;
2185 ast::ExprKind::Range(ref start, ref end, limits) => {
2186 if let &Some(ref e) = start {
2187 self.print_expr(&e)?;
2189 if limits == ast::RangeLimits::HalfOpen {
2190 word(&mut self.s, "..")?;
2192 word(&mut self.s, "...")?;
2194 if let &Some(ref e) = end {
2195 self.print_expr(&e)?;
2198 ast::ExprKind::Path(None, ref path) => {
2199 self.print_path(path, true, 0, false)?
2201 ast::ExprKind::Path(Some(ref qself), ref path) => {
2202 self.print_qpath(path, qself, true)?
2204 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2205 word(&mut self.s, "break")?;
2206 space(&mut self.s)?;
2207 if let Some(ident) = opt_ident {
2208 self.print_ident(ident.node)?;
2209 space(&mut self.s)?;
2211 if let Some(ref expr) = *opt_expr {
2212 self.print_expr(expr)?;
2213 space(&mut self.s)?;
2216 ast::ExprKind::Continue(opt_ident) => {
2217 word(&mut self.s, "continue")?;
2218 space(&mut self.s)?;
2219 if let Some(ident) = opt_ident {
2220 self.print_ident(ident.node)?;
2224 ast::ExprKind::Ret(ref result) => {
2225 word(&mut self.s, "return")?;
2228 word(&mut self.s, " ")?;
2229 self.print_expr(&expr)?;
2234 ast::ExprKind::InlineAsm(ref a) => {
2235 word(&mut self.s, "asm!")?;
2237 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2238 self.word_space(":")?;
2240 self.commasep(Inconsistent, &a.outputs, |s, out| {
2241 let constraint = out.constraint.as_str();
2242 let mut ch = constraint.chars();
2244 Some('=') if out.is_rw => {
2245 s.print_string(&format!("+{}", ch.as_str()),
2246 ast::StrStyle::Cooked)?
2248 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2251 s.print_expr(&out.expr)?;
2255 space(&mut self.s)?;
2256 self.word_space(":")?;
2258 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2259 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2265 space(&mut self.s)?;
2266 self.word_space(":")?;
2268 self.commasep(Inconsistent, &a.clobbers,
2270 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2274 let mut options = vec![];
2276 options.push("volatile");
2279 options.push("alignstack");
2281 if a.dialect == ast::AsmDialect::Intel {
2282 options.push("intel");
2285 if !options.is_empty() {
2286 space(&mut self.s)?;
2287 self.word_space(":")?;
2288 self.commasep(Inconsistent, &options,
2290 s.print_string(co, ast::StrStyle::Cooked)?;
2297 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2298 ast::ExprKind::Paren(ref e) => {
2300 self.print_inner_attributes_inline(attrs)?;
2301 self.print_expr(&e)?;
2304 ast::ExprKind::Try(ref e) => {
2305 self.print_expr(e)?;
2306 word(&mut self.s, "?")?
2308 ast::ExprKind::Catch(ref blk) => {
2309 self.head("do catch")?;
2310 space(&mut self.s)?;
2311 self.print_block_with_attrs(&blk, attrs)?
2314 self.ann.post(self, NodeExpr(expr))?;
2318 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2319 self.print_pat(&loc.pat)?;
2320 if let Some(ref ty) = loc.ty {
2321 self.word_space(":")?;
2322 self.print_type(&ty)?;
2327 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2328 word(&mut self.s, &ident.name.as_str())?;
2329 self.ann.post(self, NodeIdent(&ident))
2332 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2333 word(&mut self.s, &i.to_string())
2336 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2337 word(&mut self.s, &name.as_str())?;
2338 self.ann.post(self, NodeName(&name))
2341 pub fn print_for_decl(&mut self, loc: &ast::Local,
2342 coll: &ast::Expr) -> io::Result<()> {
2343 self.print_local_decl(loc)?;
2344 space(&mut self.s)?;
2345 self.word_space("in")?;
2346 self.print_expr(coll)
2349 fn print_path(&mut self,
2351 colons_before_params: bool,
2353 defaults_to_global: bool)
2356 self.maybe_print_comment(path.span.lo)?;
2358 let mut segments = path.segments[..path.segments.len()-depth].iter();
2359 if defaults_to_global && path.is_global() {
2362 for (i, segment) in segments.enumerate() {
2364 word(&mut self.s, "::")?
2366 if segment.identifier.name != keywords::CrateRoot.name() &&
2367 segment.identifier.name != "$crate" {
2368 self.print_ident(segment.identifier)?;
2369 if let Some(ref parameters) = segment.parameters {
2370 self.print_path_parameters(parameters, colons_before_params)?;
2378 fn print_qpath(&mut self,
2381 colons_before_params: bool)
2384 word(&mut self.s, "<")?;
2385 self.print_type(&qself.ty)?;
2386 if qself.position > 0 {
2387 space(&mut self.s)?;
2388 self.word_space("as")?;
2389 let depth = path.segments.len() - qself.position;
2390 self.print_path(&path, false, depth, false)?;
2392 word(&mut self.s, ">")?;
2393 word(&mut self.s, "::")?;
2394 let item_segment = path.segments.last().unwrap();
2395 self.print_ident(item_segment.identifier)?;
2396 match item_segment.parameters {
2397 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2402 fn print_path_parameters(&mut self,
2403 parameters: &ast::PathParameters,
2404 colons_before_params: bool)
2407 if colons_before_params {
2408 word(&mut self.s, "::")?
2412 ast::PathParameters::AngleBracketed(ref data) => {
2413 word(&mut self.s, "<")?;
2415 let mut comma = false;
2416 for lifetime in &data.lifetimes {
2418 self.word_space(",")?
2420 self.print_lifetime(lifetime)?;
2424 if !data.types.is_empty() {
2426 self.word_space(",")?
2431 |s, ty| s.print_type(&ty))?;
2435 for binding in data.bindings.iter() {
2437 self.word_space(",")?
2439 self.print_ident(binding.ident)?;
2440 space(&mut self.s)?;
2441 self.word_space("=")?;
2442 self.print_type(&binding.ty)?;
2446 word(&mut self.s, ">")?
2449 ast::PathParameters::Parenthesized(ref data) => {
2450 word(&mut self.s, "(")?;
2454 |s, ty| s.print_type(&ty))?;
2455 word(&mut self.s, ")")?;
2457 if let Some(ref ty) = data.output {
2458 self.space_if_not_bol()?;
2459 self.word_space("->")?;
2460 self.print_type(&ty)?;
2468 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2469 self.maybe_print_comment(pat.span.lo)?;
2470 self.ann.pre(self, NodePat(pat))?;
2471 /* Pat isn't normalized, but the beauty of it
2472 is that it doesn't matter */
2474 PatKind::Wild => word(&mut self.s, "_")?,
2475 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2476 match binding_mode {
2477 ast::BindingMode::ByRef(mutbl) => {
2478 self.word_nbsp("ref")?;
2479 self.print_mutability(mutbl)?;
2481 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2482 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2483 self.word_nbsp("mut")?;
2486 self.print_ident(path1.node)?;
2487 if let Some(ref p) = *sub {
2488 word(&mut self.s, "@")?;
2489 self.print_pat(&p)?;
2492 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2493 self.print_path(path, true, 0, false)?;
2495 if let Some(ddpos) = ddpos {
2496 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2498 self.word_space(",")?;
2500 word(&mut self.s, "..")?;
2501 if ddpos != elts.len() {
2502 word(&mut self.s, ",")?;
2503 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2506 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2510 PatKind::Path(None, ref path) => {
2511 self.print_path(path, true, 0, false)?;
2513 PatKind::Path(Some(ref qself), ref path) => {
2514 self.print_qpath(path, qself, false)?;
2516 PatKind::Struct(ref path, ref fields, etc) => {
2517 self.print_path(path, true, 0, false)?;
2519 self.word_space("{")?;
2521 Consistent, &fields[..],
2523 s.cbox(INDENT_UNIT)?;
2524 if !f.node.is_shorthand {
2525 s.print_ident(f.node.ident)?;
2528 s.print_pat(&f.node.pat)?;
2531 |f| f.node.pat.span)?;
2533 if !fields.is_empty() { self.word_space(",")?; }
2534 word(&mut self.s, "..")?;
2536 space(&mut self.s)?;
2537 word(&mut self.s, "}")?;
2539 PatKind::Tuple(ref elts, ddpos) => {
2541 if let Some(ddpos) = ddpos {
2542 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2544 self.word_space(",")?;
2546 word(&mut self.s, "..")?;
2547 if ddpos != elts.len() {
2548 word(&mut self.s, ",")?;
2549 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2552 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2553 if elts.len() == 1 {
2554 word(&mut self.s, ",")?;
2559 PatKind::Box(ref inner) => {
2560 word(&mut self.s, "box ")?;
2561 self.print_pat(&inner)?;
2563 PatKind::Ref(ref inner, mutbl) => {
2564 word(&mut self.s, "&")?;
2565 if mutbl == ast::Mutability::Mutable {
2566 word(&mut self.s, "mut ")?;
2568 self.print_pat(&inner)?;
2570 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2571 PatKind::Range(ref begin, ref end, ref end_kind) => {
2572 self.print_expr(&begin)?;
2573 space(&mut self.s)?;
2575 RangeEnd::Included => word(&mut self.s, "...")?,
2576 RangeEnd::Excluded => word(&mut self.s, "..")?,
2578 self.print_expr(&end)?;
2580 PatKind::Slice(ref before, ref slice, ref after) => {
2581 word(&mut self.s, "[")?;
2582 self.commasep(Inconsistent,
2584 |s, p| s.print_pat(&p))?;
2585 if let Some(ref p) = *slice {
2586 if !before.is_empty() { self.word_space(",")?; }
2587 if p.node != PatKind::Wild {
2588 self.print_pat(&p)?;
2590 word(&mut self.s, "..")?;
2591 if !after.is_empty() { self.word_space(",")?; }
2593 self.commasep(Inconsistent,
2595 |s, p| s.print_pat(&p))?;
2596 word(&mut self.s, "]")?;
2598 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2600 self.ann.post(self, NodePat(pat))
2603 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2604 // I have no idea why this check is necessary, but here it
2606 if arm.attrs.is_empty() {
2607 space(&mut self.s)?;
2609 self.cbox(INDENT_UNIT)?;
2611 self.maybe_print_comment(arm.pats[0].span.lo)?;
2612 self.print_outer_attributes(&arm.attrs)?;
2613 let mut first = true;
2614 for p in &arm.pats {
2618 space(&mut self.s)?;
2619 self.word_space("|")?;
2621 self.print_pat(&p)?;
2623 space(&mut self.s)?;
2624 if let Some(ref e) = arm.guard {
2625 self.word_space("if")?;
2626 self.print_expr(&e)?;
2627 space(&mut self.s)?;
2629 self.word_space("=>")?;
2631 match arm.body.node {
2632 ast::ExprKind::Block(ref blk) => {
2633 // the block will close the pattern's ibox
2634 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2636 // If it is a user-provided unsafe block, print a comma after it
2637 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2638 word(&mut self.s, ",")?;
2642 self.end()?; // close the ibox for the pattern
2643 self.print_expr(&arm.body)?;
2644 word(&mut self.s, ",")?;
2647 self.end() // close enclosing cbox
2650 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2651 match explicit_self.node {
2652 SelfKind::Value(m) => {
2653 self.print_mutability(m)?;
2654 word(&mut self.s, "self")
2656 SelfKind::Region(ref lt, m) => {
2657 word(&mut self.s, "&")?;
2658 self.print_opt_lifetime(lt)?;
2659 self.print_mutability(m)?;
2660 word(&mut self.s, "self")
2662 SelfKind::Explicit(ref typ, m) => {
2663 self.print_mutability(m)?;
2664 word(&mut self.s, "self")?;
2665 self.word_space(":")?;
2666 self.print_type(&typ)
2671 pub fn print_fn(&mut self,
2673 unsafety: ast::Unsafety,
2674 constness: ast::Constness,
2676 name: Option<ast::Ident>,
2677 generics: &ast::Generics,
2678 vis: &ast::Visibility) -> io::Result<()> {
2679 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2681 if let Some(name) = name {
2683 self.print_ident(name)?;
2685 self.print_generics(generics)?;
2686 self.print_fn_args_and_ret(decl)?;
2687 self.print_where_clause(&generics.where_clause)
2690 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2693 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2695 word(&mut self.s, ", ...")?;
2699 self.print_fn_output(decl)
2702 pub fn print_fn_block_args(
2706 word(&mut self.s, "|")?;
2707 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2708 word(&mut self.s, "|")?;
2710 if let ast::FunctionRetTy::Default(..) = decl.output {
2714 self.space_if_not_bol()?;
2715 self.word_space("->")?;
2717 ast::FunctionRetTy::Ty(ref ty) => {
2718 self.print_type(&ty)?;
2719 self.maybe_print_comment(ty.span.lo)
2721 ast::FunctionRetTy::Default(..) => unreachable!(),
2725 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2727 match capture_clause {
2728 ast::CaptureBy::Value => self.word_space("move"),
2729 ast::CaptureBy::Ref => Ok(()),
2733 pub fn print_bounds(&mut self,
2735 bounds: &[ast::TyParamBound])
2737 if !bounds.is_empty() {
2738 word(&mut self.s, prefix)?;
2739 let mut first = true;
2740 for bound in bounds {
2745 self.word_space("+")?;
2749 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2750 self.print_poly_trait_ref(tref)
2752 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2753 word(&mut self.s, "?")?;
2754 self.print_poly_trait_ref(tref)
2756 RegionTyParamBound(ref lt) => {
2757 self.print_lifetime(lt)
2767 pub fn print_lifetime(&mut self,
2768 lifetime: &ast::Lifetime)
2771 self.print_name(lifetime.name)
2774 pub fn print_lifetime_bounds(&mut self,
2775 lifetime: &ast::Lifetime,
2776 bounds: &[ast::Lifetime])
2779 self.print_lifetime(lifetime)?;
2780 if !bounds.is_empty() {
2781 word(&mut self.s, ": ")?;
2782 for (i, bound) in bounds.iter().enumerate() {
2784 word(&mut self.s, " + ")?;
2786 self.print_lifetime(bound)?;
2792 pub fn print_generics(&mut self,
2793 generics: &ast::Generics)
2796 let total = generics.lifetimes.len() + generics.ty_params.len();
2801 word(&mut self.s, "<")?;
2803 let mut ints = Vec::new();
2808 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2809 if idx < generics.lifetimes.len() {
2810 let lifetime_def = &generics.lifetimes[idx];
2811 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2812 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2814 let idx = idx - generics.lifetimes.len();
2815 let param = &generics.ty_params[idx];
2816 s.print_ty_param(param)
2820 word(&mut self.s, ">")?;
2824 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2825 self.print_outer_attributes_inline(¶m.attrs)?;
2826 self.print_ident(param.ident)?;
2827 self.print_bounds(":", ¶m.bounds)?;
2828 match param.default {
2829 Some(ref default) => {
2830 space(&mut self.s)?;
2831 self.word_space("=")?;
2832 self.print_type(&default)
2838 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2840 if where_clause.predicates.is_empty() {
2844 space(&mut self.s)?;
2845 self.word_space("where")?;
2847 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2849 self.word_space(",")?;
2853 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2857 self.print_formal_lifetime_list(bound_lifetimes)?;
2858 self.print_type(&bounded_ty)?;
2859 self.print_bounds(":", bounds)?;
2861 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2864 self.print_lifetime_bounds(lifetime, bounds)?;
2866 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2869 self.print_type(lhs_ty)?;
2870 space(&mut self.s)?;
2871 self.word_space("=")?;
2872 self.print_type(rhs_ty)?;
2880 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2882 ast::ViewPathSimple(ident, ref path) => {
2883 self.print_path(path, false, 0, true)?;
2885 if path.segments.last().unwrap().identifier.name !=
2887 space(&mut self.s)?;
2888 self.word_space("as")?;
2889 self.print_ident(ident)?;
2895 ast::ViewPathGlob(ref path) => {
2896 self.print_path(path, false, 0, true)?;
2897 word(&mut self.s, "::*")
2900 ast::ViewPathList(ref path, ref idents) => {
2901 if path.segments.is_empty() {
2902 word(&mut self.s, "{")?;
2904 self.print_path(path, false, 0, true)?;
2905 word(&mut self.s, "::{")?;
2907 self.commasep(Inconsistent, &idents[..], |s, w| {
2908 s.print_ident(w.node.name)?;
2909 if let Some(ident) = w.node.rename {
2911 s.word_space("as")?;
2912 s.print_ident(ident)?;
2916 word(&mut self.s, "}")
2921 pub fn print_mutability(&mut self,
2922 mutbl: ast::Mutability) -> io::Result<()> {
2924 ast::Mutability::Mutable => self.word_nbsp("mut"),
2925 ast::Mutability::Immutable => Ok(()),
2929 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2930 self.print_mutability(mt.mutbl)?;
2931 self.print_type(&mt.ty)
2934 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2935 self.ibox(INDENT_UNIT)?;
2936 match input.ty.node {
2937 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2939 if let Some(eself) = input.to_self() {
2940 self.print_explicit_self(&eself)?;
2942 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2943 ident.node.name == keywords::Invalid.name()
2948 self.print_pat(&input.pat)?;
2949 word(&mut self.s, ":")?;
2950 space(&mut self.s)?;
2952 self.print_type(&input.ty)?;
2959 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2960 if let ast::FunctionRetTy::Default(..) = decl.output {
2964 self.space_if_not_bol()?;
2965 self.ibox(INDENT_UNIT)?;
2966 self.word_space("->")?;
2968 ast::FunctionRetTy::Default(..) => unreachable!(),
2969 ast::FunctionRetTy::Ty(ref ty) =>
2970 self.print_type(&ty)?
2975 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2980 pub fn print_ty_fn(&mut self,
2982 unsafety: ast::Unsafety,
2984 name: Option<ast::Ident>,
2985 generics: &ast::Generics)
2987 self.ibox(INDENT_UNIT)?;
2988 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2989 word(&mut self.s, "for")?;
2990 self.print_generics(generics)?;
2992 let generics = ast::Generics {
2993 lifetimes: Vec::new(),
2994 ty_params: Vec::new(),
2995 where_clause: ast::WhereClause {
2996 id: ast::DUMMY_NODE_ID,
2997 predicates: Vec::new(),
2999 span: syntax_pos::DUMMY_SP,
3003 ast::Constness::NotConst,
3007 &ast::Visibility::Inherited)?;
3011 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3012 next_pos: Option<BytePos>)
3014 let cm = match self.cm {
3018 if let Some(ref cmnt) = self.next_comment() {
3019 if cmnt.style != comments::Trailing { return Ok(()) }
3020 let span_line = cm.lookup_char_pos(span.hi);
3021 let comment_line = cm.lookup_char_pos(cmnt.pos);
3022 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3023 if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3024 self.print_comment(cmnt)?;
3025 self.cur_cmnt_and_lit.cur_cmnt += 1;
3031 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3032 // If there aren't any remaining comments, then we need to manually
3033 // make sure there is a line break at the end.
3034 if self.next_comment().is_none() {
3035 hardbreak(&mut self.s)?;
3038 match self.next_comment() {
3040 self.print_comment(cmnt)?;
3041 self.cur_cmnt_and_lit.cur_cmnt += 1;
3049 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3050 opt_abi: Option<Abi>)
3053 Some(Abi::Rust) => Ok(()),
3055 self.word_nbsp("extern")?;
3056 self.word_nbsp(&abi.to_string())
3062 pub fn print_extern_opt_abi(&mut self,
3063 opt_abi: Option<Abi>) -> io::Result<()> {
3066 self.word_nbsp("extern")?;
3067 self.word_nbsp(&abi.to_string())
3073 pub fn print_fn_header_info(&mut self,
3074 unsafety: ast::Unsafety,
3075 constness: ast::Constness,
3077 vis: &ast::Visibility) -> io::Result<()> {
3078 word(&mut self.s, &visibility_qualified(vis, ""))?;
3081 ast::Constness::NotConst => {}
3082 ast::Constness::Const => self.word_nbsp("const")?
3085 self.print_unsafety(unsafety)?;
3087 if abi != Abi::Rust {
3088 self.word_nbsp("extern")?;
3089 self.word_nbsp(&abi.to_string())?;
3092 word(&mut self.s, "fn")
3095 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3097 ast::Unsafety::Normal => Ok(()),
3098 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3103 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3114 fn test_fun_to_string() {
3115 let abba_ident = ast::Ident::from_str("abba");
3117 let decl = ast::FnDecl {
3119 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3122 let generics = ast::Generics::default();
3123 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3124 ast::Constness::NotConst,
3125 abba_ident, &generics),
3130 fn test_variant_to_string() {
3131 let ident = ast::Ident::from_str("principal_skinner");
3133 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3136 // making this up as I go.... ?
3137 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3141 let varstr = variant_to_string(&var);
3142 assert_eq!(varstr, "principal_skinner");