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),
296 token::NtVis(ref e) => vis_to_string(&e),
301 pub fn ty_to_string(ty: &ast::Ty) -> String {
302 to_string(|s| s.print_type(ty))
305 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
306 to_string(|s| s.print_bounds("", bounds))
309 pub fn pat_to_string(pat: &ast::Pat) -> String {
310 to_string(|s| s.print_pat(pat))
313 pub fn arm_to_string(arm: &ast::Arm) -> String {
314 to_string(|s| s.print_arm(arm))
317 pub fn expr_to_string(e: &ast::Expr) -> String {
318 to_string(|s| s.print_expr(e))
321 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
322 to_string(|s| s.print_lifetime(e))
325 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
326 to_string(|s| s.print_tt(tt))
329 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
330 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
333 pub fn tokens_to_string(tokens: TokenStream) -> String {
334 to_string(|s| s.print_tts(tokens))
337 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
338 to_string(|s| s.print_stmt(stmt))
341 pub fn attr_to_string(attr: &ast::Attribute) -> String {
342 to_string(|s| s.print_attribute(attr))
345 pub fn item_to_string(i: &ast::Item) -> String {
346 to_string(|s| s.print_item(i))
349 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
350 to_string(|s| s.print_impl_item(i))
353 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
354 to_string(|s| s.print_trait_item(i))
357 pub fn generics_to_string(generics: &ast::Generics) -> String {
358 to_string(|s| s.print_generics(generics))
361 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
362 to_string(|s| s.print_where_clause(i))
365 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
366 to_string(|s| s.print_fn_block_args(p))
369 pub fn path_to_string(p: &ast::Path) -> String {
370 to_string(|s| s.print_path(p, false, 0, false))
373 pub fn ident_to_string(id: ast::Ident) -> String {
374 to_string(|s| s.print_ident(id))
377 pub fn vis_to_string(v: &ast::Visibility) -> String {
378 to_string(|s| s.print_visibility(v))
381 pub fn fun_to_string(decl: &ast::FnDecl,
382 unsafety: ast::Unsafety,
383 constness: ast::Constness,
385 generics: &ast::Generics)
389 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
390 generics, &ast::Visibility::Inherited)?;
391 s.end()?; // Close the head box
392 s.end() // Close the outer box
396 pub fn block_to_string(blk: &ast::Block) -> String {
398 // containing cbox, will be closed by print-block at }
399 s.cbox(INDENT_UNIT)?;
400 // head-ibox, will be closed by print-block after {
406 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
407 to_string(|s| s.print_meta_list_item(li))
410 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
411 to_string(|s| s.print_meta_item(mi))
414 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
415 to_string(|s| s.print_attribute(attr))
418 pub fn lit_to_string(l: &ast::Lit) -> String {
419 to_string(|s| s.print_literal(l))
422 pub fn variant_to_string(var: &ast::Variant) -> String {
423 to_string(|s| s.print_variant(var))
426 pub fn arg_to_string(arg: &ast::Arg) -> String {
427 to_string(|s| s.print_arg(arg, false))
430 pub fn mac_to_string(arg: &ast::Mac) -> String {
431 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
434 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
435 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
438 fn needs_parentheses(expr: &ast::Expr) -> bool {
440 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
441 ast::ExprKind::Closure(..) |
442 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
443 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
448 pub trait PrintState<'a> {
449 fn writer(&mut self) -> &mut pp::Printer<'a>;
450 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
451 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
452 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
453 fn literals(&self) -> &Option<Vec<comments::Literal>>;
455 fn word_space(&mut self, w: &str) -> io::Result<()> {
456 word(self.writer(), w)?;
460 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
462 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
464 fn is_begin(&mut self) -> bool {
465 match self.writer().last_token() {
466 pp::Token::Begin(_) => true,
471 fn is_end(&mut self) -> bool {
472 match self.writer().last_token() {
473 pp::Token::End => true,
478 // is this the beginning of a line?
479 fn is_bol(&mut self) -> bool {
480 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
483 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
485 hardbreak(self.writer())?
491 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
492 self.boxes().push(b);
493 pp::rbox(self.writer(), u, b)
496 fn ibox(&mut self, u: usize) -> io::Result<()> {
497 self.boxes().push(pp::Breaks::Inconsistent);
498 pp::ibox(self.writer(), u)
501 fn end(&mut self) -> io::Result<()> {
502 self.boxes().pop().unwrap();
503 pp::end(self.writer())
506 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
507 where F: FnMut(&mut Self, &T) -> io::Result<()>,
510 let mut first = true;
512 if first { first = false; } else { self.word_space(",")?; }
518 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
519 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
521 let mut result = None;
523 if let &Some(ref lits) = self.literals()
525 while cur_lit < lits.len() {
526 let ltrl = (*lits)[cur_lit].clone();
527 if ltrl.pos > pos { break; }
536 self.cur_cmnt_and_lit().cur_lit = cur_lit;
540 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
541 while let Some(ref cmnt) = self.next_comment() {
543 self.print_comment(cmnt)?;
544 self.cur_cmnt_and_lit().cur_cmnt += 1;
552 fn print_comment(&mut self,
553 cmnt: &comments::Comment) -> io::Result<()> {
556 assert_eq!(cmnt.lines.len(), 1);
557 zerobreak(self.writer())?;
558 word(self.writer(), &cmnt.lines[0])?;
559 zerobreak(self.writer())
561 comments::Isolated => {
562 self.hardbreak_if_not_bol()?;
563 for line in &cmnt.lines {
564 // Don't print empty lines because they will end up as trailing
566 if !line.is_empty() {
567 word(self.writer(), &line[..])?;
569 hardbreak(self.writer())?;
573 comments::Trailing => {
575 word(self.writer(), " ")?;
577 if cmnt.lines.len() == 1 {
578 word(self.writer(), &cmnt.lines[0])?;
579 hardbreak(self.writer())
582 for line in &cmnt.lines {
583 if !line.is_empty() {
584 word(self.writer(), &line[..])?;
586 hardbreak(self.writer())?;
591 comments::BlankLine => {
592 // We need to do at least one, possibly two hardbreaks.
593 let is_semi = match self.writer().last_token() {
594 pp::Token::String(s, _) => ";" == s,
597 if is_semi || self.is_begin() || self.is_end() {
598 hardbreak(self.writer())?;
600 hardbreak(self.writer())
605 fn next_comment(&mut self) -> Option<comments::Comment> {
606 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
607 match *self.comments() {
609 if cur_cmnt < cmnts.len() {
610 Some(cmnts[cur_cmnt].clone())
619 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
620 self.maybe_print_comment(lit.span.lo)?;
621 match self.next_lit(lit.span.lo) {
623 return word(self.writer(), &(*ltrl).lit);
628 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
629 ast::LitKind::Byte(byte) => {
630 let mut res = String::from("b'");
631 res.extend(ascii::escape_default(byte).map(|c| c as char));
633 word(self.writer(), &res[..])
635 ast::LitKind::Char(ch) => {
636 let mut res = String::from("'");
637 res.extend(ch.escape_default());
639 word(self.writer(), &res[..])
641 ast::LitKind::Int(i, t) => {
643 ast::LitIntType::Signed(st) => {
644 word(self.writer(), &st.val_to_string(i as i128))
646 ast::LitIntType::Unsigned(ut) => {
647 word(self.writer(), &ut.val_to_string(i))
649 ast::LitIntType::Unsuffixed => {
650 word(self.writer(), &format!("{}", i))
654 ast::LitKind::Float(ref f, t) => {
661 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()),
662 ast::LitKind::Bool(val) => {
663 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
665 ast::LitKind::ByteStr(ref v) => {
666 let mut escaped: String = String::new();
667 for &ch in v.iter() {
668 escaped.extend(ascii::escape_default(ch)
669 .map(|c| c as char));
671 word(self.writer(), &format!("b\"{}\"", escaped))
676 fn print_string(&mut self, st: &str,
677 style: ast::StrStyle) -> io::Result<()> {
678 let st = match style {
679 ast::StrStyle::Cooked => {
680 (format!("\"{}\"", st.escape_default()))
682 ast::StrStyle::Raw(n) => {
683 (format!("r{delim}\"{string}\"{delim}",
684 delim=repeat("#", n),
688 word(self.writer(), &st[..])
691 fn print_inner_attributes(&mut self,
692 attrs: &[ast::Attribute]) -> io::Result<()> {
693 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
696 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
697 attrs: &[ast::Attribute])
699 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
702 fn print_outer_attributes(&mut self,
703 attrs: &[ast::Attribute]) -> io::Result<()> {
704 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
707 fn print_inner_attributes_inline(&mut self,
708 attrs: &[ast::Attribute]) -> io::Result<()> {
709 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
712 fn print_outer_attributes_inline(&mut self,
713 attrs: &[ast::Attribute]) -> io::Result<()> {
714 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
717 fn print_either_attributes(&mut self,
718 attrs: &[ast::Attribute],
719 kind: ast::AttrStyle,
721 trailing_hardbreak: bool) -> io::Result<()> {
724 if attr.style == kind {
725 self.print_attribute_inline(attr, is_inline)?;
732 if count > 0 && trailing_hardbreak && !is_inline {
733 self.hardbreak_if_not_bol()?;
738 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
739 self.print_attribute_inline(attr, false)
742 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
743 is_inline: bool) -> io::Result<()> {
745 self.hardbreak_if_not_bol()?;
747 self.maybe_print_comment(attr.span.lo)?;
748 if attr.is_sugared_doc {
749 word(self.writer(), &attr.value_str().unwrap().as_str())?;
750 hardbreak(self.writer())
753 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
754 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
756 if let Some(mi) = attr.meta() {
757 self.print_meta_item(&mi)?
759 for (i, segment) in attr.path.segments.iter().enumerate() {
761 word(self.writer(), "::")?
763 if segment.identifier.name != keywords::CrateRoot.name() &&
764 segment.identifier.name != "$crate" {
765 word(self.writer(), &segment.identifier.name.as_str())?;
768 space(self.writer())?;
769 self.print_tts(attr.tokens.clone())?;
771 word(self.writer(), "]")
775 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
777 ast::NestedMetaItemKind::MetaItem(ref mi) => {
778 self.print_meta_item(mi)
780 ast::NestedMetaItemKind::Literal(ref lit) => {
781 self.print_literal(lit)
786 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
787 self.ibox(INDENT_UNIT)?;
789 ast::MetaItemKind::Word => {
790 word(self.writer(), &item.name.as_str())?;
792 ast::MetaItemKind::NameValue(ref value) => {
793 self.word_space(&item.name.as_str())?;
794 self.word_space("=")?;
795 self.print_literal(value)?;
797 ast::MetaItemKind::List(ref items) => {
798 word(self.writer(), &item.name.as_str())?;
800 self.commasep(Consistent,
802 |s, i| s.print_meta_list_item(&i))?;
809 /// This doesn't deserve to be called "pretty" printing, but it should be
810 /// meaning-preserving. A quick hack that might help would be to look at the
811 /// spans embedded in the TTs to decide where to put spaces and newlines.
812 /// But it'd be better to parse these according to the grammar of the
813 /// appropriate macro, transcribe back into the grammar we just parsed from,
814 /// and then pretty-print the resulting AST nodes (so, e.g., we print
815 /// expression arguments as expressions). It can be done! I think.
816 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
818 TokenTree::Token(_, ref tk) => {
819 word(self.writer(), &token_to_string(tk))?;
821 parse::token::DocComment(..) => {
822 hardbreak(self.writer())
827 TokenTree::Delimited(_, ref delimed) => {
828 word(self.writer(), &token_to_string(&delimed.open_token()))?;
829 space(self.writer())?;
830 self.print_tts(delimed.stream())?;
831 space(self.writer())?;
832 word(self.writer(), &token_to_string(&delimed.close_token()))
837 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
839 for (i, tt) in tts.into_trees().enumerate() {
841 space(self.writer())?;
848 fn space_if_not_bol(&mut self) -> io::Result<()> {
849 if !self.is_bol() { space(self.writer())?; }
853 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
856 impl<'a> PrintState<'a> for State<'a> {
857 fn writer(&mut self) -> &mut pp::Printer<'a> {
861 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
865 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
869 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
870 &mut self.cur_cmnt_and_lit
873 fn literals(&self) -> &Option<Vec<comments::Literal>> {
879 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
880 self.boxes.push(pp::Breaks::Consistent);
881 pp::cbox(&mut self.s, u)
884 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
885 word(&mut self.s, w)?;
889 pub fn head(&mut self, w: &str) -> io::Result<()> {
890 // outer-box is consistent
891 self.cbox(INDENT_UNIT)?;
892 // head-box is inconsistent
893 self.ibox(w.len() + 1)?;
894 // keyword that starts the head
901 pub fn bopen(&mut self) -> io::Result<()> {
902 word(&mut self.s, "{")?;
903 self.end() // close the head-box
906 pub fn bclose_(&mut self, span: syntax_pos::Span,
907 indented: usize) -> io::Result<()> {
908 self.bclose_maybe_open(span, indented, true)
910 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
911 indented: usize, close_box: bool) -> io::Result<()> {
912 self.maybe_print_comment(span.hi)?;
913 self.break_offset_if_not_bol(1, -(indented as isize))?;
914 word(&mut self.s, "}")?;
916 self.end()?; // close the outer-box
920 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
921 self.bclose_(span, INDENT_UNIT)
924 pub fn in_cbox(&self) -> bool {
925 match self.boxes.last() {
926 Some(&last_box) => last_box == pp::Breaks::Consistent,
931 pub fn break_offset_if_not_bol(&mut self, n: usize,
932 off: isize) -> io::Result<()> {
934 break_offset(&mut self.s, n, off)
936 if off != 0 && self.s.last_token().is_hardbreak_tok() {
937 // We do something pretty sketchy here: tuck the nonzero
938 // offset-adjustment we were going to deposit along with the
939 // break into the previous hardbreak.
940 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
946 // Synthesizes a comment that was not textually present in the original source
948 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
949 word(&mut self.s, "/*")?;
951 word(&mut self.s, &text[..])?;
953 word(&mut self.s, "*/")
958 pub fn commasep_cmnt<T, F, G>(&mut self,
962 mut get_span: G) -> io::Result<()> where
963 F: FnMut(&mut State, &T) -> io::Result<()>,
964 G: FnMut(&T) -> syntax_pos::Span,
967 let len = elts.len();
970 self.maybe_print_comment(get_span(elt).hi)?;
974 word(&mut self.s, ",")?;
975 self.maybe_print_trailing_comment(get_span(elt),
976 Some(get_span(&elts[i]).hi))?;
977 self.space_if_not_bol()?;
983 pub fn commasep_exprs(&mut self, b: Breaks,
984 exprs: &[P<ast::Expr>]) -> io::Result<()> {
985 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
988 pub fn print_mod(&mut self, _mod: &ast::Mod,
989 attrs: &[ast::Attribute]) -> io::Result<()> {
990 self.print_inner_attributes(attrs)?;
991 for item in &_mod.items {
992 self.print_item(&item)?;
997 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
998 attrs: &[ast::Attribute]) -> io::Result<()> {
999 self.print_inner_attributes(attrs)?;
1000 for item in &nmod.items {
1001 self.print_foreign_item(item)?;
1006 pub fn print_opt_lifetime(&mut self,
1007 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1008 if let Some(l) = *lifetime {
1009 self.print_lifetime(&l)?;
1015 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1016 self.maybe_print_comment(ty.span.lo)?;
1019 ast::TyKind::Slice(ref ty) => {
1020 word(&mut self.s, "[")?;
1021 self.print_type(&ty)?;
1022 word(&mut self.s, "]")?;
1024 ast::TyKind::Ptr(ref mt) => {
1025 word(&mut self.s, "*")?;
1027 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1028 ast::Mutability::Immutable => self.word_nbsp("const")?,
1030 self.print_type(&mt.ty)?;
1032 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1033 word(&mut self.s, "&")?;
1034 self.print_opt_lifetime(lifetime)?;
1037 ast::TyKind::Never => {
1038 word(&mut self.s, "!")?;
1040 ast::TyKind::Tup(ref elts) => {
1042 self.commasep(Inconsistent, &elts[..],
1043 |s, ty| s.print_type(&ty))?;
1044 if elts.len() == 1 {
1045 word(&mut self.s, ",")?;
1049 ast::TyKind::Paren(ref typ) => {
1051 self.print_type(&typ)?;
1054 ast::TyKind::BareFn(ref f) => {
1055 let generics = ast::Generics {
1056 lifetimes: f.lifetimes.clone(),
1057 ty_params: Vec::new(),
1058 where_clause: ast::WhereClause {
1059 id: ast::DUMMY_NODE_ID,
1060 predicates: Vec::new(),
1062 span: syntax_pos::DUMMY_SP,
1064 self.print_ty_fn(f.abi,
1070 ast::TyKind::Path(None, ref path) => {
1071 self.print_path(path, false, 0, false)?;
1073 ast::TyKind::Path(Some(ref qself), ref path) => {
1074 self.print_qpath(path, qself, false)?
1076 ast::TyKind::TraitObject(ref bounds) => {
1077 self.print_bounds("", &bounds[..])?;
1079 ast::TyKind::ImplTrait(ref bounds) => {
1080 self.print_bounds("impl ", &bounds[..])?;
1082 ast::TyKind::Array(ref ty, ref v) => {
1083 word(&mut self.s, "[")?;
1084 self.print_type(&ty)?;
1085 word(&mut self.s, "; ")?;
1086 self.print_expr(&v)?;
1087 word(&mut self.s, "]")?;
1089 ast::TyKind::Typeof(ref e) => {
1090 word(&mut self.s, "typeof(")?;
1091 self.print_expr(&e)?;
1092 word(&mut self.s, ")")?;
1094 ast::TyKind::Infer => {
1095 word(&mut self.s, "_")?;
1097 ast::TyKind::Err => {
1098 word(&mut self.s, "?")?;
1100 ast::TyKind::ImplicitSelf => {
1101 word(&mut self.s, "Self")?;
1103 ast::TyKind::Mac(ref m) => {
1104 self.print_mac(m, token::Paren)?;
1110 pub fn print_foreign_item(&mut self,
1111 item: &ast::ForeignItem) -> io::Result<()> {
1112 self.hardbreak_if_not_bol()?;
1113 self.maybe_print_comment(item.span.lo)?;
1114 self.print_outer_attributes(&item.attrs)?;
1116 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1118 self.print_fn(decl, ast::Unsafety::Normal,
1119 ast::Constness::NotConst,
1120 Abi::Rust, Some(item.ident),
1121 generics, &item.vis)?;
1122 self.end()?; // end head-ibox
1123 word(&mut self.s, ";")?;
1124 self.end() // end the outer fn box
1126 ast::ForeignItemKind::Static(ref t, m) => {
1127 self.head(&visibility_qualified(&item.vis, "static"))?;
1129 self.word_space("mut")?;
1131 self.print_ident(item.ident)?;
1132 self.word_space(":")?;
1133 self.print_type(&t)?;
1134 word(&mut self.s, ";")?;
1135 self.end()?; // end the head-ibox
1136 self.end() // end the outer cbox
1141 fn print_associated_const(&mut self,
1144 default: Option<&ast::Expr>,
1145 vis: &ast::Visibility)
1148 word(&mut self.s, &visibility_qualified(vis, ""))?;
1149 self.word_space("const")?;
1150 self.print_ident(ident)?;
1151 self.word_space(":")?;
1152 self.print_type(ty)?;
1153 if let Some(expr) = default {
1154 space(&mut self.s)?;
1155 self.word_space("=")?;
1156 self.print_expr(expr)?;
1158 word(&mut self.s, ";")
1161 fn print_associated_type(&mut self,
1163 bounds: Option<&ast::TyParamBounds>,
1164 ty: Option<&ast::Ty>)
1166 self.word_space("type")?;
1167 self.print_ident(ident)?;
1168 if let Some(bounds) = bounds {
1169 self.print_bounds(":", bounds)?;
1171 if let Some(ty) = ty {
1172 space(&mut self.s)?;
1173 self.word_space("=")?;
1174 self.print_type(ty)?;
1176 word(&mut self.s, ";")
1179 /// Pretty-print an item
1180 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1181 self.hardbreak_if_not_bol()?;
1182 self.maybe_print_comment(item.span.lo)?;
1183 self.print_outer_attributes(&item.attrs)?;
1184 self.ann.pre(self, NodeItem(item))?;
1186 ast::ItemKind::ExternCrate(ref optional_path) => {
1187 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1188 if let Some(p) = *optional_path {
1189 let val = p.as_str();
1190 if val.contains("-") {
1191 self.print_string(&val, ast::StrStyle::Cooked)?;
1193 self.print_name(p)?;
1195 space(&mut self.s)?;
1196 word(&mut self.s, "as")?;
1197 space(&mut self.s)?;
1199 self.print_ident(item.ident)?;
1200 word(&mut self.s, ";")?;
1201 self.end()?; // end inner head-block
1202 self.end()?; // end outer head-block
1204 ast::ItemKind::Use(ref vp) => {
1205 self.head(&visibility_qualified(&item.vis, "use"))?;
1206 self.print_view_path(&vp)?;
1207 word(&mut self.s, ";")?;
1208 self.end()?; // end inner head-block
1209 self.end()?; // end outer head-block
1211 ast::ItemKind::Static(ref ty, m, ref expr) => {
1212 self.head(&visibility_qualified(&item.vis, "static"))?;
1213 if m == ast::Mutability::Mutable {
1214 self.word_space("mut")?;
1216 self.print_ident(item.ident)?;
1217 self.word_space(":")?;
1218 self.print_type(&ty)?;
1219 space(&mut self.s)?;
1220 self.end()?; // end the head-ibox
1222 self.word_space("=")?;
1223 self.print_expr(&expr)?;
1224 word(&mut self.s, ";")?;
1225 self.end()?; // end the outer cbox
1227 ast::ItemKind::Const(ref ty, ref expr) => {
1228 self.head(&visibility_qualified(&item.vis, "const"))?;
1229 self.print_ident(item.ident)?;
1230 self.word_space(":")?;
1231 self.print_type(&ty)?;
1232 space(&mut self.s)?;
1233 self.end()?; // end the head-ibox
1235 self.word_space("=")?;
1236 self.print_expr(&expr)?;
1237 word(&mut self.s, ";")?;
1238 self.end()?; // end the outer cbox
1240 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1251 word(&mut self.s, " ")?;
1252 self.print_block_with_attrs(&body, &item.attrs)?;
1254 ast::ItemKind::Mod(ref _mod) => {
1255 self.head(&visibility_qualified(&item.vis, "mod"))?;
1256 self.print_ident(item.ident)?;
1259 self.print_mod(_mod, &item.attrs)?;
1260 self.bclose(item.span)?;
1262 ast::ItemKind::ForeignMod(ref nmod) => {
1263 self.head("extern")?;
1264 self.word_nbsp(&nmod.abi.to_string())?;
1266 self.print_foreign_mod(nmod, &item.attrs)?;
1267 self.bclose(item.span)?;
1269 ast::ItemKind::GlobalAsm(ref ga) => {
1270 self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
1271 word(&mut self.s, &ga.asm.as_str())?;
1274 ast::ItemKind::Ty(ref ty, ref params) => {
1275 self.ibox(INDENT_UNIT)?;
1277 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1278 self.print_ident(item.ident)?;
1279 self.print_generics(params)?;
1280 self.end()?; // end the inner ibox
1282 self.print_where_clause(¶ms.where_clause)?;
1283 space(&mut self.s)?;
1284 self.word_space("=")?;
1285 self.print_type(&ty)?;
1286 word(&mut self.s, ";")?;
1287 self.end()?; // end the outer ibox
1289 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1290 self.print_enum_def(
1298 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1299 self.head(&visibility_qualified(&item.vis, "struct"))?;
1300 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1302 ast::ItemKind::Union(ref struct_def, ref generics) => {
1303 self.head(&visibility_qualified(&item.vis, "union"))?;
1304 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1306 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1308 self.print_visibility(&item.vis)?;
1309 self.print_unsafety(unsafety)?;
1310 self.word_nbsp("impl")?;
1311 self.print_trait_ref(trait_ref)?;
1312 space(&mut self.s)?;
1313 self.word_space("for")?;
1314 self.word_space("..")?;
1316 self.bclose(item.span)?;
1318 ast::ItemKind::Impl(unsafety,
1324 ref impl_items) => {
1326 self.print_visibility(&item.vis)?;
1327 self.print_defaultness(defaultness)?;
1328 self.print_unsafety(unsafety)?;
1329 self.word_nbsp("impl")?;
1331 if generics.is_parameterized() {
1332 self.print_generics(generics)?;
1333 space(&mut self.s)?;
1337 ast::ImplPolarity::Negative => {
1338 word(&mut self.s, "!")?;
1343 if let Some(ref t) = *opt_trait {
1344 self.print_trait_ref(t)?;
1345 space(&mut self.s)?;
1346 self.word_space("for")?;
1349 self.print_type(&ty)?;
1350 self.print_where_clause(&generics.where_clause)?;
1352 space(&mut self.s)?;
1354 self.print_inner_attributes(&item.attrs)?;
1355 for impl_item in impl_items {
1356 self.print_impl_item(impl_item)?;
1358 self.bclose(item.span)?;
1360 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1362 self.print_visibility(&item.vis)?;
1363 self.print_unsafety(unsafety)?;
1364 self.word_nbsp("trait")?;
1365 self.print_ident(item.ident)?;
1366 self.print_generics(generics)?;
1367 let mut real_bounds = Vec::with_capacity(bounds.len());
1368 for b in bounds.iter() {
1369 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1370 space(&mut self.s)?;
1371 self.word_space("for ?")?;
1372 self.print_trait_ref(&ptr.trait_ref)?;
1374 real_bounds.push(b.clone());
1377 self.print_bounds(":", &real_bounds[..])?;
1378 self.print_where_clause(&generics.where_clause)?;
1379 word(&mut self.s, " ")?;
1381 for trait_item in trait_items {
1382 self.print_trait_item(trait_item)?;
1384 self.bclose(item.span)?;
1386 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1387 self.print_path(&node.path, false, 0, false)?;
1388 word(&mut self.s, "! ")?;
1389 self.print_ident(item.ident)?;
1390 self.cbox(INDENT_UNIT)?;
1392 self.print_tts(node.stream())?;
1394 word(&mut self.s, ";")?;
1397 ast::ItemKind::MacroDef(ref tts) => {
1398 word(&mut self.s, "macro_rules! ")?;
1399 self.print_ident(item.ident)?;
1400 self.cbox(INDENT_UNIT)?;
1402 self.print_tts(tts.clone().into())?;
1404 word(&mut self.s, ";")?;
1408 self.ann.post(self, NodeItem(item))
1411 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1412 self.print_path(&t.path, false, 0, false)
1415 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1416 if !lifetimes.is_empty() {
1417 word(&mut self.s, "for<")?;
1418 let mut comma = false;
1419 for lifetime_def in lifetimes {
1421 self.word_space(",")?
1423 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1424 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1427 word(&mut self.s, ">")?;
1432 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1433 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1434 self.print_trait_ref(&t.trait_ref)
1437 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1438 generics: &ast::Generics, ident: ast::Ident,
1439 span: syntax_pos::Span,
1440 visibility: &ast::Visibility) -> io::Result<()> {
1441 self.head(&visibility_qualified(visibility, "enum"))?;
1442 self.print_ident(ident)?;
1443 self.print_generics(generics)?;
1444 self.print_where_clause(&generics.where_clause)?;
1445 space(&mut self.s)?;
1446 self.print_variants(&enum_definition.variants, span)
1449 pub fn print_variants(&mut self,
1450 variants: &[ast::Variant],
1451 span: syntax_pos::Span) -> io::Result<()> {
1454 self.space_if_not_bol()?;
1455 self.maybe_print_comment(v.span.lo)?;
1456 self.print_outer_attributes(&v.node.attrs)?;
1457 self.ibox(INDENT_UNIT)?;
1458 self.print_variant(v)?;
1459 word(&mut self.s, ",")?;
1461 self.maybe_print_trailing_comment(v.span, None)?;
1466 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1468 ast::Visibility::Public => self.word_nbsp("pub"),
1469 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1470 ast::Visibility::Restricted { ref path, .. } => {
1471 let path = to_string(|s| s.print_path(path, false, 0, true));
1472 if path == "self" || path == "super" {
1473 self.word_nbsp(&format!("pub({})", path))
1475 self.word_nbsp(&format!("pub(in {})", path))
1478 ast::Visibility::Inherited => Ok(())
1482 pub fn print_defaultness(&mut self, defatulness: ast::Defaultness) -> io::Result<()> {
1483 if let ast::Defaultness::Default = defatulness {
1484 try!(self.word_nbsp("default"));
1489 pub fn print_struct(&mut self,
1490 struct_def: &ast::VariantData,
1491 generics: &ast::Generics,
1493 span: syntax_pos::Span,
1494 print_finalizer: bool) -> io::Result<()> {
1495 self.print_ident(ident)?;
1496 self.print_generics(generics)?;
1497 if !struct_def.is_struct() {
1498 if struct_def.is_tuple() {
1501 Inconsistent, struct_def.fields(),
1503 s.maybe_print_comment(field.span.lo)?;
1504 s.print_outer_attributes(&field.attrs)?;
1505 s.print_visibility(&field.vis)?;
1506 s.print_type(&field.ty)
1511 self.print_where_clause(&generics.where_clause)?;
1512 if print_finalizer {
1513 word(&mut self.s, ";")?;
1516 self.end() // close the outer-box
1518 self.print_where_clause(&generics.where_clause)?;
1521 self.hardbreak_if_not_bol()?;
1523 for field in struct_def.fields() {
1524 self.hardbreak_if_not_bol()?;
1525 self.maybe_print_comment(field.span.lo)?;
1526 self.print_outer_attributes(&field.attrs)?;
1527 self.print_visibility(&field.vis)?;
1528 self.print_ident(field.ident.unwrap())?;
1529 self.word_nbsp(":")?;
1530 self.print_type(&field.ty)?;
1531 word(&mut self.s, ",")?;
1538 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1540 let generics = ast::Generics::default();
1541 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1542 match v.node.disr_expr {
1544 space(&mut self.s)?;
1545 self.word_space("=")?;
1552 pub fn print_method_sig(&mut self,
1555 vis: &ast::Visibility)
1557 self.print_fn(&m.decl,
1566 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1568 self.ann.pre(self, NodeSubItem(ti.id))?;
1569 self.hardbreak_if_not_bol()?;
1570 self.maybe_print_comment(ti.span.lo)?;
1571 self.print_outer_attributes(&ti.attrs)?;
1573 ast::TraitItemKind::Const(ref ty, ref default) => {
1574 self.print_associated_const(ti.ident, &ty,
1575 default.as_ref().map(|expr| &**expr),
1576 &ast::Visibility::Inherited)?;
1578 ast::TraitItemKind::Method(ref sig, ref body) => {
1582 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1583 if let Some(ref body) = *body {
1585 self.print_block_with_attrs(body, &ti.attrs)?;
1587 word(&mut self.s, ";")?;
1590 ast::TraitItemKind::Type(ref bounds, ref default) => {
1591 self.print_associated_type(ti.ident, Some(bounds),
1592 default.as_ref().map(|ty| &**ty))?;
1594 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1595 // code copied from ItemKind::Mac:
1596 self.print_path(&node.path, false, 0, false)?;
1597 word(&mut self.s, "! ")?;
1598 self.cbox(INDENT_UNIT)?;
1600 self.print_tts(node.stream())?;
1602 word(&mut self.s, ";")?;
1606 self.ann.post(self, NodeSubItem(ti.id))
1609 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1610 self.ann.pre(self, NodeSubItem(ii.id))?;
1611 self.hardbreak_if_not_bol()?;
1612 self.maybe_print_comment(ii.span.lo)?;
1613 self.print_outer_attributes(&ii.attrs)?;
1614 self.print_defaultness(ii.defaultness)?;
1616 ast::ImplItemKind::Const(ref ty, ref expr) => {
1617 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1619 ast::ImplItemKind::Method(ref sig, ref body) => {
1621 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1623 self.print_block_with_attrs(body, &ii.attrs)?;
1625 ast::ImplItemKind::Type(ref ty) => {
1626 self.print_associated_type(ii.ident, None, Some(ty))?;
1628 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1629 // code copied from ItemKind::Mac:
1630 self.print_path(&node.path, false, 0, false)?;
1631 word(&mut self.s, "! ")?;
1632 self.cbox(INDENT_UNIT)?;
1634 self.print_tts(node.stream())?;
1636 word(&mut self.s, ";")?;
1640 self.ann.post(self, NodeSubItem(ii.id))
1643 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1644 self.maybe_print_comment(st.span.lo)?;
1646 ast::StmtKind::Local(ref loc) => {
1647 self.print_outer_attributes(&loc.attrs)?;
1648 self.space_if_not_bol()?;
1649 self.ibox(INDENT_UNIT)?;
1650 self.word_nbsp("let")?;
1652 self.ibox(INDENT_UNIT)?;
1653 self.print_local_decl(&loc)?;
1655 if let Some(ref init) = loc.init {
1657 self.word_space("=")?;
1658 self.print_expr(&init)?;
1660 word(&mut self.s, ";")?;
1663 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1664 ast::StmtKind::Expr(ref expr) => {
1665 self.space_if_not_bol()?;
1666 self.print_expr_outer_attr_style(&expr, false)?;
1667 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1668 word(&mut self.s, ";")?;
1671 ast::StmtKind::Semi(ref expr) => {
1672 self.space_if_not_bol()?;
1673 self.print_expr_outer_attr_style(&expr, false)?;
1674 word(&mut self.s, ";")?;
1676 ast::StmtKind::Mac(ref mac) => {
1677 let (ref mac, style, ref attrs) = **mac;
1678 self.space_if_not_bol()?;
1679 self.print_outer_attributes(&attrs)?;
1680 let delim = match style {
1681 ast::MacStmtStyle::Braces => token::Brace,
1684 self.print_mac(&mac, delim)?;
1685 if style == ast::MacStmtStyle::Semicolon {
1686 word(&mut self.s, ";")?;
1690 self.maybe_print_trailing_comment(st.span, None)
1693 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1694 self.print_block_with_attrs(blk, &[])
1697 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1698 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1701 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1702 attrs: &[ast::Attribute])
1704 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1707 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1708 indented: usize) -> io::Result<()> {
1709 self.print_block_maybe_unclosed(blk, indented, &[], false)
1712 pub fn print_block_with_attrs(&mut self,
1714 attrs: &[ast::Attribute]) -> io::Result<()> {
1715 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1718 pub fn print_block_maybe_unclosed(&mut self,
1721 attrs: &[ast::Attribute],
1722 close_box: bool) -> io::Result<()> {
1724 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1725 BlockCheckMode::Default => ()
1727 self.maybe_print_comment(blk.span.lo)?;
1728 self.ann.pre(self, NodeBlock(blk))?;
1731 self.print_inner_attributes(attrs)?;
1733 for (i, st) in blk.stmts.iter().enumerate() {
1735 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1736 self.maybe_print_comment(st.span.lo)?;
1737 self.space_if_not_bol()?;
1738 self.print_expr_outer_attr_style(&expr, false)?;
1739 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1741 _ => self.print_stmt(st)?,
1745 self.bclose_maybe_open(blk.span, indented, close_box)?;
1746 self.ann.post(self, NodeBlock(blk))
1749 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1753 // "another else-if"
1754 ast::ExprKind::If(ref i, ref then, ref e) => {
1755 self.cbox(INDENT_UNIT - 1)?;
1757 word(&mut self.s, " else if ")?;
1758 self.print_expr(&i)?;
1759 space(&mut self.s)?;
1760 self.print_block(&then)?;
1761 self.print_else(e.as_ref().map(|e| &**e))
1763 // "another else-if-let"
1764 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1765 self.cbox(INDENT_UNIT - 1)?;
1767 word(&mut self.s, " else if let ")?;
1768 self.print_pat(&pat)?;
1769 space(&mut self.s)?;
1770 self.word_space("=")?;
1771 self.print_expr(&expr)?;
1772 space(&mut self.s)?;
1773 self.print_block(&then)?;
1774 self.print_else(e.as_ref().map(|e| &**e))
1777 ast::ExprKind::Block(ref b) => {
1778 self.cbox(INDENT_UNIT - 1)?;
1780 word(&mut self.s, " else ")?;
1781 self.print_block(&b)
1783 // BLEAH, constraints would be great here
1785 panic!("print_if saw if with weird alternative");
1793 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1794 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1796 self.print_expr(test)?;
1797 space(&mut self.s)?;
1798 self.print_block(blk)?;
1799 self.print_else(elseopt)
1802 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1803 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1804 self.head("if let")?;
1805 self.print_pat(pat)?;
1806 space(&mut self.s)?;
1807 self.word_space("=")?;
1808 self.print_expr(expr)?;
1809 space(&mut self.s)?;
1810 self.print_block(blk)?;
1811 self.print_else(elseopt)
1814 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1816 self.print_path(&m.node.path, false, 0, false)?;
1817 word(&mut self.s, "!")?;
1819 token::Paren => self.popen()?,
1820 token::Bracket => word(&mut self.s, "[")?,
1825 token::NoDelim => {}
1827 self.print_tts(m.node.stream())?;
1829 token::Paren => self.pclose(),
1830 token::Bracket => word(&mut self.s, "]"),
1831 token::Brace => self.bclose(m.span),
1832 token::NoDelim => Ok(()),
1837 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1839 self.commasep_exprs(Inconsistent, args)?;
1843 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1844 binop: ast::BinOp) -> bool {
1845 match sub_expr.node {
1846 ast::ExprKind::Binary(ref sub_op, _, _) => {
1847 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1848 AssocOp::from_ast_binop(binop.node).precedence() {
1858 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1859 let needs_par = needs_parentheses(expr);
1863 self.print_expr(expr)?;
1870 fn print_expr_in_place(&mut self,
1872 expr: &ast::Expr) -> io::Result<()> {
1873 self.print_expr_maybe_paren(place)?;
1874 space(&mut self.s)?;
1875 self.word_space("<-")?;
1876 self.print_expr_maybe_paren(expr)
1879 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1880 attrs: &[Attribute]) -> io::Result<()> {
1881 self.ibox(INDENT_UNIT)?;
1882 word(&mut self.s, "[")?;
1883 self.print_inner_attributes_inline(attrs)?;
1884 self.commasep_exprs(Inconsistent, &exprs[..])?;
1885 word(&mut self.s, "]")?;
1889 fn print_expr_repeat(&mut self,
1890 element: &ast::Expr,
1892 attrs: &[Attribute]) -> io::Result<()> {
1893 self.ibox(INDENT_UNIT)?;
1894 word(&mut self.s, "[")?;
1895 self.print_inner_attributes_inline(attrs)?;
1896 self.print_expr(element)?;
1897 self.word_space(";")?;
1898 self.print_expr(count)?;
1899 word(&mut self.s, "]")?;
1903 fn print_expr_struct(&mut self,
1905 fields: &[ast::Field],
1906 wth: &Option<P<ast::Expr>>,
1907 attrs: &[Attribute]) -> io::Result<()> {
1908 self.print_path(path, true, 0, false)?;
1909 word(&mut self.s, "{")?;
1910 self.print_inner_attributes_inline(attrs)?;
1915 s.ibox(INDENT_UNIT)?;
1916 if !field.is_shorthand {
1917 s.print_ident(field.ident.node)?;
1920 s.print_expr(&field.expr)?;
1926 self.ibox(INDENT_UNIT)?;
1927 if !fields.is_empty() {
1928 word(&mut self.s, ",")?;
1929 space(&mut self.s)?;
1931 word(&mut self.s, "..")?;
1932 self.print_expr(&expr)?;
1935 _ => if !fields.is_empty() {
1936 word(&mut self.s, ",")?
1939 word(&mut self.s, "}")?;
1943 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1944 attrs: &[Attribute]) -> io::Result<()> {
1946 self.print_inner_attributes_inline(attrs)?;
1947 self.commasep_exprs(Inconsistent, &exprs[..])?;
1948 if exprs.len() == 1 {
1949 word(&mut self.s, ",")?;
1954 fn print_expr_call(&mut self,
1956 args: &[P<ast::Expr>]) -> io::Result<()> {
1957 self.print_expr_maybe_paren(func)?;
1958 self.print_call_post(args)
1961 fn print_expr_method_call(&mut self,
1962 ident: ast::SpannedIdent,
1964 args: &[P<ast::Expr>]) -> io::Result<()> {
1965 let base_args = &args[1..];
1966 self.print_expr(&args[0])?;
1967 word(&mut self.s, ".")?;
1968 self.print_ident(ident.node)?;
1969 if !tys.is_empty() {
1970 word(&mut self.s, "::<")?;
1971 self.commasep(Inconsistent, tys,
1972 |s, ty| s.print_type(&ty))?;
1973 word(&mut self.s, ">")?;
1975 self.print_call_post(base_args)
1978 fn print_expr_binary(&mut self,
1981 rhs: &ast::Expr) -> io::Result<()> {
1982 if self.check_expr_bin_needs_paren(lhs, op) {
1983 self.print_expr_maybe_paren(lhs)?;
1985 self.print_expr(lhs)?;
1987 space(&mut self.s)?;
1988 self.word_space(op.node.to_string())?;
1989 if self.check_expr_bin_needs_paren(rhs, op) {
1990 self.print_expr_maybe_paren(rhs)
1992 self.print_expr(rhs)
1996 fn print_expr_unary(&mut self,
1998 expr: &ast::Expr) -> io::Result<()> {
1999 word(&mut self.s, ast::UnOp::to_string(op))?;
2000 self.print_expr_maybe_paren(expr)
2003 fn print_expr_addr_of(&mut self,
2004 mutability: ast::Mutability,
2005 expr: &ast::Expr) -> io::Result<()> {
2006 word(&mut self.s, "&")?;
2007 self.print_mutability(mutability)?;
2008 self.print_expr_maybe_paren(expr)
2011 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2012 self.print_expr_outer_attr_style(expr, true)
2015 fn print_expr_outer_attr_style(&mut self,
2017 is_inline: bool) -> io::Result<()> {
2018 self.maybe_print_comment(expr.span.lo)?;
2020 let attrs = &expr.attrs;
2022 self.print_outer_attributes_inline(attrs)?;
2024 self.print_outer_attributes(attrs)?;
2027 self.ibox(INDENT_UNIT)?;
2028 self.ann.pre(self, NodeExpr(expr))?;
2030 ast::ExprKind::Box(ref expr) => {
2031 self.word_space("box")?;
2032 self.print_expr(expr)?;
2034 ast::ExprKind::InPlace(ref place, ref expr) => {
2035 self.print_expr_in_place(place, expr)?;
2037 ast::ExprKind::Array(ref exprs) => {
2038 self.print_expr_vec(&exprs[..], attrs)?;
2040 ast::ExprKind::Repeat(ref element, ref count) => {
2041 self.print_expr_repeat(&element, &count, attrs)?;
2043 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2044 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2046 ast::ExprKind::Tup(ref exprs) => {
2047 self.print_expr_tup(&exprs[..], attrs)?;
2049 ast::ExprKind::Call(ref func, ref args) => {
2050 self.print_expr_call(&func, &args[..])?;
2052 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2053 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2055 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2056 self.print_expr_binary(op, &lhs, &rhs)?;
2058 ast::ExprKind::Unary(op, ref expr) => {
2059 self.print_expr_unary(op, &expr)?;
2061 ast::ExprKind::AddrOf(m, ref expr) => {
2062 self.print_expr_addr_of(m, &expr)?;
2064 ast::ExprKind::Lit(ref lit) => {
2065 self.print_literal(&lit)?;
2067 ast::ExprKind::Cast(ref expr, ref ty) => {
2068 if let ast::ExprKind::Cast(..) = expr.node {
2069 self.print_expr(&expr)?;
2071 self.print_expr_maybe_paren(&expr)?;
2073 space(&mut self.s)?;
2074 self.word_space("as")?;
2075 self.print_type(&ty)?;
2077 ast::ExprKind::Type(ref expr, ref ty) => {
2078 self.print_expr(&expr)?;
2079 self.word_space(":")?;
2080 self.print_type(&ty)?;
2082 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2083 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2085 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2086 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2088 ast::ExprKind::While(ref test, 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")?;
2094 self.print_expr(&test)?;
2095 space(&mut self.s)?;
2096 self.print_block_with_attrs(&blk, attrs)?;
2098 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2099 if let Some(ident) = opt_ident {
2100 self.print_ident(ident.node)?;
2101 self.word_space(":")?;
2103 self.head("while let")?;
2104 self.print_pat(&pat)?;
2105 space(&mut self.s)?;
2106 self.word_space("=")?;
2107 self.print_expr(&expr)?;
2108 space(&mut self.s)?;
2109 self.print_block_with_attrs(&blk, attrs)?;
2111 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2112 if let Some(ident) = opt_ident {
2113 self.print_ident(ident.node)?;
2114 self.word_space(":")?;
2117 self.print_pat(&pat)?;
2118 space(&mut self.s)?;
2119 self.word_space("in")?;
2120 self.print_expr(&iter)?;
2121 space(&mut self.s)?;
2122 self.print_block_with_attrs(&blk, attrs)?;
2124 ast::ExprKind::Loop(ref blk, opt_ident) => {
2125 if let Some(ident) = opt_ident {
2126 self.print_ident(ident.node)?;
2127 self.word_space(":")?;
2130 space(&mut self.s)?;
2131 self.print_block_with_attrs(&blk, attrs)?;
2133 ast::ExprKind::Match(ref expr, ref arms) => {
2134 self.cbox(INDENT_UNIT)?;
2136 self.word_nbsp("match")?;
2137 self.print_expr(&expr)?;
2138 space(&mut self.s)?;
2140 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2142 self.print_arm(arm)?;
2144 self.bclose_(expr.span, INDENT_UNIT)?;
2146 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2147 self.print_capture_clause(capture_clause)?;
2149 self.print_fn_block_args(&decl)?;
2150 space(&mut self.s)?;
2151 self.print_expr(body)?;
2152 self.end()?; // need to close a box
2154 // a box will be closed by print_expr, but we didn't want an overall
2155 // wrapper so we closed the corresponding opening. so create an
2156 // empty box to satisfy the close.
2159 ast::ExprKind::Block(ref blk) => {
2160 // containing cbox, will be closed by print-block at }
2161 self.cbox(INDENT_UNIT)?;
2162 // head-box, will be closed by print-block after {
2164 self.print_block_with_attrs(&blk, attrs)?;
2166 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2167 self.print_expr(&lhs)?;
2168 space(&mut self.s)?;
2169 self.word_space("=")?;
2170 self.print_expr(&rhs)?;
2172 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2173 self.print_expr(&lhs)?;
2174 space(&mut self.s)?;
2175 word(&mut self.s, op.node.to_string())?;
2176 self.word_space("=")?;
2177 self.print_expr(&rhs)?;
2179 ast::ExprKind::Field(ref expr, id) => {
2180 self.print_expr(&expr)?;
2181 word(&mut self.s, ".")?;
2182 self.print_ident(id.node)?;
2184 ast::ExprKind::TupField(ref expr, id) => {
2185 self.print_expr(&expr)?;
2186 word(&mut self.s, ".")?;
2187 self.print_usize(id.node)?;
2189 ast::ExprKind::Index(ref expr, ref index) => {
2190 self.print_expr(&expr)?;
2191 word(&mut self.s, "[")?;
2192 self.print_expr(&index)?;
2193 word(&mut self.s, "]")?;
2195 ast::ExprKind::Range(ref start, ref end, limits) => {
2196 if let &Some(ref e) = start {
2197 self.print_expr(&e)?;
2199 if limits == ast::RangeLimits::HalfOpen {
2200 word(&mut self.s, "..")?;
2202 word(&mut self.s, "...")?;
2204 if let &Some(ref e) = end {
2205 self.print_expr(&e)?;
2208 ast::ExprKind::Path(None, ref path) => {
2209 self.print_path(path, true, 0, false)?
2211 ast::ExprKind::Path(Some(ref qself), ref path) => {
2212 self.print_qpath(path, qself, true)?
2214 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2215 word(&mut self.s, "break")?;
2216 space(&mut self.s)?;
2217 if let Some(ident) = opt_ident {
2218 self.print_ident(ident.node)?;
2219 space(&mut self.s)?;
2221 if let Some(ref expr) = *opt_expr {
2222 self.print_expr(expr)?;
2223 space(&mut self.s)?;
2226 ast::ExprKind::Continue(opt_ident) => {
2227 word(&mut self.s, "continue")?;
2228 space(&mut self.s)?;
2229 if let Some(ident) = opt_ident {
2230 self.print_ident(ident.node)?;
2234 ast::ExprKind::Ret(ref result) => {
2235 word(&mut self.s, "return")?;
2238 word(&mut self.s, " ")?;
2239 self.print_expr(&expr)?;
2244 ast::ExprKind::InlineAsm(ref a) => {
2245 word(&mut self.s, "asm!")?;
2247 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2248 self.word_space(":")?;
2250 self.commasep(Inconsistent, &a.outputs, |s, out| {
2251 let constraint = out.constraint.as_str();
2252 let mut ch = constraint.chars();
2254 Some('=') if out.is_rw => {
2255 s.print_string(&format!("+{}", ch.as_str()),
2256 ast::StrStyle::Cooked)?
2258 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2261 s.print_expr(&out.expr)?;
2265 space(&mut self.s)?;
2266 self.word_space(":")?;
2268 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2269 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2275 space(&mut self.s)?;
2276 self.word_space(":")?;
2278 self.commasep(Inconsistent, &a.clobbers,
2280 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2284 let mut options = vec![];
2286 options.push("volatile");
2289 options.push("alignstack");
2291 if a.dialect == ast::AsmDialect::Intel {
2292 options.push("intel");
2295 if !options.is_empty() {
2296 space(&mut self.s)?;
2297 self.word_space(":")?;
2298 self.commasep(Inconsistent, &options,
2300 s.print_string(co, ast::StrStyle::Cooked)?;
2307 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2308 ast::ExprKind::Paren(ref e) => {
2310 self.print_inner_attributes_inline(attrs)?;
2311 self.print_expr(&e)?;
2314 ast::ExprKind::Try(ref e) => {
2315 self.print_expr(e)?;
2316 word(&mut self.s, "?")?
2318 ast::ExprKind::Catch(ref blk) => {
2319 self.head("do catch")?;
2320 space(&mut self.s)?;
2321 self.print_block_with_attrs(&blk, attrs)?
2324 self.ann.post(self, NodeExpr(expr))?;
2328 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2329 self.print_pat(&loc.pat)?;
2330 if let Some(ref ty) = loc.ty {
2331 self.word_space(":")?;
2332 self.print_type(&ty)?;
2337 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2338 word(&mut self.s, &ident.name.as_str())?;
2339 self.ann.post(self, NodeIdent(&ident))
2342 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2343 word(&mut self.s, &i.to_string())
2346 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2347 word(&mut self.s, &name.as_str())?;
2348 self.ann.post(self, NodeName(&name))
2351 pub fn print_for_decl(&mut self, loc: &ast::Local,
2352 coll: &ast::Expr) -> io::Result<()> {
2353 self.print_local_decl(loc)?;
2354 space(&mut self.s)?;
2355 self.word_space("in")?;
2356 self.print_expr(coll)
2359 fn print_path(&mut self,
2361 colons_before_params: bool,
2363 defaults_to_global: bool)
2366 self.maybe_print_comment(path.span.lo)?;
2368 let mut segments = path.segments[..path.segments.len()-depth].iter();
2369 if defaults_to_global && path.is_global() {
2372 for (i, segment) in segments.enumerate() {
2374 word(&mut self.s, "::")?
2376 if segment.identifier.name != keywords::CrateRoot.name() &&
2377 segment.identifier.name != "$crate" {
2378 self.print_ident(segment.identifier)?;
2379 if let Some(ref parameters) = segment.parameters {
2380 self.print_path_parameters(parameters, colons_before_params)?;
2388 fn print_qpath(&mut self,
2391 colons_before_params: bool)
2394 word(&mut self.s, "<")?;
2395 self.print_type(&qself.ty)?;
2396 if qself.position > 0 {
2397 space(&mut self.s)?;
2398 self.word_space("as")?;
2399 let depth = path.segments.len() - qself.position;
2400 self.print_path(&path, false, depth, false)?;
2402 word(&mut self.s, ">")?;
2403 word(&mut self.s, "::")?;
2404 let item_segment = path.segments.last().unwrap();
2405 self.print_ident(item_segment.identifier)?;
2406 match item_segment.parameters {
2407 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2412 fn print_path_parameters(&mut self,
2413 parameters: &ast::PathParameters,
2414 colons_before_params: bool)
2417 if colons_before_params {
2418 word(&mut self.s, "::")?
2422 ast::PathParameters::AngleBracketed(ref data) => {
2423 word(&mut self.s, "<")?;
2425 let mut comma = false;
2426 for lifetime in &data.lifetimes {
2428 self.word_space(",")?
2430 self.print_lifetime(lifetime)?;
2434 if !data.types.is_empty() {
2436 self.word_space(",")?
2441 |s, ty| s.print_type(&ty))?;
2445 for binding in data.bindings.iter() {
2447 self.word_space(",")?
2449 self.print_ident(binding.ident)?;
2450 space(&mut self.s)?;
2451 self.word_space("=")?;
2452 self.print_type(&binding.ty)?;
2456 word(&mut self.s, ">")?
2459 ast::PathParameters::Parenthesized(ref data) => {
2460 word(&mut self.s, "(")?;
2464 |s, ty| s.print_type(&ty))?;
2465 word(&mut self.s, ")")?;
2467 if let Some(ref ty) = data.output {
2468 self.space_if_not_bol()?;
2469 self.word_space("->")?;
2470 self.print_type(&ty)?;
2478 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2479 self.maybe_print_comment(pat.span.lo)?;
2480 self.ann.pre(self, NodePat(pat))?;
2481 /* Pat isn't normalized, but the beauty of it
2482 is that it doesn't matter */
2484 PatKind::Wild => word(&mut self.s, "_")?,
2485 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2486 match binding_mode {
2487 ast::BindingMode::ByRef(mutbl) => {
2488 self.word_nbsp("ref")?;
2489 self.print_mutability(mutbl)?;
2491 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2492 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2493 self.word_nbsp("mut")?;
2496 self.print_ident(path1.node)?;
2497 if let Some(ref p) = *sub {
2498 word(&mut self.s, "@")?;
2499 self.print_pat(&p)?;
2502 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2503 self.print_path(path, true, 0, false)?;
2505 if let Some(ddpos) = ddpos {
2506 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2508 self.word_space(",")?;
2510 word(&mut self.s, "..")?;
2511 if ddpos != elts.len() {
2512 word(&mut self.s, ",")?;
2513 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2516 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2520 PatKind::Path(None, ref path) => {
2521 self.print_path(path, true, 0, false)?;
2523 PatKind::Path(Some(ref qself), ref path) => {
2524 self.print_qpath(path, qself, false)?;
2526 PatKind::Struct(ref path, ref fields, etc) => {
2527 self.print_path(path, true, 0, false)?;
2529 self.word_space("{")?;
2531 Consistent, &fields[..],
2533 s.cbox(INDENT_UNIT)?;
2534 if !f.node.is_shorthand {
2535 s.print_ident(f.node.ident)?;
2538 s.print_pat(&f.node.pat)?;
2541 |f| f.node.pat.span)?;
2543 if !fields.is_empty() { self.word_space(",")?; }
2544 word(&mut self.s, "..")?;
2546 space(&mut self.s)?;
2547 word(&mut self.s, "}")?;
2549 PatKind::Tuple(ref elts, ddpos) => {
2551 if let Some(ddpos) = ddpos {
2552 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2554 self.word_space(",")?;
2556 word(&mut self.s, "..")?;
2557 if ddpos != elts.len() {
2558 word(&mut self.s, ",")?;
2559 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2562 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2563 if elts.len() == 1 {
2564 word(&mut self.s, ",")?;
2569 PatKind::Box(ref inner) => {
2570 word(&mut self.s, "box ")?;
2571 self.print_pat(&inner)?;
2573 PatKind::Ref(ref inner, mutbl) => {
2574 word(&mut self.s, "&")?;
2575 if mutbl == ast::Mutability::Mutable {
2576 word(&mut self.s, "mut ")?;
2578 self.print_pat(&inner)?;
2580 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2581 PatKind::Range(ref begin, ref end, ref end_kind) => {
2582 self.print_expr(&begin)?;
2583 space(&mut self.s)?;
2585 RangeEnd::Included => word(&mut self.s, "...")?,
2586 RangeEnd::Excluded => word(&mut self.s, "..")?,
2588 self.print_expr(&end)?;
2590 PatKind::Slice(ref before, ref slice, ref after) => {
2591 word(&mut self.s, "[")?;
2592 self.commasep(Inconsistent,
2594 |s, p| s.print_pat(&p))?;
2595 if let Some(ref p) = *slice {
2596 if !before.is_empty() { self.word_space(",")?; }
2597 if p.node != PatKind::Wild {
2598 self.print_pat(&p)?;
2600 word(&mut self.s, "..")?;
2601 if !after.is_empty() { self.word_space(",")?; }
2603 self.commasep(Inconsistent,
2605 |s, p| s.print_pat(&p))?;
2606 word(&mut self.s, "]")?;
2608 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2610 self.ann.post(self, NodePat(pat))
2613 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2614 // I have no idea why this check is necessary, but here it
2616 if arm.attrs.is_empty() {
2617 space(&mut self.s)?;
2619 self.cbox(INDENT_UNIT)?;
2621 self.maybe_print_comment(arm.pats[0].span.lo)?;
2622 self.print_outer_attributes(&arm.attrs)?;
2623 let mut first = true;
2624 for p in &arm.pats {
2628 space(&mut self.s)?;
2629 self.word_space("|")?;
2631 self.print_pat(&p)?;
2633 space(&mut self.s)?;
2634 if let Some(ref e) = arm.guard {
2635 self.word_space("if")?;
2636 self.print_expr(&e)?;
2637 space(&mut self.s)?;
2639 self.word_space("=>")?;
2641 match arm.body.node {
2642 ast::ExprKind::Block(ref blk) => {
2643 // the block will close the pattern's ibox
2644 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2646 // If it is a user-provided unsafe block, print a comma after it
2647 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2648 word(&mut self.s, ",")?;
2652 self.end()?; // close the ibox for the pattern
2653 self.print_expr(&arm.body)?;
2654 word(&mut self.s, ",")?;
2657 self.end() // close enclosing cbox
2660 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2661 match explicit_self.node {
2662 SelfKind::Value(m) => {
2663 self.print_mutability(m)?;
2664 word(&mut self.s, "self")
2666 SelfKind::Region(ref lt, m) => {
2667 word(&mut self.s, "&")?;
2668 self.print_opt_lifetime(lt)?;
2669 self.print_mutability(m)?;
2670 word(&mut self.s, "self")
2672 SelfKind::Explicit(ref typ, m) => {
2673 self.print_mutability(m)?;
2674 word(&mut self.s, "self")?;
2675 self.word_space(":")?;
2676 self.print_type(&typ)
2681 pub fn print_fn(&mut self,
2683 unsafety: ast::Unsafety,
2684 constness: ast::Constness,
2686 name: Option<ast::Ident>,
2687 generics: &ast::Generics,
2688 vis: &ast::Visibility) -> io::Result<()> {
2689 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2691 if let Some(name) = name {
2693 self.print_ident(name)?;
2695 self.print_generics(generics)?;
2696 self.print_fn_args_and_ret(decl)?;
2697 self.print_where_clause(&generics.where_clause)
2700 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2703 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2705 word(&mut self.s, ", ...")?;
2709 self.print_fn_output(decl)
2712 pub fn print_fn_block_args(
2716 word(&mut self.s, "|")?;
2717 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2718 word(&mut self.s, "|")?;
2720 if let ast::FunctionRetTy::Default(..) = decl.output {
2724 self.space_if_not_bol()?;
2725 self.word_space("->")?;
2727 ast::FunctionRetTy::Ty(ref ty) => {
2728 self.print_type(&ty)?;
2729 self.maybe_print_comment(ty.span.lo)
2731 ast::FunctionRetTy::Default(..) => unreachable!(),
2735 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2737 match capture_clause {
2738 ast::CaptureBy::Value => self.word_space("move"),
2739 ast::CaptureBy::Ref => Ok(()),
2743 pub fn print_bounds(&mut self,
2745 bounds: &[ast::TyParamBound])
2747 if !bounds.is_empty() {
2748 word(&mut self.s, prefix)?;
2749 let mut first = true;
2750 for bound in bounds {
2755 self.word_space("+")?;
2759 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2760 self.print_poly_trait_ref(tref)
2762 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2763 word(&mut self.s, "?")?;
2764 self.print_poly_trait_ref(tref)
2766 RegionTyParamBound(ref lt) => {
2767 self.print_lifetime(lt)
2777 pub fn print_lifetime(&mut self,
2778 lifetime: &ast::Lifetime)
2781 self.print_name(lifetime.name)
2784 pub fn print_lifetime_bounds(&mut self,
2785 lifetime: &ast::Lifetime,
2786 bounds: &[ast::Lifetime])
2789 self.print_lifetime(lifetime)?;
2790 if !bounds.is_empty() {
2791 word(&mut self.s, ": ")?;
2792 for (i, bound) in bounds.iter().enumerate() {
2794 word(&mut self.s, " + ")?;
2796 self.print_lifetime(bound)?;
2802 pub fn print_generics(&mut self,
2803 generics: &ast::Generics)
2806 let total = generics.lifetimes.len() + generics.ty_params.len();
2811 word(&mut self.s, "<")?;
2813 let mut ints = Vec::new();
2818 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2819 if idx < generics.lifetimes.len() {
2820 let lifetime_def = &generics.lifetimes[idx];
2821 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2822 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2824 let idx = idx - generics.lifetimes.len();
2825 let param = &generics.ty_params[idx];
2826 s.print_ty_param(param)
2830 word(&mut self.s, ">")?;
2834 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2835 self.print_outer_attributes_inline(¶m.attrs)?;
2836 self.print_ident(param.ident)?;
2837 self.print_bounds(":", ¶m.bounds)?;
2838 match param.default {
2839 Some(ref default) => {
2840 space(&mut self.s)?;
2841 self.word_space("=")?;
2842 self.print_type(&default)
2848 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2850 if where_clause.predicates.is_empty() {
2854 space(&mut self.s)?;
2855 self.word_space("where")?;
2857 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2859 self.word_space(",")?;
2863 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2867 self.print_formal_lifetime_list(bound_lifetimes)?;
2868 self.print_type(&bounded_ty)?;
2869 self.print_bounds(":", bounds)?;
2871 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2874 self.print_lifetime_bounds(lifetime, bounds)?;
2876 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2879 self.print_type(lhs_ty)?;
2880 space(&mut self.s)?;
2881 self.word_space("=")?;
2882 self.print_type(rhs_ty)?;
2890 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2892 ast::ViewPathSimple(ident, ref path) => {
2893 self.print_path(path, false, 0, true)?;
2895 if path.segments.last().unwrap().identifier.name !=
2897 space(&mut self.s)?;
2898 self.word_space("as")?;
2899 self.print_ident(ident)?;
2905 ast::ViewPathGlob(ref path) => {
2906 self.print_path(path, false, 0, true)?;
2907 word(&mut self.s, "::*")
2910 ast::ViewPathList(ref path, ref idents) => {
2911 if path.segments.is_empty() {
2912 word(&mut self.s, "{")?;
2914 self.print_path(path, false, 0, true)?;
2915 word(&mut self.s, "::{")?;
2917 self.commasep(Inconsistent, &idents[..], |s, w| {
2918 s.print_ident(w.node.name)?;
2919 if let Some(ident) = w.node.rename {
2921 s.word_space("as")?;
2922 s.print_ident(ident)?;
2926 word(&mut self.s, "}")
2931 pub fn print_mutability(&mut self,
2932 mutbl: ast::Mutability) -> io::Result<()> {
2934 ast::Mutability::Mutable => self.word_nbsp("mut"),
2935 ast::Mutability::Immutable => Ok(()),
2939 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2940 self.print_mutability(mt.mutbl)?;
2941 self.print_type(&mt.ty)
2944 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2945 self.ibox(INDENT_UNIT)?;
2946 match input.ty.node {
2947 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2949 if let Some(eself) = input.to_self() {
2950 self.print_explicit_self(&eself)?;
2952 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2953 ident.node.name == keywords::Invalid.name()
2958 self.print_pat(&input.pat)?;
2959 word(&mut self.s, ":")?;
2960 space(&mut self.s)?;
2962 self.print_type(&input.ty)?;
2969 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2970 if let ast::FunctionRetTy::Default(..) = decl.output {
2974 self.space_if_not_bol()?;
2975 self.ibox(INDENT_UNIT)?;
2976 self.word_space("->")?;
2978 ast::FunctionRetTy::Default(..) => unreachable!(),
2979 ast::FunctionRetTy::Ty(ref ty) =>
2980 self.print_type(&ty)?
2985 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2990 pub fn print_ty_fn(&mut self,
2992 unsafety: ast::Unsafety,
2994 name: Option<ast::Ident>,
2995 generics: &ast::Generics)
2997 self.ibox(INDENT_UNIT)?;
2998 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2999 word(&mut self.s, "for")?;
3000 self.print_generics(generics)?;
3002 let generics = ast::Generics {
3003 lifetimes: Vec::new(),
3004 ty_params: Vec::new(),
3005 where_clause: ast::WhereClause {
3006 id: ast::DUMMY_NODE_ID,
3007 predicates: Vec::new(),
3009 span: syntax_pos::DUMMY_SP,
3013 ast::Constness::NotConst,
3017 &ast::Visibility::Inherited)?;
3021 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3022 next_pos: Option<BytePos>)
3024 let cm = match self.cm {
3028 if let Some(ref cmnt) = self.next_comment() {
3029 if cmnt.style != comments::Trailing { return Ok(()) }
3030 let span_line = cm.lookup_char_pos(span.hi);
3031 let comment_line = cm.lookup_char_pos(cmnt.pos);
3032 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3033 if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3034 self.print_comment(cmnt)?;
3035 self.cur_cmnt_and_lit.cur_cmnt += 1;
3041 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3042 // If there aren't any remaining comments, then we need to manually
3043 // make sure there is a line break at the end.
3044 if self.next_comment().is_none() {
3045 hardbreak(&mut self.s)?;
3048 match self.next_comment() {
3050 self.print_comment(cmnt)?;
3051 self.cur_cmnt_and_lit.cur_cmnt += 1;
3059 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3060 opt_abi: Option<Abi>)
3063 Some(Abi::Rust) => Ok(()),
3065 self.word_nbsp("extern")?;
3066 self.word_nbsp(&abi.to_string())
3072 pub fn print_extern_opt_abi(&mut self,
3073 opt_abi: Option<Abi>) -> io::Result<()> {
3076 self.word_nbsp("extern")?;
3077 self.word_nbsp(&abi.to_string())
3083 pub fn print_fn_header_info(&mut self,
3084 unsafety: ast::Unsafety,
3085 constness: ast::Constness,
3087 vis: &ast::Visibility) -> io::Result<()> {
3088 word(&mut self.s, &visibility_qualified(vis, ""))?;
3091 ast::Constness::NotConst => {}
3092 ast::Constness::Const => self.word_nbsp("const")?
3095 self.print_unsafety(unsafety)?;
3097 if abi != Abi::Rust {
3098 self.word_nbsp("extern")?;
3099 self.word_nbsp(&abi.to_string())?;
3102 word(&mut self.s, "fn")
3105 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3107 ast::Unsafety::Normal => Ok(()),
3108 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3113 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3124 fn test_fun_to_string() {
3125 let abba_ident = ast::Ident::from_str("abba");
3127 let decl = ast::FnDecl {
3129 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3132 let generics = ast::Generics::default();
3133 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3134 ast::Constness::NotConst,
3135 abba_ident, &generics),
3140 fn test_variant_to_string() {
3141 let ident = ast::Ident::from_str("principal_skinner");
3143 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3146 // making this up as I go.... ?
3147 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3151 let varstr = variant_to_string(&var);
3152 assert_eq!(varstr, "principal_skinner");