1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
14 use ast::{self, TokenTree, BlockCheckMode, PatKind};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use attr::ThinAttributesExt;
18 use util::parser::AssocOp;
20 use attr::{AttrMetaMethods, AttributeMethods};
21 use codemap::{self, CodeMap, BytePos};
23 use parse::token::{self, keywords, BinOpToken, Token, InternedString};
24 use parse::lexer::comments;
26 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
27 use print::pp::{Breaks, eof};
28 use print::pp::Breaks::{Consistent, Inconsistent};
33 use std::io::{self, Write, Read};
36 pub enum AnnNode<'a> {
37 NodeIdent(&'a ast::Ident),
38 NodeName(&'a ast::Name),
39 NodeBlock(&'a ast::Block),
40 NodeItem(&'a ast::Item),
41 NodeSubItem(ast::NodeId),
42 NodeExpr(&'a ast::Expr),
43 NodePat(&'a ast::Pat),
47 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
48 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
51 #[derive(Copy, Clone)]
54 impl PpAnn for NoAnn {}
56 #[derive(Copy, Clone)]
57 pub struct CurrentCommentAndLiteral {
62 pub struct State<'a> {
63 pub s: pp::Printer<'a>,
64 cm: Option<&'a CodeMap>,
65 comments: Option<Vec<comments::Comment> >,
66 literals: Option<Vec<comments::Literal> >,
67 cur_cmnt_and_lit: CurrentCommentAndLiteral,
68 boxes: Vec<pp::Breaks>,
72 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
73 static NO_ANN: NoAnn = NoAnn;
74 rust_printer_annotated(writer, &NO_ANN)
77 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
78 ann: &'a PpAnn) -> State<'a> {
80 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
84 cur_cmnt_and_lit: CurrentCommentAndLiteral {
93 pub const INDENT_UNIT: usize = 4;
95 pub const DEFAULT_COLUMNS: usize = 78;
97 /// Requires you to pass an input filename and reader so that
98 /// it can scan the input text for comments and literals to
100 pub fn print_crate<'a>(cm: &'a CodeMap,
101 span_diagnostic: &errors::Handler,
107 is_expanded: bool) -> io::Result<()> {
108 let mut s = State::new_from_input(cm,
115 if is_expanded && !std_inject::no_std(krate) {
116 // We need to print `#![no_std]` (and its feature gate) so that
117 // compiling pretty-printed source won't inject libstd again.
118 // However we don't want these attributes in the AST because
119 // of the feature gate, so we fake them up here.
121 // #![feature(prelude_import)]
122 let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
123 let list = attr::mk_list_item(InternedString::new("feature"),
124 vec![prelude_import_meta]);
125 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
126 s.print_attribute(&fake_attr)?;
129 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
130 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
131 s.print_attribute(&fake_attr)?;
134 s.print_mod(&krate.module, &krate.attrs)?;
135 s.print_remaining_comments()?;
140 pub fn new_from_input(cm: &'a CodeMap,
141 span_diagnostic: &errors::Handler,
146 is_expanded: bool) -> State<'a> {
147 let (cmnts, lits) = comments::gather_comments_and_literals(
157 // If the code is post expansion, don't use the table of
158 // literals, since it doesn't correspond with the literals
159 // in the AST anymore.
160 if is_expanded { None } else { Some(lits) })
163 pub fn new(cm: &'a CodeMap,
166 comments: Option<Vec<comments::Comment>>,
167 literals: Option<Vec<comments::Literal>>) -> State<'a> {
169 s: pp::mk_printer(out, DEFAULT_COLUMNS),
173 cur_cmnt_and_lit: CurrentCommentAndLiteral {
183 pub fn to_string<F>(f: F) -> String where
184 F: FnOnce(&mut State) -> io::Result<()>,
186 let mut wr = Vec::new();
188 let mut printer = rust_printer(Box::new(&mut wr));
189 f(&mut printer).unwrap();
190 eof(&mut printer.s).unwrap();
192 String::from_utf8(wr).unwrap()
195 pub fn binop_to_string(op: BinOpToken) -> &'static str {
201 token::Percent => "%",
210 pub fn token_to_string(tok: &Token) -> String {
212 token::Eq => "=".to_string(),
213 token::Lt => "<".to_string(),
214 token::Le => "<=".to_string(),
215 token::EqEq => "==".to_string(),
216 token::Ne => "!=".to_string(),
217 token::Ge => ">=".to_string(),
218 token::Gt => ">".to_string(),
219 token::Not => "!".to_string(),
220 token::Tilde => "~".to_string(),
221 token::OrOr => "||".to_string(),
222 token::AndAnd => "&&".to_string(),
223 token::BinOp(op) => binop_to_string(op).to_string(),
224 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
226 /* Structural symbols */
227 token::At => "@".to_string(),
228 token::Dot => ".".to_string(),
229 token::DotDot => "..".to_string(),
230 token::DotDotDot => "...".to_string(),
231 token::Comma => ",".to_string(),
232 token::Semi => ";".to_string(),
233 token::Colon => ":".to_string(),
234 token::ModSep => "::".to_string(),
235 token::RArrow => "->".to_string(),
236 token::LArrow => "<-".to_string(),
237 token::FatArrow => "=>".to_string(),
238 token::OpenDelim(token::Paren) => "(".to_string(),
239 token::CloseDelim(token::Paren) => ")".to_string(),
240 token::OpenDelim(token::Bracket) => "[".to_string(),
241 token::CloseDelim(token::Bracket) => "]".to_string(),
242 token::OpenDelim(token::Brace) => "{".to_string(),
243 token::CloseDelim(token::Brace) => "}".to_string(),
244 token::Pound => "#".to_string(),
245 token::Dollar => "$".to_string(),
246 token::Question => "?".to_string(),
249 token::Literal(lit, suf) => {
250 let mut out = match lit {
251 token::Byte(b) => format!("b'{}'", b),
252 token::Char(c) => format!("'{}'", c),
253 token::Float(c) => c.to_string(),
254 token::Integer(c) => c.to_string(),
255 token::Str_(s) => format!("\"{}\"", s),
256 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
257 delim=repeat("#", n),
259 token::ByteStr(v) => format!("b\"{}\"", v),
260 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
261 delim=repeat("#", n),
265 if let Some(s) = suf {
266 out.push_str(&s.as_str())
272 /* Name components */
273 token::Ident(s) => s.to_string(),
274 token::Lifetime(s) => s.to_string(),
275 token::Underscore => "_".to_string(),
278 token::DocComment(s) => s.to_string(),
279 token::SubstNt(s) => format!("${}", s),
280 token::MatchNt(s, t) => format!("${}:{}", s, t),
281 token::Eof => "<eof>".to_string(),
282 token::Whitespace => " ".to_string(),
283 token::Comment => "/* */".to_string(),
284 token::Shebang(s) => format!("/* shebang: {}*/", s),
286 token::SpecialVarNt(var) => format!("${}", var.as_str()),
288 token::Interpolated(ref nt) => match *nt {
289 token::NtExpr(ref e) => expr_to_string(&e),
290 token::NtMeta(ref e) => meta_item_to_string(&e),
291 token::NtTy(ref e) => ty_to_string(&e),
292 token::NtPath(ref e) => path_to_string(&e),
293 token::NtItem(ref e) => item_to_string(&e),
294 token::NtBlock(ref e) => block_to_string(&e),
295 token::NtStmt(ref e) => stmt_to_string(&e),
296 token::NtPat(ref e) => pat_to_string(&e),
297 token::NtIdent(ref e) => ident_to_string(e.node),
298 token::NtTT(ref e) => tt_to_string(&e),
299 token::NtArm(ref e) => arm_to_string(&e),
300 token::NtImplItem(ref e) => impl_item_to_string(&e),
301 token::NtTraitItem(ref e) => trait_item_to_string(&e),
302 token::NtGenerics(ref e) => generics_to_string(&e),
303 token::NtWhereClause(ref e) => where_clause_to_string(&e),
304 token::NtArg(ref e) => arg_to_string(&e),
309 pub fn ty_to_string(ty: &ast::Ty) -> String {
310 to_string(|s| s.print_type(ty))
313 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
314 to_string(|s| s.print_bounds("", bounds))
317 pub fn pat_to_string(pat: &ast::Pat) -> String {
318 to_string(|s| s.print_pat(pat))
321 pub fn arm_to_string(arm: &ast::Arm) -> String {
322 to_string(|s| s.print_arm(arm))
325 pub fn expr_to_string(e: &ast::Expr) -> String {
326 to_string(|s| s.print_expr(e))
329 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
330 to_string(|s| s.print_lifetime(e))
333 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
334 to_string(|s| s.print_tt(tt))
337 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
338 to_string(|s| s.print_tts(tts))
341 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
342 to_string(|s| s.print_stmt(stmt))
345 pub fn attr_to_string(attr: &ast::Attribute) -> String {
346 to_string(|s| s.print_attribute(attr))
349 pub fn item_to_string(i: &ast::Item) -> String {
350 to_string(|s| s.print_item(i))
353 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
354 to_string(|s| s.print_impl_item(i))
357 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
358 to_string(|s| s.print_trait_item(i))
361 pub fn generics_to_string(generics: &ast::Generics) -> String {
362 to_string(|s| s.print_generics(generics))
365 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
366 to_string(|s| s.print_where_clause(i))
369 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
370 to_string(|s| s.print_fn_block_args(p))
373 pub fn path_to_string(p: &ast::Path) -> String {
374 to_string(|s| s.print_path(p, false, 0))
377 pub fn ident_to_string(id: ast::Ident) -> String {
378 to_string(|s| s.print_ident(id))
381 pub fn fun_to_string(decl: &ast::FnDecl,
382 unsafety: ast::Unsafety,
383 constness: ast::Constness,
385 generics: &ast::Generics)
389 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_item_to_string(mi: &ast::MetaItem) -> String {
407 to_string(|s| s.print_meta_item(mi))
410 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
411 to_string(|s| s.print_attribute(attr))
414 pub fn lit_to_string(l: &ast::Lit) -> String {
415 to_string(|s| s.print_literal(l))
418 pub fn variant_to_string(var: &ast::Variant) -> String {
419 to_string(|s| s.print_variant(var))
422 pub fn arg_to_string(arg: &ast::Arg) -> String {
423 to_string(|s| s.print_arg(arg, false))
426 pub fn mac_to_string(arg: &ast::Mac) -> String {
427 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
430 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
432 ast::Visibility::Public => format!("pub {}", s),
433 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
434 ast::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
435 ast::Visibility::Inherited => s.to_string()
439 fn needs_parentheses(expr: &ast::Expr) -> bool {
441 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
442 ast::ExprKind::Closure(..) |
443 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
444 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
449 pub trait PrintState<'a> {
450 fn writer(&mut self) -> &mut pp::Printer<'a>;
451 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
452 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
453 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
454 fn literals(&self) -> &Option<Vec<comments::Literal>>;
456 fn word_space(&mut self, w: &str) -> io::Result<()> {
457 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<()> {
543 match self.next_comment() {
545 if (*cmnt).pos < pos {
546 self.print_comment(cmnt)?;
547 self.cur_cmnt_and_lit().cur_cmnt += 1;
556 fn print_comment(&mut self,
557 cmnt: &comments::Comment) -> io::Result<()> {
560 assert_eq!(cmnt.lines.len(), 1);
561 zerobreak(self.writer())?;
562 word(self.writer(), &cmnt.lines[0])?;
563 zerobreak(self.writer())
565 comments::Isolated => {
566 self.hardbreak_if_not_bol()?;
567 for line in &cmnt.lines {
568 // Don't print empty lines because they will end up as trailing
570 if !line.is_empty() {
571 word(self.writer(), &line[..])?;
573 hardbreak(self.writer())?;
577 comments::Trailing => {
578 word(self.writer(), " ")?;
579 if cmnt.lines.len() == 1 {
580 word(self.writer(), &cmnt.lines[0])?;
581 hardbreak(self.writer())
584 for line in &cmnt.lines {
585 if !line.is_empty() {
586 word(self.writer(), &line[..])?;
588 hardbreak(self.writer())?;
593 comments::BlankLine => {
594 // We need to do at least one, possibly two hardbreaks.
595 let is_semi = match self.writer().last_token() {
596 pp::Token::String(s, _) => ";" == s,
599 if is_semi || self.is_begin() || self.is_end() {
600 hardbreak(self.writer())?;
602 hardbreak(self.writer())
607 fn next_comment(&mut self) -> Option<comments::Comment> {
608 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
609 match *self.comments() {
611 if cur_cmnt < cmnts.len() {
612 Some(cmnts[cur_cmnt].clone())
621 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
622 self.maybe_print_comment(lit.span.lo)?;
623 match self.next_lit(lit.span.lo) {
625 return word(self.writer(), &(*ltrl).lit);
630 ast::LitKind::Str(ref st, style) => self.print_string(&st, style),
631 ast::LitKind::Byte(byte) => {
632 let mut res = String::from("b'");
633 res.extend(ascii::escape_default(byte).map(|c| c as char));
635 word(self.writer(), &res[..])
637 ast::LitKind::Char(ch) => {
638 let mut res = String::from("'");
639 res.extend(ch.escape_default());
641 word(self.writer(), &res[..])
643 ast::LitKind::Int(i, t) => {
645 ast::LitIntType::Signed(st) => {
647 &st.val_to_string(i as i64))
649 ast::LitIntType::Unsigned(ut) => {
650 word(self.writer(), &ut.val_to_string(i))
652 ast::LitIntType::Unsuffixed => {
653 word(self.writer(), &format!("{}", i))
657 ast::LitKind::Float(ref f, t) => {
664 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
665 ast::LitKind::Bool(val) => {
666 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
668 ast::LitKind::ByteStr(ref v) => {
669 let mut escaped: String = String::new();
670 for &ch in v.iter() {
671 escaped.extend(ascii::escape_default(ch)
672 .map(|c| c as char));
674 word(self.writer(), &format!("b\"{}\"", escaped))
679 fn print_string(&mut self, st: &str,
680 style: ast::StrStyle) -> io::Result<()> {
681 let st = match style {
682 ast::StrStyle::Cooked => {
683 (format!("\"{}\"", st.escape_default()))
685 ast::StrStyle::Raw(n) => {
686 (format!("r{delim}\"{string}\"{delim}",
687 delim=repeat("#", n),
691 word(self.writer(), &st[..])
694 fn print_inner_attributes(&mut self,
695 attrs: &[ast::Attribute]) -> io::Result<()> {
696 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
699 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
700 attrs: &[ast::Attribute])
702 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
705 fn print_outer_attributes(&mut self,
706 attrs: &[ast::Attribute]) -> io::Result<()> {
707 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
710 fn print_inner_attributes_inline(&mut self,
711 attrs: &[ast::Attribute]) -> io::Result<()> {
712 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
715 fn print_outer_attributes_inline(&mut self,
716 attrs: &[ast::Attribute]) -> io::Result<()> {
717 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
720 fn print_either_attributes(&mut self,
721 attrs: &[ast::Attribute],
722 kind: ast::AttrStyle,
724 trailing_hardbreak: bool) -> io::Result<()> {
727 if attr.node.style == kind {
728 self.print_attribute_inline(attr, is_inline)?;
735 if count > 0 && trailing_hardbreak && !is_inline {
736 self.hardbreak_if_not_bol()?;
741 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
742 self.print_attribute_inline(attr, false)
745 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
746 is_inline: bool) -> io::Result<()> {
748 self.hardbreak_if_not_bol()?;
750 self.maybe_print_comment(attr.span.lo)?;
751 if attr.node.is_sugared_doc {
752 word(self.writer(), &attr.value_str().unwrap())?;
753 hardbreak(self.writer())
755 match attr.node.style {
756 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
757 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
759 self.print_meta_item(&attr.meta())?;
760 word(self.writer(), "]")
764 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
765 self.ibox(INDENT_UNIT)?;
767 ast::MetaItemKind::Word(ref name) => {
768 word(self.writer(), &name)?;
770 ast::MetaItemKind::NameValue(ref name, ref value) => {
771 self.word_space(&name[..])?;
772 self.word_space("=")?;
773 self.print_literal(value)?;
775 ast::MetaItemKind::List(ref name, ref items) => {
776 word(self.writer(), &name)?;
778 self.commasep(Consistent,
780 |s, i| s.print_meta_item(&i))?;
787 fn space_if_not_bol(&mut self) -> io::Result<()> {
788 if !self.is_bol() { space(self.writer())?; }
792 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
795 impl<'a> PrintState<'a> for State<'a> {
796 fn writer(&mut self) -> &mut pp::Printer<'a> {
800 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
804 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
808 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
809 &mut self.cur_cmnt_and_lit
812 fn literals(&self) -> &Option<Vec<comments::Literal>> {
818 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
819 self.boxes.push(pp::Breaks::Consistent);
820 pp::cbox(&mut self.s, u)
823 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
824 word(&mut self.s, w)?;
828 pub fn head(&mut self, w: &str) -> io::Result<()> {
829 // outer-box is consistent
830 self.cbox(INDENT_UNIT)?;
831 // head-box is inconsistent
832 self.ibox(w.len() + 1)?;
833 // keyword that starts the head
840 pub fn bopen(&mut self) -> io::Result<()> {
841 word(&mut self.s, "{")?;
842 self.end() // close the head-box
845 pub fn bclose_(&mut self, span: codemap::Span,
846 indented: usize) -> io::Result<()> {
847 self.bclose_maybe_open(span, indented, true)
849 pub fn bclose_maybe_open(&mut self, span: codemap::Span,
850 indented: usize, close_box: bool) -> io::Result<()> {
851 self.maybe_print_comment(span.hi)?;
852 self.break_offset_if_not_bol(1, -(indented as isize))?;
853 word(&mut self.s, "}")?;
855 self.end()?; // close the outer-box
859 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
860 self.bclose_(span, INDENT_UNIT)
863 pub fn in_cbox(&self) -> bool {
864 match self.boxes.last() {
865 Some(&last_box) => last_box == pp::Breaks::Consistent,
870 pub fn break_offset_if_not_bol(&mut self, n: usize,
871 off: isize) -> io::Result<()> {
873 break_offset(&mut self.s, n, off)
875 if off != 0 && self.s.last_token().is_hardbreak_tok() {
876 // We do something pretty sketchy here: tuck the nonzero
877 // offset-adjustment we were going to deposit along with the
878 // break into the previous hardbreak.
879 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
885 // Synthesizes a comment that was not textually present in the original source
887 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
888 word(&mut self.s, "/*")?;
890 word(&mut self.s, &text[..])?;
892 word(&mut self.s, "*/")
897 pub fn commasep_cmnt<T, F, G>(&mut self,
901 mut get_span: G) -> io::Result<()> where
902 F: FnMut(&mut State, &T) -> io::Result<()>,
903 G: FnMut(&T) -> codemap::Span,
906 let len = elts.len();
909 self.maybe_print_comment(get_span(elt).hi)?;
913 word(&mut self.s, ",")?;
914 self.maybe_print_trailing_comment(get_span(elt),
915 Some(get_span(&elts[i]).hi))?;
916 self.space_if_not_bol()?;
922 pub fn commasep_exprs(&mut self, b: Breaks,
923 exprs: &[P<ast::Expr>]) -> io::Result<()> {
924 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
927 pub fn print_mod(&mut self, _mod: &ast::Mod,
928 attrs: &[ast::Attribute]) -> io::Result<()> {
929 self.print_inner_attributes(attrs)?;
930 for item in &_mod.items {
931 self.print_item(&item)?;
936 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
937 attrs: &[ast::Attribute]) -> io::Result<()> {
938 self.print_inner_attributes(attrs)?;
939 for item in &nmod.items {
940 self.print_foreign_item(item)?;
945 pub fn print_opt_lifetime(&mut self,
946 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
947 if let Some(l) = *lifetime {
948 self.print_lifetime(&l)?;
954 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
955 self.maybe_print_comment(ty.span.lo)?;
958 ast::TyKind::Vec(ref ty) => {
959 word(&mut self.s, "[")?;
960 self.print_type(&ty)?;
961 word(&mut self.s, "]")?;
963 ast::TyKind::Ptr(ref mt) => {
964 word(&mut self.s, "*")?;
966 ast::Mutability::Mutable => self.word_nbsp("mut")?,
967 ast::Mutability::Immutable => self.word_nbsp("const")?,
969 self.print_type(&mt.ty)?;
971 ast::TyKind::Rptr(ref lifetime, ref mt) => {
972 word(&mut self.s, "&")?;
973 self.print_opt_lifetime(lifetime)?;
976 ast::TyKind::Tup(ref elts) => {
978 self.commasep(Inconsistent, &elts[..],
979 |s, ty| s.print_type(&ty))?;
981 word(&mut self.s, ",")?;
985 ast::TyKind::Paren(ref typ) => {
987 self.print_type(&typ)?;
990 ast::TyKind::BareFn(ref f) => {
991 let generics = ast::Generics {
992 lifetimes: f.lifetimes.clone(),
994 where_clause: ast::WhereClause {
995 id: ast::DUMMY_NODE_ID,
996 predicates: Vec::new(),
999 self.print_ty_fn(f.abi,
1005 ast::TyKind::Path(None, ref path) => {
1006 self.print_path(path, false, 0)?;
1008 ast::TyKind::Path(Some(ref qself), ref path) => {
1009 self.print_qpath(path, qself, false)?
1011 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1012 self.print_type(&ty)?;
1013 self.print_bounds("+", &bounds[..])?;
1015 ast::TyKind::PolyTraitRef(ref bounds) => {
1016 self.print_bounds("", &bounds[..])?;
1018 ast::TyKind::FixedLengthVec(ref ty, ref v) => {
1019 word(&mut self.s, "[")?;
1020 self.print_type(&ty)?;
1021 word(&mut self.s, "; ")?;
1022 self.print_expr(&v)?;
1023 word(&mut self.s, "]")?;
1025 ast::TyKind::Typeof(ref e) => {
1026 word(&mut self.s, "typeof(")?;
1027 self.print_expr(&e)?;
1028 word(&mut self.s, ")")?;
1030 ast::TyKind::Infer => {
1031 word(&mut self.s, "_")?;
1033 ast::TyKind::ImplicitSelf => {
1036 ast::TyKind::Mac(ref m) => {
1037 self.print_mac(m, token::Paren)?;
1043 pub fn print_foreign_item(&mut self,
1044 item: &ast::ForeignItem) -> io::Result<()> {
1045 self.hardbreak_if_not_bol()?;
1046 self.maybe_print_comment(item.span.lo)?;
1047 self.print_outer_attributes(&item.attrs)?;
1049 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1051 self.print_fn(decl, ast::Unsafety::Normal,
1052 ast::Constness::NotConst,
1053 Abi::Rust, Some(item.ident),
1054 generics, &item.vis)?;
1055 self.end()?; // end head-ibox
1056 word(&mut self.s, ";")?;
1057 self.end() // end the outer fn box
1059 ast::ForeignItemKind::Static(ref t, m) => {
1060 self.head(&visibility_qualified(&item.vis, "static"))?;
1062 self.word_space("mut")?;
1064 self.print_ident(item.ident)?;
1065 self.word_space(":")?;
1066 self.print_type(&t)?;
1067 word(&mut self.s, ";")?;
1068 self.end()?; // end the head-ibox
1069 self.end() // end the outer cbox
1074 fn print_associated_const(&mut self,
1077 default: Option<&ast::Expr>,
1078 vis: &ast::Visibility)
1081 word(&mut self.s, &visibility_qualified(vis, ""))?;
1082 self.word_space("const")?;
1083 self.print_ident(ident)?;
1084 self.word_space(":")?;
1085 self.print_type(ty)?;
1086 if let Some(expr) = default {
1087 space(&mut self.s)?;
1088 self.word_space("=")?;
1089 self.print_expr(expr)?;
1091 word(&mut self.s, ";")
1094 fn print_associated_type(&mut self,
1096 bounds: Option<&ast::TyParamBounds>,
1097 ty: Option<&ast::Ty>)
1099 self.word_space("type")?;
1100 self.print_ident(ident)?;
1101 if let Some(bounds) = bounds {
1102 self.print_bounds(":", bounds)?;
1104 if let Some(ty) = ty {
1105 space(&mut self.s)?;
1106 self.word_space("=")?;
1107 self.print_type(ty)?;
1109 word(&mut self.s, ";")
1112 /// Pretty-print an item
1113 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1114 self.hardbreak_if_not_bol()?;
1115 self.maybe_print_comment(item.span.lo)?;
1116 self.print_outer_attributes(&item.attrs)?;
1117 self.ann.pre(self, NodeItem(item))?;
1119 ast::ItemKind::ExternCrate(ref optional_path) => {
1120 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1121 if let Some(p) = *optional_path {
1122 let val = p.as_str();
1123 if val.contains("-") {
1124 self.print_string(&val, ast::StrStyle::Cooked)?;
1126 self.print_name(p)?;
1128 space(&mut self.s)?;
1129 word(&mut self.s, "as")?;
1130 space(&mut self.s)?;
1132 self.print_ident(item.ident)?;
1133 word(&mut self.s, ";")?;
1134 self.end()?; // end inner head-block
1135 self.end()?; // end outer head-block
1137 ast::ItemKind::Use(ref vp) => {
1138 self.head(&visibility_qualified(&item.vis, "use"))?;
1139 self.print_view_path(&vp)?;
1140 word(&mut self.s, ";")?;
1141 self.end()?; // end inner head-block
1142 self.end()?; // end outer head-block
1144 ast::ItemKind::Static(ref ty, m, ref expr) => {
1145 self.head(&visibility_qualified(&item.vis, "static"))?;
1146 if m == ast::Mutability::Mutable {
1147 self.word_space("mut")?;
1149 self.print_ident(item.ident)?;
1150 self.word_space(":")?;
1151 self.print_type(&ty)?;
1152 space(&mut self.s)?;
1153 self.end()?; // end the head-ibox
1155 self.word_space("=")?;
1156 self.print_expr(&expr)?;
1157 word(&mut self.s, ";")?;
1158 self.end()?; // end the outer cbox
1160 ast::ItemKind::Const(ref ty, ref expr) => {
1161 self.head(&visibility_qualified(&item.vis, "const"))?;
1162 self.print_ident(item.ident)?;
1163 self.word_space(":")?;
1164 self.print_type(&ty)?;
1165 space(&mut self.s)?;
1166 self.end()?; // end the head-ibox
1168 self.word_space("=")?;
1169 self.print_expr(&expr)?;
1170 word(&mut self.s, ";")?;
1171 self.end()?; // end the outer cbox
1173 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1184 word(&mut self.s, " ")?;
1185 self.print_block_with_attrs(&body, &item.attrs)?;
1187 ast::ItemKind::Mod(ref _mod) => {
1188 self.head(&visibility_qualified(&item.vis, "mod"))?;
1189 self.print_ident(item.ident)?;
1192 self.print_mod(_mod, &item.attrs)?;
1193 self.bclose(item.span)?;
1195 ast::ItemKind::ForeignMod(ref nmod) => {
1196 self.head("extern")?;
1197 self.word_nbsp(&nmod.abi.to_string())?;
1199 self.print_foreign_mod(nmod, &item.attrs)?;
1200 self.bclose(item.span)?;
1202 ast::ItemKind::Ty(ref ty, ref params) => {
1203 self.ibox(INDENT_UNIT)?;
1205 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1206 self.print_ident(item.ident)?;
1207 self.print_generics(params)?;
1208 self.end()?; // end the inner ibox
1210 self.print_where_clause(¶ms.where_clause)?;
1211 space(&mut self.s)?;
1212 self.word_space("=")?;
1213 self.print_type(&ty)?;
1214 word(&mut self.s, ";")?;
1215 self.end()?; // end the outer ibox
1217 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1218 self.print_enum_def(
1226 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1227 self.head(&visibility_qualified(&item.vis, "struct"))?;
1228 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1231 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1233 self.print_visibility(&item.vis)?;
1234 self.print_unsafety(unsafety)?;
1235 self.word_nbsp("impl")?;
1236 self.print_trait_ref(trait_ref)?;
1237 space(&mut self.s)?;
1238 self.word_space("for")?;
1239 self.word_space("..")?;
1241 self.bclose(item.span)?;
1243 ast::ItemKind::Impl(unsafety,
1248 ref impl_items) => {
1250 self.print_visibility(&item.vis)?;
1251 self.print_unsafety(unsafety)?;
1252 self.word_nbsp("impl")?;
1254 if generics.is_parameterized() {
1255 self.print_generics(generics)?;
1256 space(&mut self.s)?;
1260 ast::ImplPolarity::Negative => {
1261 word(&mut self.s, "!")?;
1268 self.print_trait_ref(t)?;
1269 space(&mut self.s)?;
1270 self.word_space("for")?;
1275 self.print_type(&ty)?;
1276 self.print_where_clause(&generics.where_clause)?;
1278 space(&mut self.s)?;
1280 self.print_inner_attributes(&item.attrs)?;
1281 for impl_item in impl_items {
1282 self.print_impl_item(impl_item)?;
1284 self.bclose(item.span)?;
1286 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1288 self.print_visibility(&item.vis)?;
1289 self.print_unsafety(unsafety)?;
1290 self.word_nbsp("trait")?;
1291 self.print_ident(item.ident)?;
1292 self.print_generics(generics)?;
1293 let mut real_bounds = Vec::with_capacity(bounds.len());
1294 for b in bounds.iter() {
1295 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1296 space(&mut self.s)?;
1297 self.word_space("for ?")?;
1298 self.print_trait_ref(&ptr.trait_ref)?;
1300 real_bounds.push(b.clone());
1303 self.print_bounds(":", &real_bounds[..])?;
1304 self.print_where_clause(&generics.where_clause)?;
1305 word(&mut self.s, " ")?;
1307 for trait_item in trait_items {
1308 self.print_trait_item(trait_item)?;
1310 self.bclose(item.span)?;
1312 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1313 self.print_visibility(&item.vis)?;
1314 self.print_path(&node.path, false, 0)?;
1315 word(&mut self.s, "! ")?;
1316 self.print_ident(item.ident)?;
1317 self.cbox(INDENT_UNIT)?;
1319 self.print_tts(&node.tts[..])?;
1321 word(&mut self.s, ";")?;
1325 self.ann.post(self, NodeItem(item))
1328 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1329 self.print_path(&t.path, false, 0)
1332 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1333 if !lifetimes.is_empty() {
1334 word(&mut self.s, "for<")?;
1335 let mut comma = false;
1336 for lifetime_def in lifetimes {
1338 self.word_space(",")?
1340 self.print_lifetime_def(lifetime_def)?;
1343 word(&mut self.s, ">")?;
1348 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1349 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1350 self.print_trait_ref(&t.trait_ref)
1353 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1354 generics: &ast::Generics, ident: ast::Ident,
1355 span: codemap::Span,
1356 visibility: &ast::Visibility) -> io::Result<()> {
1357 self.head(&visibility_qualified(visibility, "enum"))?;
1358 self.print_ident(ident)?;
1359 self.print_generics(generics)?;
1360 self.print_where_clause(&generics.where_clause)?;
1361 space(&mut self.s)?;
1362 self.print_variants(&enum_definition.variants, span)
1365 pub fn print_variants(&mut self,
1366 variants: &[ast::Variant],
1367 span: codemap::Span) -> io::Result<()> {
1370 self.space_if_not_bol()?;
1371 self.maybe_print_comment(v.span.lo)?;
1372 self.print_outer_attributes(&v.node.attrs)?;
1373 self.ibox(INDENT_UNIT)?;
1374 self.print_variant(v)?;
1375 word(&mut self.s, ",")?;
1377 self.maybe_print_trailing_comment(v.span, None)?;
1382 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1384 ast::Visibility::Public => self.word_nbsp("pub"),
1385 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1386 ast::Visibility::Restricted { ref path, .. } =>
1387 self.word_nbsp(&format!("pub({})", path)),
1388 ast::Visibility::Inherited => Ok(())
1392 pub fn print_struct(&mut self,
1393 struct_def: &ast::VariantData,
1394 generics: &ast::Generics,
1396 span: codemap::Span,
1397 print_finalizer: bool) -> io::Result<()> {
1398 self.print_ident(ident)?;
1399 self.print_generics(generics)?;
1400 if !struct_def.is_struct() {
1401 if struct_def.is_tuple() {
1404 Inconsistent, struct_def.fields(),
1406 s.print_visibility(&field.vis)?;
1407 s.maybe_print_comment(field.span.lo)?;
1408 s.print_type(&field.ty)
1413 self.print_where_clause(&generics.where_clause)?;
1414 if print_finalizer {
1415 word(&mut self.s, ";")?;
1418 self.end() // close the outer-box
1420 self.print_where_clause(&generics.where_clause)?;
1423 self.hardbreak_if_not_bol()?;
1425 for field in struct_def.fields() {
1426 self.hardbreak_if_not_bol()?;
1427 self.maybe_print_comment(field.span.lo)?;
1428 self.print_outer_attributes(&field.attrs)?;
1429 self.print_visibility(&field.vis)?;
1430 self.print_ident(field.ident.unwrap())?;
1431 self.word_nbsp(":")?;
1432 self.print_type(&field.ty)?;
1433 word(&mut self.s, ",")?;
1440 /// This doesn't deserve to be called "pretty" printing, but it should be
1441 /// meaning-preserving. A quick hack that might help would be to look at the
1442 /// spans embedded in the TTs to decide where to put spaces and newlines.
1443 /// But it'd be better to parse these according to the grammar of the
1444 /// appropriate macro, transcribe back into the grammar we just parsed from,
1445 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1446 /// expression arguments as expressions). It can be done! I think.
1447 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1449 TokenTree::Token(_, ref tk) => {
1450 word(&mut self.s, &token_to_string(tk))?;
1452 parse::token::DocComment(..) => {
1453 hardbreak(&mut self.s)
1458 TokenTree::Delimited(_, ref delimed) => {
1459 word(&mut self.s, &token_to_string(&delimed.open_token()))?;
1460 space(&mut self.s)?;
1461 self.print_tts(&delimed.tts)?;
1462 space(&mut self.s)?;
1463 word(&mut self.s, &token_to_string(&delimed.close_token()))
1465 TokenTree::Sequence(_, ref seq) => {
1466 word(&mut self.s, "$(")?;
1467 for tt_elt in &seq.tts {
1468 self.print_tt(tt_elt)?;
1470 word(&mut self.s, ")")?;
1471 match seq.separator {
1473 word(&mut self.s, &token_to_string(tk))?;
1478 ast::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1479 ast::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1485 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1487 for (i, tt) in tts.iter().enumerate() {
1489 space(&mut self.s)?;
1496 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1498 let generics = ast::Generics::default();
1499 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1500 match v.node.disr_expr {
1502 space(&mut self.s)?;
1503 self.word_space("=")?;
1510 pub fn print_method_sig(&mut self,
1513 vis: &ast::Visibility)
1515 self.print_fn(&m.decl,
1524 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1526 self.ann.pre(self, NodeSubItem(ti.id))?;
1527 self.hardbreak_if_not_bol()?;
1528 self.maybe_print_comment(ti.span.lo)?;
1529 self.print_outer_attributes(&ti.attrs)?;
1531 ast::TraitItemKind::Const(ref ty, ref default) => {
1532 self.print_associated_const(ti.ident, &ty,
1533 default.as_ref().map(|expr| &**expr),
1534 &ast::Visibility::Inherited)?;
1536 ast::TraitItemKind::Method(ref sig, ref body) => {
1540 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1541 if let Some(ref body) = *body {
1543 self.print_block_with_attrs(body, &ti.attrs)?;
1545 word(&mut self.s, ";")?;
1548 ast::TraitItemKind::Type(ref bounds, ref default) => {
1549 self.print_associated_type(ti.ident, Some(bounds),
1550 default.as_ref().map(|ty| &**ty))?;
1553 self.ann.post(self, NodeSubItem(ti.id))
1556 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1557 self.ann.pre(self, NodeSubItem(ii.id))?;
1558 self.hardbreak_if_not_bol()?;
1559 self.maybe_print_comment(ii.span.lo)?;
1560 self.print_outer_attributes(&ii.attrs)?;
1561 if let ast::Defaultness::Default = ii.defaultness {
1562 self.word_nbsp("default")?;
1565 ast::ImplItemKind::Const(ref ty, ref expr) => {
1566 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1568 ast::ImplItemKind::Method(ref sig, ref body) => {
1570 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1572 self.print_block_with_attrs(body, &ii.attrs)?;
1574 ast::ImplItemKind::Type(ref ty) => {
1575 self.print_associated_type(ii.ident, None, Some(ty))?;
1577 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1578 // code copied from ItemKind::Mac:
1579 self.print_path(&node.path, false, 0)?;
1580 word(&mut self.s, "! ")?;
1581 self.cbox(INDENT_UNIT)?;
1583 self.print_tts(&node.tts[..])?;
1585 word(&mut self.s, ";")?;
1589 self.ann.post(self, NodeSubItem(ii.id))
1592 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1593 self.maybe_print_comment(st.span.lo)?;
1595 ast::StmtKind::Decl(ref decl, _) => {
1596 self.print_decl(&decl)?;
1598 ast::StmtKind::Expr(ref expr, _) => {
1599 self.space_if_not_bol()?;
1600 self.print_expr_outer_attr_style(&expr, false)?;
1602 ast::StmtKind::Semi(ref expr, _) => {
1603 self.space_if_not_bol()?;
1604 self.print_expr_outer_attr_style(&expr, false)?;
1605 word(&mut self.s, ";")?;
1607 ast::StmtKind::Mac(ref mac, style, ref attrs) => {
1608 self.space_if_not_bol()?;
1609 self.print_outer_attributes(attrs.as_attr_slice())?;
1610 let delim = match style {
1611 ast::MacStmtStyle::Braces => token::Brace,
1614 self.print_mac(&mac, delim)?;
1616 ast::MacStmtStyle::Braces => {}
1617 _ => word(&mut self.s, ";")?,
1621 if parse::classify::stmt_ends_with_semi(&st.node) {
1622 word(&mut self.s, ";")?;
1624 self.maybe_print_trailing_comment(st.span, None)
1627 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1628 self.print_block_with_attrs(blk, &[])
1631 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1632 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1635 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1636 attrs: &[ast::Attribute])
1638 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1641 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1642 indented: usize) -> io::Result<()> {
1643 self.print_block_maybe_unclosed(blk, indented, &[], false)
1646 pub fn print_block_with_attrs(&mut self,
1648 attrs: &[ast::Attribute]) -> io::Result<()> {
1649 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1652 pub fn print_block_maybe_unclosed(&mut self,
1655 attrs: &[ast::Attribute],
1656 close_box: bool) -> io::Result<()> {
1658 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1659 BlockCheckMode::Default => ()
1661 self.maybe_print_comment(blk.span.lo)?;
1662 self.ann.pre(self, NodeBlock(blk))?;
1665 self.print_inner_attributes(attrs)?;
1667 for st in &blk.stmts {
1668 self.print_stmt(st)?;
1672 self.space_if_not_bol()?;
1673 self.print_expr_outer_attr_style(&expr, false)?;
1674 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1678 self.bclose_maybe_open(blk.span, indented, close_box)?;
1679 self.ann.post(self, NodeBlock(blk))
1682 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1686 // "another else-if"
1687 ast::ExprKind::If(ref i, ref then, ref e) => {
1688 self.cbox(INDENT_UNIT - 1)?;
1690 word(&mut self.s, " else if ")?;
1691 self.print_expr(&i)?;
1692 space(&mut self.s)?;
1693 self.print_block(&then)?;
1694 self.print_else(e.as_ref().map(|e| &**e))
1696 // "another else-if-let"
1697 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1698 self.cbox(INDENT_UNIT - 1)?;
1700 word(&mut self.s, " else if let ")?;
1701 self.print_pat(&pat)?;
1702 space(&mut self.s)?;
1703 self.word_space("=")?;
1704 self.print_expr(&expr)?;
1705 space(&mut self.s)?;
1706 self.print_block(&then)?;
1707 self.print_else(e.as_ref().map(|e| &**e))
1710 ast::ExprKind::Block(ref b) => {
1711 self.cbox(INDENT_UNIT - 1)?;
1713 word(&mut self.s, " else ")?;
1714 self.print_block(&b)
1716 // BLEAH, constraints would be great here
1718 panic!("print_if saw if with weird alternative");
1726 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1727 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1729 self.print_expr(test)?;
1730 space(&mut self.s)?;
1731 self.print_block(blk)?;
1732 self.print_else(elseopt)
1735 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1736 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1737 self.head("if let")?;
1738 self.print_pat(pat)?;
1739 space(&mut self.s)?;
1740 self.word_space("=")?;
1741 self.print_expr(expr)?;
1742 space(&mut self.s)?;
1743 self.print_block(blk)?;
1744 self.print_else(elseopt)
1747 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1749 self.print_path(&m.node.path, false, 0)?;
1750 word(&mut self.s, "!")?;
1752 token::Paren => self.popen()?,
1753 token::Bracket => word(&mut self.s, "[")?,
1759 self.print_tts(&m.node.tts)?;
1761 token::Paren => self.pclose(),
1762 token::Bracket => word(&mut self.s, "]"),
1763 token::Brace => self.bclose(m.span),
1768 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1770 self.commasep_exprs(Inconsistent, args)?;
1774 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1775 binop: ast::BinOp) -> bool {
1776 match sub_expr.node {
1777 ast::ExprKind::Binary(ref sub_op, _, _) => {
1778 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1779 AssocOp::from_ast_binop(binop.node).precedence() {
1789 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1790 let needs_par = needs_parentheses(expr);
1794 self.print_expr(expr)?;
1801 fn print_expr_in_place(&mut self,
1803 expr: &ast::Expr) -> io::Result<()> {
1804 self.print_expr_maybe_paren(place)?;
1805 space(&mut self.s)?;
1806 self.word_space("<-")?;
1807 self.print_expr_maybe_paren(expr)
1810 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1811 attrs: &[Attribute]) -> io::Result<()> {
1812 self.ibox(INDENT_UNIT)?;
1813 word(&mut self.s, "[")?;
1814 self.print_inner_attributes_inline(attrs)?;
1815 self.commasep_exprs(Inconsistent, &exprs[..])?;
1816 word(&mut self.s, "]")?;
1820 fn print_expr_repeat(&mut self,
1821 element: &ast::Expr,
1823 attrs: &[Attribute]) -> io::Result<()> {
1824 self.ibox(INDENT_UNIT)?;
1825 word(&mut self.s, "[")?;
1826 self.print_inner_attributes_inline(attrs)?;
1827 self.print_expr(element)?;
1828 self.word_space(";")?;
1829 self.print_expr(count)?;
1830 word(&mut self.s, "]")?;
1834 fn print_expr_struct(&mut self,
1836 fields: &[ast::Field],
1837 wth: &Option<P<ast::Expr>>,
1838 attrs: &[Attribute]) -> io::Result<()> {
1839 self.print_path(path, true, 0)?;
1840 word(&mut self.s, "{")?;
1841 self.print_inner_attributes_inline(attrs)?;
1846 s.ibox(INDENT_UNIT)?;
1847 s.print_ident(field.ident.node)?;
1849 s.print_expr(&field.expr)?;
1855 self.ibox(INDENT_UNIT)?;
1856 if !fields.is_empty() {
1857 word(&mut self.s, ",")?;
1858 space(&mut self.s)?;
1860 word(&mut self.s, "..")?;
1861 self.print_expr(&expr)?;
1864 _ => if !fields.is_empty() {
1865 word(&mut self.s, ",")?
1868 word(&mut self.s, "}")?;
1872 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1873 attrs: &[Attribute]) -> io::Result<()> {
1875 self.print_inner_attributes_inline(attrs)?;
1876 self.commasep_exprs(Inconsistent, &exprs[..])?;
1877 if exprs.len() == 1 {
1878 word(&mut self.s, ",")?;
1883 fn print_expr_call(&mut self,
1885 args: &[P<ast::Expr>]) -> io::Result<()> {
1886 self.print_expr_maybe_paren(func)?;
1887 self.print_call_post(args)
1890 fn print_expr_method_call(&mut self,
1891 ident: ast::SpannedIdent,
1893 args: &[P<ast::Expr>]) -> io::Result<()> {
1894 let base_args = &args[1..];
1895 self.print_expr(&args[0])?;
1896 word(&mut self.s, ".")?;
1897 self.print_ident(ident.node)?;
1898 if !tys.is_empty() {
1899 word(&mut self.s, "::<")?;
1900 self.commasep(Inconsistent, tys,
1901 |s, ty| s.print_type(&ty))?;
1902 word(&mut self.s, ">")?;
1904 self.print_call_post(base_args)
1907 fn print_expr_binary(&mut self,
1910 rhs: &ast::Expr) -> io::Result<()> {
1911 if self.check_expr_bin_needs_paren(lhs, op) {
1912 self.print_expr_maybe_paren(lhs)?;
1914 self.print_expr(lhs)?;
1916 space(&mut self.s)?;
1917 self.word_space(op.node.to_string())?;
1918 if self.check_expr_bin_needs_paren(rhs, op) {
1919 self.print_expr_maybe_paren(rhs)
1921 self.print_expr(rhs)
1925 fn print_expr_unary(&mut self,
1927 expr: &ast::Expr) -> io::Result<()> {
1928 word(&mut self.s, ast::UnOp::to_string(op))?;
1929 self.print_expr_maybe_paren(expr)
1932 fn print_expr_addr_of(&mut self,
1933 mutability: ast::Mutability,
1934 expr: &ast::Expr) -> io::Result<()> {
1935 word(&mut self.s, "&")?;
1936 self.print_mutability(mutability)?;
1937 self.print_expr_maybe_paren(expr)
1940 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1941 self.print_expr_outer_attr_style(expr, true)
1944 fn print_expr_outer_attr_style(&mut self,
1946 is_inline: bool) -> io::Result<()> {
1947 self.maybe_print_comment(expr.span.lo)?;
1949 let attrs = expr.attrs.as_attr_slice();
1951 self.print_outer_attributes_inline(attrs)?;
1953 self.print_outer_attributes(attrs)?;
1956 self.ibox(INDENT_UNIT)?;
1957 self.ann.pre(self, NodeExpr(expr))?;
1959 ast::ExprKind::Box(ref expr) => {
1960 self.word_space("box")?;
1961 self.print_expr(expr)?;
1963 ast::ExprKind::InPlace(ref place, ref expr) => {
1964 self.print_expr_in_place(place, expr)?;
1966 ast::ExprKind::Vec(ref exprs) => {
1967 self.print_expr_vec(&exprs[..], attrs)?;
1969 ast::ExprKind::Repeat(ref element, ref count) => {
1970 self.print_expr_repeat(&element, &count, attrs)?;
1972 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1973 self.print_expr_struct(path, &fields[..], wth, attrs)?;
1975 ast::ExprKind::Tup(ref exprs) => {
1976 self.print_expr_tup(&exprs[..], attrs)?;
1978 ast::ExprKind::Call(ref func, ref args) => {
1979 self.print_expr_call(&func, &args[..])?;
1981 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
1982 self.print_expr_method_call(ident, &tys[..], &args[..])?;
1984 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1985 self.print_expr_binary(op, &lhs, &rhs)?;
1987 ast::ExprKind::Unary(op, ref expr) => {
1988 self.print_expr_unary(op, &expr)?;
1990 ast::ExprKind::AddrOf(m, ref expr) => {
1991 self.print_expr_addr_of(m, &expr)?;
1993 ast::ExprKind::Lit(ref lit) => {
1994 self.print_literal(&lit)?;
1996 ast::ExprKind::Cast(ref expr, ref ty) => {
1997 if let ast::ExprKind::Cast(..) = expr.node {
1998 self.print_expr(&expr)?;
2000 self.print_expr_maybe_paren(&expr)?;
2002 space(&mut self.s)?;
2003 self.word_space("as")?;
2004 self.print_type(&ty)?;
2006 ast::ExprKind::Type(ref expr, ref ty) => {
2007 self.print_expr(&expr)?;
2008 self.word_space(":")?;
2009 self.print_type(&ty)?;
2011 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2012 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2014 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2015 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2017 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2018 if let Some(ident) = opt_ident {
2019 self.print_ident(ident.node)?;
2020 self.word_space(":")?;
2022 self.head("while")?;
2023 self.print_expr(&test)?;
2024 space(&mut self.s)?;
2025 self.print_block_with_attrs(&blk, attrs)?;
2027 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2028 if let Some(ident) = opt_ident {
2029 self.print_ident(ident.node)?;
2030 self.word_space(":")?;
2032 self.head("while let")?;
2033 self.print_pat(&pat)?;
2034 space(&mut self.s)?;
2035 self.word_space("=")?;
2036 self.print_expr(&expr)?;
2037 space(&mut self.s)?;
2038 self.print_block_with_attrs(&blk, attrs)?;
2040 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2041 if let Some(ident) = opt_ident {
2042 self.print_ident(ident.node)?;
2043 self.word_space(":")?;
2046 self.print_pat(&pat)?;
2047 space(&mut self.s)?;
2048 self.word_space("in")?;
2049 self.print_expr(&iter)?;
2050 space(&mut self.s)?;
2051 self.print_block_with_attrs(&blk, attrs)?;
2053 ast::ExprKind::Loop(ref blk, opt_ident) => {
2054 if let Some(ident) = opt_ident {
2055 self.print_ident(ident.node)?;
2056 self.word_space(":")?;
2059 space(&mut self.s)?;
2060 self.print_block_with_attrs(&blk, attrs)?;
2062 ast::ExprKind::Match(ref expr, ref arms) => {
2063 self.cbox(INDENT_UNIT)?;
2065 self.word_nbsp("match")?;
2066 self.print_expr(&expr)?;
2067 space(&mut self.s)?;
2069 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2071 self.print_arm(arm)?;
2073 self.bclose_(expr.span, INDENT_UNIT)?;
2075 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2076 self.print_capture_clause(capture_clause)?;
2078 self.print_fn_block_args(&decl)?;
2079 space(&mut self.s)?;
2081 let default_return = match decl.output {
2082 ast::FunctionRetTy::Default(..) => true,
2086 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2087 self.print_block_unclosed(&body)?;
2089 // we extract the block, so as not to create another set of boxes
2090 let i_expr = body.expr.as_ref().unwrap();
2092 ast::ExprKind::Block(ref blk) => {
2093 self.print_block_unclosed_with_attrs(
2095 i_expr.attrs.as_attr_slice())?;
2098 // this is a bare expression
2099 self.print_expr(&i_expr)?;
2100 self.end()?; // need to close a box
2104 // a box will be closed by print_expr, but we didn't want an overall
2105 // wrapper so we closed the corresponding opening. so create an
2106 // empty box to satisfy the close.
2109 ast::ExprKind::Block(ref blk) => {
2110 // containing cbox, will be closed by print-block at }
2111 self.cbox(INDENT_UNIT)?;
2112 // head-box, will be closed by print-block after {
2114 self.print_block_with_attrs(&blk, attrs)?;
2116 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2117 self.print_expr(&lhs)?;
2118 space(&mut self.s)?;
2119 self.word_space("=")?;
2120 self.print_expr(&rhs)?;
2122 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2123 self.print_expr(&lhs)?;
2124 space(&mut self.s)?;
2125 word(&mut self.s, op.node.to_string())?;
2126 self.word_space("=")?;
2127 self.print_expr(&rhs)?;
2129 ast::ExprKind::Field(ref expr, id) => {
2130 self.print_expr(&expr)?;
2131 word(&mut self.s, ".")?;
2132 self.print_ident(id.node)?;
2134 ast::ExprKind::TupField(ref expr, id) => {
2135 self.print_expr(&expr)?;
2136 word(&mut self.s, ".")?;
2137 self.print_usize(id.node)?;
2139 ast::ExprKind::Index(ref expr, ref index) => {
2140 self.print_expr(&expr)?;
2141 word(&mut self.s, "[")?;
2142 self.print_expr(&index)?;
2143 word(&mut self.s, "]")?;
2145 ast::ExprKind::Range(ref start, ref end, limits) => {
2146 if let &Some(ref e) = start {
2147 self.print_expr(&e)?;
2149 if limits == ast::RangeLimits::HalfOpen {
2150 word(&mut self.s, "..")?;
2152 word(&mut self.s, "...")?;
2154 if let &Some(ref e) = end {
2155 self.print_expr(&e)?;
2158 ast::ExprKind::Path(None, ref path) => {
2159 self.print_path(path, true, 0)?
2161 ast::ExprKind::Path(Some(ref qself), ref path) => {
2162 self.print_qpath(path, qself, true)?
2164 ast::ExprKind::Break(opt_ident) => {
2165 word(&mut self.s, "break")?;
2166 space(&mut self.s)?;
2167 if let Some(ident) = opt_ident {
2168 self.print_ident(ident.node)?;
2169 space(&mut self.s)?;
2172 ast::ExprKind::Again(opt_ident) => {
2173 word(&mut self.s, "continue")?;
2174 space(&mut self.s)?;
2175 if let Some(ident) = opt_ident {
2176 self.print_ident(ident.node)?;
2180 ast::ExprKind::Ret(ref result) => {
2181 word(&mut self.s, "return")?;
2184 word(&mut self.s, " ")?;
2185 self.print_expr(&expr)?;
2190 ast::ExprKind::InlineAsm(ref a) => {
2191 word(&mut self.s, "asm!")?;
2193 self.print_string(&a.asm, a.asm_str_style)?;
2194 self.word_space(":")?;
2196 self.commasep(Inconsistent, &a.outputs,
2198 let mut ch = out.constraint.chars();
2200 Some('=') if out.is_rw => {
2201 s.print_string(&format!("+{}", ch.as_str()),
2202 ast::StrStyle::Cooked)?
2204 _ => s.print_string(&out.constraint,
2205 ast::StrStyle::Cooked)?
2208 s.print_expr(&out.expr)?;
2212 space(&mut self.s)?;
2213 self.word_space(":")?;
2215 self.commasep(Inconsistent, &a.inputs,
2216 |s, &(ref co, ref o)| {
2217 s.print_string(&co, ast::StrStyle::Cooked)?;
2223 space(&mut self.s)?;
2224 self.word_space(":")?;
2226 self.commasep(Inconsistent, &a.clobbers,
2228 s.print_string(&co, ast::StrStyle::Cooked)?;
2232 let mut options = vec!();
2234 options.push("volatile");
2237 options.push("alignstack");
2239 if a.dialect == ast::AsmDialect::Intel {
2240 options.push("intel");
2243 if !options.is_empty() {
2244 space(&mut self.s)?;
2245 self.word_space(":")?;
2246 self.commasep(Inconsistent, &options,
2248 s.print_string(co, ast::StrStyle::Cooked)?;
2255 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2256 ast::ExprKind::Paren(ref e) => {
2258 self.print_inner_attributes_inline(attrs)?;
2259 self.print_expr(&e)?;
2262 ast::ExprKind::Try(ref e) => {
2263 self.print_expr(e)?;
2264 word(&mut self.s, "?")?
2267 self.ann.post(self, NodeExpr(expr))?;
2271 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2272 self.print_pat(&loc.pat)?;
2273 if let Some(ref ty) = loc.ty {
2274 self.word_space(":")?;
2275 self.print_type(&ty)?;
2280 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2281 self.maybe_print_comment(decl.span.lo)?;
2283 ast::DeclKind::Local(ref loc) => {
2284 self.print_outer_attributes(loc.attrs.as_attr_slice())?;
2285 self.space_if_not_bol()?;
2286 self.ibox(INDENT_UNIT)?;
2287 self.word_nbsp("let")?;
2289 self.ibox(INDENT_UNIT)?;
2290 self.print_local_decl(&loc)?;
2292 if let Some(ref init) = loc.init {
2294 self.word_space("=")?;
2295 self.print_expr(&init)?;
2299 ast::DeclKind::Item(ref item) => self.print_item(&item)
2303 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2304 word(&mut self.s, &ident.name.as_str())?;
2305 self.ann.post(self, NodeIdent(&ident))
2308 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2309 word(&mut self.s, &i.to_string())
2312 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2313 word(&mut self.s, &name.as_str())?;
2314 self.ann.post(self, NodeName(&name))
2317 pub fn print_for_decl(&mut self, loc: &ast::Local,
2318 coll: &ast::Expr) -> io::Result<()> {
2319 self.print_local_decl(loc)?;
2320 space(&mut self.s)?;
2321 self.word_space("in")?;
2322 self.print_expr(coll)
2325 fn print_path(&mut self,
2327 colons_before_params: bool,
2331 self.maybe_print_comment(path.span.lo)?;
2333 let mut first = !path.global;
2334 for segment in &path.segments[..path.segments.len()-depth] {
2338 word(&mut self.s, "::")?
2341 self.print_ident(segment.identifier)?;
2343 self.print_path_parameters(&segment.parameters, colons_before_params)?;
2349 fn print_qpath(&mut self,
2352 colons_before_params: bool)
2355 word(&mut self.s, "<")?;
2356 self.print_type(&qself.ty)?;
2357 if qself.position > 0 {
2358 space(&mut self.s)?;
2359 self.word_space("as")?;
2360 let depth = path.segments.len() - qself.position;
2361 self.print_path(&path, false, depth)?;
2363 word(&mut self.s, ">")?;
2364 word(&mut self.s, "::")?;
2365 let item_segment = path.segments.last().unwrap();
2366 self.print_ident(item_segment.identifier)?;
2367 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2370 fn print_path_parameters(&mut self,
2371 parameters: &ast::PathParameters,
2372 colons_before_params: bool)
2375 if parameters.is_empty() {
2379 if colons_before_params {
2380 word(&mut self.s, "::")?
2384 ast::PathParameters::AngleBracketed(ref data) => {
2385 word(&mut self.s, "<")?;
2387 let mut comma = false;
2388 for lifetime in &data.lifetimes {
2390 self.word_space(",")?
2392 self.print_lifetime(lifetime)?;
2396 if !data.types.is_empty() {
2398 self.word_space(",")?
2403 |s, ty| s.print_type(&ty))?;
2407 for binding in data.bindings.iter() {
2409 self.word_space(",")?
2411 self.print_ident(binding.ident)?;
2412 space(&mut self.s)?;
2413 self.word_space("=")?;
2414 self.print_type(&binding.ty)?;
2418 word(&mut self.s, ">")?
2421 ast::PathParameters::Parenthesized(ref data) => {
2422 word(&mut self.s, "(")?;
2426 |s, ty| s.print_type(&ty))?;
2427 word(&mut self.s, ")")?;
2432 self.space_if_not_bol()?;
2433 self.word_space("->")?;
2434 self.print_type(&ty)?;
2443 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2444 self.maybe_print_comment(pat.span.lo)?;
2445 self.ann.pre(self, NodePat(pat))?;
2446 /* Pat isn't normalized, but the beauty of it
2447 is that it doesn't matter */
2449 PatKind::Wild => word(&mut self.s, "_")?,
2450 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2451 match binding_mode {
2452 ast::BindingMode::ByRef(mutbl) => {
2453 self.word_nbsp("ref")?;
2454 self.print_mutability(mutbl)?;
2456 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2457 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2458 self.word_nbsp("mut")?;
2461 self.print_ident(path1.node)?;
2464 word(&mut self.s, "@")?;
2465 self.print_pat(&p)?;
2470 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2471 self.print_path(path, true, 0)?;
2473 if let Some(ddpos) = ddpos {
2474 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2476 self.word_space(",")?;
2478 word(&mut self.s, "..")?;
2479 if ddpos != elts.len() {
2480 word(&mut self.s, ",")?;
2481 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2484 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2488 PatKind::Path(ref path) => {
2489 self.print_path(path, true, 0)?;
2491 PatKind::QPath(ref qself, ref path) => {
2492 self.print_qpath(path, qself, false)?;
2494 PatKind::Struct(ref path, ref fields, etc) => {
2495 self.print_path(path, true, 0)?;
2497 self.word_space("{")?;
2499 Consistent, &fields[..],
2501 s.cbox(INDENT_UNIT)?;
2502 if !f.node.is_shorthand {
2503 s.print_ident(f.node.ident)?;
2506 s.print_pat(&f.node.pat)?;
2509 |f| f.node.pat.span)?;
2511 if !fields.is_empty() { self.word_space(",")?; }
2512 word(&mut self.s, "..")?;
2514 space(&mut self.s)?;
2515 word(&mut self.s, "}")?;
2517 PatKind::Tuple(ref elts, ddpos) => {
2519 if let Some(ddpos) = ddpos {
2520 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2522 self.word_space(",")?;
2524 word(&mut self.s, "..")?;
2525 if ddpos != elts.len() {
2526 word(&mut self.s, ",")?;
2527 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2530 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2531 if elts.len() == 1 {
2532 word(&mut self.s, ",")?;
2537 PatKind::Box(ref inner) => {
2538 word(&mut self.s, "box ")?;
2539 self.print_pat(&inner)?;
2541 PatKind::Ref(ref inner, mutbl) => {
2542 word(&mut self.s, "&")?;
2543 if mutbl == ast::Mutability::Mutable {
2544 word(&mut self.s, "mut ")?;
2546 self.print_pat(&inner)?;
2548 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2549 PatKind::Range(ref begin, ref end) => {
2550 self.print_expr(&begin)?;
2551 space(&mut self.s)?;
2552 word(&mut self.s, "...")?;
2553 self.print_expr(&end)?;
2555 PatKind::Vec(ref before, ref slice, ref after) => {
2556 word(&mut self.s, "[")?;
2557 self.commasep(Inconsistent,
2559 |s, p| s.print_pat(&p))?;
2560 if let Some(ref p) = *slice {
2561 if !before.is_empty() { self.word_space(",")?; }
2562 if p.node != PatKind::Wild {
2563 self.print_pat(&p)?;
2565 word(&mut self.s, "..")?;
2566 if !after.is_empty() { self.word_space(",")?; }
2568 self.commasep(Inconsistent,
2570 |s, p| s.print_pat(&p))?;
2571 word(&mut self.s, "]")?;
2573 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2575 self.ann.post(self, NodePat(pat))
2578 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2579 // I have no idea why this check is necessary, but here it
2581 if arm.attrs.is_empty() {
2582 space(&mut self.s)?;
2584 self.cbox(INDENT_UNIT)?;
2586 self.print_outer_attributes(&arm.attrs)?;
2587 let mut first = true;
2588 for p in &arm.pats {
2592 space(&mut self.s)?;
2593 self.word_space("|")?;
2595 self.print_pat(&p)?;
2597 space(&mut self.s)?;
2598 if let Some(ref e) = arm.guard {
2599 self.word_space("if")?;
2600 self.print_expr(&e)?;
2601 space(&mut self.s)?;
2603 self.word_space("=>")?;
2605 match arm.body.node {
2606 ast::ExprKind::Block(ref blk) => {
2607 // the block will close the pattern's ibox
2608 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2610 // If it is a user-provided unsafe block, print a comma after it
2611 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2612 word(&mut self.s, ",")?;
2616 self.end()?; // close the ibox for the pattern
2617 self.print_expr(&arm.body)?;
2618 word(&mut self.s, ",")?;
2621 self.end() // close enclosing cbox
2624 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2625 match explicit_self.node {
2626 SelfKind::Value(m) => {
2627 self.print_mutability(m)?;
2628 word(&mut self.s, "self")
2630 SelfKind::Region(ref lt, m) => {
2631 word(&mut self.s, "&")?;
2632 self.print_opt_lifetime(lt)?;
2633 self.print_mutability(m)?;
2634 word(&mut self.s, "self")
2636 SelfKind::Explicit(ref typ, m) => {
2637 self.print_mutability(m)?;
2638 word(&mut self.s, "self")?;
2639 self.word_space(":")?;
2640 self.print_type(&typ)
2645 pub fn print_fn(&mut self,
2647 unsafety: ast::Unsafety,
2648 constness: ast::Constness,
2650 name: Option<ast::Ident>,
2651 generics: &ast::Generics,
2652 vis: &ast::Visibility) -> io::Result<()> {
2653 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2655 if let Some(name) = name {
2657 self.print_ident(name)?;
2659 self.print_generics(generics)?;
2660 self.print_fn_args_and_ret(decl)?;
2661 self.print_where_clause(&generics.where_clause)
2664 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2667 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2669 word(&mut self.s, ", ...")?;
2673 self.print_fn_output(decl)
2676 pub fn print_fn_block_args(
2680 word(&mut self.s, "|")?;
2681 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2682 word(&mut self.s, "|")?;
2684 if let ast::FunctionRetTy::Default(..) = decl.output {
2688 self.space_if_not_bol()?;
2689 self.word_space("->")?;
2691 ast::FunctionRetTy::Ty(ref ty) => {
2692 self.print_type(&ty)?;
2693 self.maybe_print_comment(ty.span.lo)
2695 ast::FunctionRetTy::Default(..) => unreachable!(),
2696 ast::FunctionRetTy::None(span) => {
2697 self.word_nbsp("!")?;
2698 self.maybe_print_comment(span.lo)
2703 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2705 match capture_clause {
2706 ast::CaptureBy::Value => self.word_space("move"),
2707 ast::CaptureBy::Ref => Ok(()),
2711 pub fn print_bounds(&mut self,
2713 bounds: &[ast::TyParamBound])
2715 if !bounds.is_empty() {
2716 word(&mut self.s, prefix)?;
2717 let mut first = true;
2718 for bound in bounds {
2723 self.word_space("+")?;
2727 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2728 self.print_poly_trait_ref(tref)
2730 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2731 word(&mut self.s, "?")?;
2732 self.print_poly_trait_ref(tref)
2734 RegionTyParamBound(ref lt) => {
2735 self.print_lifetime(lt)
2745 pub fn print_lifetime(&mut self,
2746 lifetime: &ast::Lifetime)
2749 self.print_name(lifetime.name)
2752 pub fn print_lifetime_def(&mut self,
2753 lifetime: &ast::LifetimeDef)
2756 self.print_lifetime(&lifetime.lifetime)?;
2758 for v in &lifetime.bounds {
2759 word(&mut self.s, sep)?;
2760 self.print_lifetime(v)?;
2766 pub fn print_generics(&mut self,
2767 generics: &ast::Generics)
2770 let total = generics.lifetimes.len() + generics.ty_params.len();
2775 word(&mut self.s, "<")?;
2777 let mut ints = Vec::new();
2782 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2783 if idx < generics.lifetimes.len() {
2784 let lifetime = &generics.lifetimes[idx];
2785 s.print_lifetime_def(lifetime)
2787 let idx = idx - generics.lifetimes.len();
2788 let param = &generics.ty_params[idx];
2789 s.print_ty_param(param)
2793 word(&mut self.s, ">")?;
2797 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2798 self.print_ident(param.ident)?;
2799 self.print_bounds(":", ¶m.bounds)?;
2800 match param.default {
2801 Some(ref default) => {
2802 space(&mut self.s)?;
2803 self.word_space("=")?;
2804 self.print_type(&default)
2810 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2812 if where_clause.predicates.is_empty() {
2816 space(&mut self.s)?;
2817 self.word_space("where")?;
2819 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2821 self.word_space(",")?;
2825 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2829 self.print_formal_lifetime_list(bound_lifetimes)?;
2830 self.print_type(&bounded_ty)?;
2831 self.print_bounds(":", bounds)?;
2833 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2836 self.print_lifetime(lifetime)?;
2837 word(&mut self.s, ":")?;
2839 for (i, bound) in bounds.iter().enumerate() {
2840 self.print_lifetime(bound)?;
2843 word(&mut self.s, ":")?;
2847 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2848 self.print_path(path, false, 0)?;
2849 space(&mut self.s)?;
2850 self.word_space("=")?;
2851 self.print_type(&ty)?;
2859 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2861 ast::ViewPathSimple(ident, ref path) => {
2862 self.print_path(path, false, 0)?;
2864 if path.segments.last().unwrap().identifier.name !=
2866 space(&mut self.s)?;
2867 self.word_space("as")?;
2868 self.print_ident(ident)?;
2874 ast::ViewPathGlob(ref path) => {
2875 self.print_path(path, false, 0)?;
2876 word(&mut self.s, "::*")
2879 ast::ViewPathList(ref path, ref idents) => {
2880 if path.segments.is_empty() {
2881 word(&mut self.s, "{")?;
2883 self.print_path(path, false, 0)?;
2884 word(&mut self.s, "::{")?;
2886 self.commasep(Inconsistent, &idents[..], |s, w| {
2888 ast::PathListItemKind::Ident { name, rename, .. } => {
2889 s.print_ident(name)?;
2890 if let Some(ident) = rename {
2892 s.word_space("as")?;
2893 s.print_ident(ident)?;
2897 ast::PathListItemKind::Mod { rename, .. } => {
2898 word(&mut s.s, "self")?;
2899 if let Some(ident) = rename {
2901 s.word_space("as")?;
2902 s.print_ident(ident)?;
2908 word(&mut self.s, "}")
2913 pub fn print_mutability(&mut self,
2914 mutbl: ast::Mutability) -> io::Result<()> {
2916 ast::Mutability::Mutable => self.word_nbsp("mut"),
2917 ast::Mutability::Immutable => Ok(()),
2921 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2922 self.print_mutability(mt.mutbl)?;
2923 self.print_type(&mt.ty)
2926 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2927 self.ibox(INDENT_UNIT)?;
2928 match input.ty.node {
2929 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2931 if let Some(eself) = input.to_self() {
2932 self.print_explicit_self(&eself)?;
2934 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2935 ident.node.name == keywords::Invalid.name()
2940 self.print_pat(&input.pat)?;
2941 word(&mut self.s, ":")?;
2942 space(&mut self.s)?;
2944 self.print_type(&input.ty)?;
2951 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2952 if let ast::FunctionRetTy::Default(..) = decl.output {
2956 self.space_if_not_bol()?;
2957 self.ibox(INDENT_UNIT)?;
2958 self.word_space("->")?;
2960 ast::FunctionRetTy::None(_) =>
2961 self.word_nbsp("!")?,
2962 ast::FunctionRetTy::Default(..) => unreachable!(),
2963 ast::FunctionRetTy::Ty(ref ty) =>
2964 self.print_type(&ty)?
2969 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2974 pub fn print_ty_fn(&mut self,
2976 unsafety: ast::Unsafety,
2978 name: Option<ast::Ident>,
2979 generics: &ast::Generics)
2981 self.ibox(INDENT_UNIT)?;
2982 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2983 word(&mut self.s, "for")?;
2984 self.print_generics(generics)?;
2986 let generics = ast::Generics {
2987 lifetimes: Vec::new(),
2988 ty_params: P::new(),
2989 where_clause: ast::WhereClause {
2990 id: ast::DUMMY_NODE_ID,
2991 predicates: Vec::new(),
2996 ast::Constness::NotConst,
3000 &ast::Visibility::Inherited)?;
3004 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
3005 next_pos: Option<BytePos>)
3007 let cm = match self.cm {
3011 match self.next_comment() {
3013 if (*cmnt).style != comments::Trailing { return Ok(()) }
3014 let span_line = cm.lookup_char_pos(span.hi);
3015 let comment_line = cm.lookup_char_pos((*cmnt).pos);
3016 let mut next = (*cmnt).pos + BytePos(1);
3017 match next_pos { None => (), Some(p) => next = p }
3018 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
3019 span_line.line == comment_line.line {
3020 self.print_comment(cmnt)?;
3021 self.cur_cmnt_and_lit.cur_cmnt += 1;
3029 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3030 // If there aren't any remaining comments, then we need to manually
3031 // make sure there is a line break at the end.
3032 if self.next_comment().is_none() {
3033 hardbreak(&mut self.s)?;
3036 match self.next_comment() {
3038 self.print_comment(cmnt)?;
3039 self.cur_cmnt_and_lit.cur_cmnt += 1;
3047 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3048 opt_abi: Option<Abi>)
3051 Some(Abi::Rust) => Ok(()),
3053 self.word_nbsp("extern")?;
3054 self.word_nbsp(&abi.to_string())
3060 pub fn print_extern_opt_abi(&mut self,
3061 opt_abi: Option<Abi>) -> io::Result<()> {
3064 self.word_nbsp("extern")?;
3065 self.word_nbsp(&abi.to_string())
3071 pub fn print_fn_header_info(&mut self,
3072 unsafety: ast::Unsafety,
3073 constness: ast::Constness,
3075 vis: &ast::Visibility) -> io::Result<()> {
3076 word(&mut self.s, &visibility_qualified(vis, ""))?;
3079 ast::Constness::NotConst => {}
3080 ast::Constness::Const => self.word_nbsp("const")?
3083 self.print_unsafety(unsafety)?;
3085 if abi != Abi::Rust {
3086 self.word_nbsp("extern")?;
3087 self.word_nbsp(&abi.to_string())?;
3090 word(&mut self.s, "fn")
3093 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3095 ast::Unsafety::Normal => Ok(()),
3096 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3101 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3112 fn test_fun_to_string() {
3113 let abba_ident = token::str_to_ident("abba");
3115 let decl = ast::FnDecl {
3117 output: ast::FunctionRetTy::Default(codemap::DUMMY_SP),
3120 let generics = ast::Generics::default();
3121 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3122 ast::Constness::NotConst,
3123 abba_ident, &generics),
3128 fn test_variant_to_string() {
3129 let ident = token::str_to_ident("principal_skinner");
3131 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3134 // making this up as I go.... ?
3135 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3139 let varstr = variant_to_string(&var);
3140 assert_eq!(varstr, "principal_skinner");