1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
14 use ast::{self, BlockCheckMode, PatKind};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use codemap::{self, CodeMap};
20 use syntax_pos::{self, BytePos};
22 use parse::token::{self, BinOpToken, Token};
23 use parse::lexer::comments;
25 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, eof};
27 use print::pp::Breaks::{Consistent, Inconsistent};
30 use symbol::{Symbol, keywords};
31 use tokenstream::{self, TokenTree};
36 use std::io::{self, Write, Read};
39 pub enum AnnNode<'a> {
40 NodeIdent(&'a ast::Ident),
41 NodeName(&'a ast::Name),
42 NodeBlock(&'a ast::Block),
43 NodeItem(&'a ast::Item),
44 NodeSubItem(ast::NodeId),
45 NodeExpr(&'a ast::Expr),
46 NodePat(&'a ast::Pat),
50 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
51 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
54 #[derive(Copy, Clone)]
57 impl PpAnn for NoAnn {}
59 #[derive(Copy, Clone)]
60 pub struct CurrentCommentAndLiteral {
65 pub struct State<'a> {
66 pub s: pp::Printer<'a>,
67 cm: Option<&'a CodeMap>,
68 comments: Option<Vec<comments::Comment> >,
69 literals: Option<Vec<comments::Literal> >,
70 cur_cmnt_and_lit: CurrentCommentAndLiteral,
71 boxes: Vec<pp::Breaks>,
75 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
76 static NO_ANN: NoAnn = NoAnn;
77 rust_printer_annotated(writer, &NO_ANN)
80 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
81 ann: &'a PpAnn) -> State<'a> {
83 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
87 cur_cmnt_and_lit: CurrentCommentAndLiteral {
96 pub const INDENT_UNIT: usize = 4;
98 pub const DEFAULT_COLUMNS: usize = 78;
100 /// Requires you to pass an input filename and reader so that
101 /// it can scan the input text for comments and literals to
103 pub fn print_crate<'a>(cm: &'a CodeMap,
104 span_diagnostic: &errors::Handler,
110 is_expanded: bool) -> io::Result<()> {
111 let mut s = State::new_from_input(cm,
118 if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
119 // We need to print `#![no_std]` (and its feature gate) so that
120 // compiling pretty-printed source won't inject libstd again.
121 // However we don't want these attributes in the AST because
122 // of the feature gate, so we fake them up here.
124 // #![feature(prelude_import)]
125 let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
126 let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
127 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
128 s.print_attribute(&fake_attr)?;
131 let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
132 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
133 s.print_attribute(&fake_attr)?;
136 s.print_mod(&krate.module, &krate.attrs)?;
137 s.print_remaining_comments()?;
142 pub fn new_from_input(cm: &'a CodeMap,
143 span_diagnostic: &errors::Handler,
148 is_expanded: bool) -> State<'a> {
149 let (cmnts, lits) = comments::gather_comments_and_literals(
159 // If the code is post expansion, don't use the table of
160 // literals, since it doesn't correspond with the literals
161 // in the AST anymore.
162 if is_expanded { None } else { Some(lits) })
165 pub fn new(cm: &'a CodeMap,
168 comments: Option<Vec<comments::Comment>>,
169 literals: Option<Vec<comments::Literal>>) -> State<'a> {
171 s: pp::mk_printer(out, DEFAULT_COLUMNS),
175 cur_cmnt_and_lit: CurrentCommentAndLiteral {
185 pub fn to_string<F>(f: F) -> String where
186 F: FnOnce(&mut State) -> io::Result<()>,
188 let mut wr = Vec::new();
190 let mut printer = rust_printer(Box::new(&mut wr));
191 f(&mut printer).unwrap();
192 eof(&mut printer.s).unwrap();
194 String::from_utf8(wr).unwrap()
197 pub fn binop_to_string(op: BinOpToken) -> &'static str {
203 token::Percent => "%",
212 pub fn token_to_string(tok: &Token) -> String {
214 token::Eq => "=".to_string(),
215 token::Lt => "<".to_string(),
216 token::Le => "<=".to_string(),
217 token::EqEq => "==".to_string(),
218 token::Ne => "!=".to_string(),
219 token::Ge => ">=".to_string(),
220 token::Gt => ">".to_string(),
221 token::Not => "!".to_string(),
222 token::Tilde => "~".to_string(),
223 token::OrOr => "||".to_string(),
224 token::AndAnd => "&&".to_string(),
225 token::BinOp(op) => binop_to_string(op).to_string(),
226 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
228 /* Structural symbols */
229 token::At => "@".to_string(),
230 token::Dot => ".".to_string(),
231 token::DotDot => "..".to_string(),
232 token::DotDotDot => "...".to_string(),
233 token::Comma => ",".to_string(),
234 token::Semi => ";".to_string(),
235 token::Colon => ":".to_string(),
236 token::ModSep => "::".to_string(),
237 token::RArrow => "->".to_string(),
238 token::LArrow => "<-".to_string(),
239 token::FatArrow => "=>".to_string(),
240 token::OpenDelim(token::Paren) => "(".to_string(),
241 token::CloseDelim(token::Paren) => ")".to_string(),
242 token::OpenDelim(token::Bracket) => "[".to_string(),
243 token::CloseDelim(token::Bracket) => "]".to_string(),
244 token::OpenDelim(token::Brace) => "{".to_string(),
245 token::CloseDelim(token::Brace) => "}".to_string(),
246 token::OpenDelim(token::NoDelim) => " ".to_string(),
247 token::CloseDelim(token::NoDelim) => " ".to_string(),
248 token::Pound => "#".to_string(),
249 token::Dollar => "$".to_string(),
250 token::Question => "?".to_string(),
253 token::Literal(lit, suf) => {
254 let mut out = match lit {
255 token::Byte(b) => format!("b'{}'", b),
256 token::Char(c) => format!("'{}'", c),
257 token::Float(c) => c.to_string(),
258 token::Integer(c) => c.to_string(),
259 token::Str_(s) => format!("\"{}\"", s),
260 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
261 delim=repeat("#", n),
263 token::ByteStr(v) => format!("b\"{}\"", v),
264 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
265 delim=repeat("#", n),
269 if let Some(s) = suf {
270 out.push_str(&s.as_str())
276 /* Name components */
277 token::Ident(s) => s.to_string(),
278 token::Lifetime(s) => s.to_string(),
279 token::Underscore => "_".to_string(),
282 token::DocComment(s) => s.to_string(),
283 token::SubstNt(s) => format!("${}", s),
284 token::MatchNt(s, t) => format!("${}:{}", s, t),
285 token::Eof => "<eof>".to_string(),
286 token::Whitespace => " ".to_string(),
287 token::Comment => "/* */".to_string(),
288 token::Shebang(s) => format!("/* shebang: {}*/", s),
290 token::Interpolated(ref nt) => match **nt {
291 token::NtExpr(ref e) => expr_to_string(&e),
292 token::NtMeta(ref e) => meta_item_to_string(&e),
293 token::NtTy(ref e) => ty_to_string(&e),
294 token::NtPath(ref e) => path_to_string(&e),
295 token::NtItem(ref e) => item_to_string(&e),
296 token::NtBlock(ref e) => block_to_string(&e),
297 token::NtStmt(ref e) => stmt_to_string(&e),
298 token::NtPat(ref e) => pat_to_string(&e),
299 token::NtIdent(ref e) => ident_to_string(e.node),
300 token::NtTT(ref e) => tt_to_string(&e),
301 token::NtArm(ref e) => arm_to_string(&e),
302 token::NtImplItem(ref e) => impl_item_to_string(&e),
303 token::NtTraitItem(ref e) => trait_item_to_string(&e),
304 token::NtGenerics(ref e) => generics_to_string(&e),
305 token::NtWhereClause(ref e) => where_clause_to_string(&e),
306 token::NtArg(ref e) => arg_to_string(&e),
311 pub fn ty_to_string(ty: &ast::Ty) -> String {
312 to_string(|s| s.print_type(ty))
315 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
316 to_string(|s| s.print_bounds("", bounds))
319 pub fn pat_to_string(pat: &ast::Pat) -> String {
320 to_string(|s| s.print_pat(pat))
323 pub fn arm_to_string(arm: &ast::Arm) -> String {
324 to_string(|s| s.print_arm(arm))
327 pub fn expr_to_string(e: &ast::Expr) -> String {
328 to_string(|s| s.print_expr(e))
331 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
332 to_string(|s| s.print_lifetime(e))
335 pub fn tt_to_string(tt: &tokenstream::TokenTree) -> String {
336 to_string(|s| s.print_tt(tt))
339 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
340 to_string(|s| s.print_tts(tts))
343 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
344 to_string(|s| s.print_stmt(stmt))
347 pub fn attr_to_string(attr: &ast::Attribute) -> String {
348 to_string(|s| s.print_attribute(attr))
351 pub fn item_to_string(i: &ast::Item) -> String {
352 to_string(|s| s.print_item(i))
355 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
356 to_string(|s| s.print_impl_item(i))
359 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
360 to_string(|s| s.print_trait_item(i))
363 pub fn generics_to_string(generics: &ast::Generics) -> String {
364 to_string(|s| s.print_generics(generics))
367 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
368 to_string(|s| s.print_where_clause(i))
371 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
372 to_string(|s| s.print_fn_block_args(p))
375 pub fn path_to_string(p: &ast::Path) -> String {
376 to_string(|s| s.print_path(p, false, 0, false))
379 pub fn ident_to_string(id: ast::Ident) -> String {
380 to_string(|s| s.print_ident(id))
383 pub fn fun_to_string(decl: &ast::FnDecl,
384 unsafety: ast::Unsafety,
385 constness: ast::Constness,
387 generics: &ast::Generics)
391 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
392 generics, &ast::Visibility::Inherited)?;
393 s.end()?; // Close the head box
394 s.end() // Close the outer box
398 pub fn block_to_string(blk: &ast::Block) -> String {
400 // containing cbox, will be closed by print-block at }
401 s.cbox(INDENT_UNIT)?;
402 // head-ibox, will be closed by print-block after {
408 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
409 to_string(|s| s.print_meta_list_item(li))
412 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
413 to_string(|s| s.print_meta_item(mi))
416 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
417 to_string(|s| s.print_attribute(attr))
420 pub fn lit_to_string(l: &ast::Lit) -> String {
421 to_string(|s| s.print_literal(l))
424 pub fn variant_to_string(var: &ast::Variant) -> String {
425 to_string(|s| s.print_variant(var))
428 pub fn arg_to_string(arg: &ast::Arg) -> String {
429 to_string(|s| s.print_arg(arg, false))
432 pub fn mac_to_string(arg: &ast::Mac) -> String {
433 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
436 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
438 ast::Visibility::Public => format!("pub {}", s),
439 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
440 ast::Visibility::Restricted { ref path, .. } =>
441 format!("pub({}) {}", to_string(|s| s.print_path(path, false, 0, true)), s),
442 ast::Visibility::Inherited => s.to_string()
446 fn needs_parentheses(expr: &ast::Expr) -> bool {
448 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
449 ast::ExprKind::Closure(..) |
450 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
451 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
456 pub trait PrintState<'a> {
457 fn writer(&mut self) -> &mut pp::Printer<'a>;
458 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
459 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
460 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
461 fn literals(&self) -> &Option<Vec<comments::Literal>>;
463 fn word_space(&mut self, w: &str) -> io::Result<()> {
464 word(self.writer(), w)?;
468 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
470 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
472 fn is_begin(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::Begin(_) => true,
479 fn is_end(&mut self) -> bool {
480 match self.writer().last_token() {
481 pp::Token::End => true,
486 // is this the beginning of a line?
487 fn is_bol(&mut self) -> bool {
488 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
491 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
493 hardbreak(self.writer())?
499 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
500 self.boxes().push(b);
501 pp::rbox(self.writer(), u, b)
504 fn ibox(&mut self, u: usize) -> io::Result<()> {
505 self.boxes().push(pp::Breaks::Inconsistent);
506 pp::ibox(self.writer(), u)
509 fn end(&mut self) -> io::Result<()> {
510 self.boxes().pop().unwrap();
511 pp::end(self.writer())
514 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
515 where F: FnMut(&mut Self, &T) -> io::Result<()>,
518 let mut first = true;
520 if first { first = false; } else { self.word_space(",")?; }
526 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
527 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
529 let mut result = None;
531 if let &Some(ref lits) = self.literals()
533 while cur_lit < lits.len() {
534 let ltrl = (*lits)[cur_lit].clone();
535 if ltrl.pos > pos { break; }
544 self.cur_cmnt_and_lit().cur_lit = cur_lit;
548 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
549 while let Some(ref cmnt) = self.next_comment() {
551 self.print_comment(cmnt)?;
552 self.cur_cmnt_and_lit().cur_cmnt += 1;
560 fn print_comment(&mut self,
561 cmnt: &comments::Comment) -> io::Result<()> {
564 assert_eq!(cmnt.lines.len(), 1);
565 zerobreak(self.writer())?;
566 word(self.writer(), &cmnt.lines[0])?;
567 zerobreak(self.writer())
569 comments::Isolated => {
570 self.hardbreak_if_not_bol()?;
571 for line in &cmnt.lines {
572 // Don't print empty lines because they will end up as trailing
574 if !line.is_empty() {
575 word(self.writer(), &line[..])?;
577 hardbreak(self.writer())?;
581 comments::Trailing => {
583 word(self.writer(), " ")?;
585 if cmnt.lines.len() == 1 {
586 word(self.writer(), &cmnt.lines[0])?;
587 hardbreak(self.writer())
590 for line in &cmnt.lines {
591 if !line.is_empty() {
592 word(self.writer(), &line[..])?;
594 hardbreak(self.writer())?;
599 comments::BlankLine => {
600 // We need to do at least one, possibly two hardbreaks.
601 let is_semi = match self.writer().last_token() {
602 pp::Token::String(s, _) => ";" == s,
605 if is_semi || self.is_begin() || self.is_end() {
606 hardbreak(self.writer())?;
608 hardbreak(self.writer())
613 fn next_comment(&mut self) -> Option<comments::Comment> {
614 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
615 match *self.comments() {
617 if cur_cmnt < cmnts.len() {
618 Some(cmnts[cur_cmnt].clone())
627 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
628 self.maybe_print_comment(lit.span.lo)?;
629 match self.next_lit(lit.span.lo) {
631 return word(self.writer(), &(*ltrl).lit);
636 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
637 ast::LitKind::Byte(byte) => {
638 let mut res = String::from("b'");
639 res.extend(ascii::escape_default(byte).map(|c| c as char));
641 word(self.writer(), &res[..])
643 ast::LitKind::Char(ch) => {
644 let mut res = String::from("'");
645 res.extend(ch.escape_default());
647 word(self.writer(), &res[..])
649 ast::LitKind::Int(i, t) => {
651 ast::LitIntType::Signed(st) => {
652 word(self.writer(), &st.val_to_string(i as i128))
654 ast::LitIntType::Unsigned(ut) => {
655 word(self.writer(), &ut.val_to_string(i))
657 ast::LitIntType::Unsuffixed => {
658 word(self.writer(), &format!("{}", i))
662 ast::LitKind::Float(ref f, t) => {
669 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()),
670 ast::LitKind::Bool(val) => {
671 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
673 ast::LitKind::ByteStr(ref v) => {
674 let mut escaped: String = String::new();
675 for &ch in v.iter() {
676 escaped.extend(ascii::escape_default(ch)
677 .map(|c| c as char));
679 word(self.writer(), &format!("b\"{}\"", escaped))
684 fn print_string(&mut self, st: &str,
685 style: ast::StrStyle) -> io::Result<()> {
686 let st = match style {
687 ast::StrStyle::Cooked => {
688 (format!("\"{}\"", st.escape_default()))
690 ast::StrStyle::Raw(n) => {
691 (format!("r{delim}\"{string}\"{delim}",
692 delim=repeat("#", n),
696 word(self.writer(), &st[..])
699 fn print_inner_attributes(&mut self,
700 attrs: &[ast::Attribute]) -> io::Result<()> {
701 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
704 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
705 attrs: &[ast::Attribute])
707 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
710 fn print_outer_attributes(&mut self,
711 attrs: &[ast::Attribute]) -> io::Result<()> {
712 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
715 fn print_inner_attributes_inline(&mut self,
716 attrs: &[ast::Attribute]) -> io::Result<()> {
717 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
720 fn print_outer_attributes_inline(&mut self,
721 attrs: &[ast::Attribute]) -> io::Result<()> {
722 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
725 fn print_either_attributes(&mut self,
726 attrs: &[ast::Attribute],
727 kind: ast::AttrStyle,
729 trailing_hardbreak: bool) -> io::Result<()> {
732 if attr.style == kind {
733 self.print_attribute_inline(attr, is_inline)?;
740 if count > 0 && trailing_hardbreak && !is_inline {
741 self.hardbreak_if_not_bol()?;
746 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
747 self.print_attribute_inline(attr, false)
750 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
751 is_inline: bool) -> io::Result<()> {
753 self.hardbreak_if_not_bol()?;
755 self.maybe_print_comment(attr.span.lo)?;
756 if attr.is_sugared_doc {
757 word(self.writer(), &attr.value_str().unwrap().as_str())?;
758 hardbreak(self.writer())
761 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
762 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
764 self.print_meta_item(&attr.meta())?;
765 word(self.writer(), "]")
769 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
771 ast::NestedMetaItemKind::MetaItem(ref mi) => {
772 self.print_meta_item(mi)
774 ast::NestedMetaItemKind::Literal(ref lit) => {
775 self.print_literal(lit)
780 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
781 self.ibox(INDENT_UNIT)?;
783 ast::MetaItemKind::Word => {
784 word(self.writer(), &item.name.as_str())?;
786 ast::MetaItemKind::NameValue(ref value) => {
787 self.word_space(&item.name.as_str())?;
788 self.word_space("=")?;
789 self.print_literal(value)?;
791 ast::MetaItemKind::List(ref items) => {
792 word(self.writer(), &item.name.as_str())?;
794 self.commasep(Consistent,
796 |s, i| s.print_meta_list_item(&i))?;
803 fn space_if_not_bol(&mut self) -> io::Result<()> {
804 if !self.is_bol() { space(self.writer())?; }
808 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
811 impl<'a> PrintState<'a> for State<'a> {
812 fn writer(&mut self) -> &mut pp::Printer<'a> {
816 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
820 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
824 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
825 &mut self.cur_cmnt_and_lit
828 fn literals(&self) -> &Option<Vec<comments::Literal>> {
834 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
835 self.boxes.push(pp::Breaks::Consistent);
836 pp::cbox(&mut self.s, u)
839 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
840 word(&mut self.s, w)?;
844 pub fn head(&mut self, w: &str) -> io::Result<()> {
845 // outer-box is consistent
846 self.cbox(INDENT_UNIT)?;
847 // head-box is inconsistent
848 self.ibox(w.len() + 1)?;
849 // keyword that starts the head
856 pub fn bopen(&mut self) -> io::Result<()> {
857 word(&mut self.s, "{")?;
858 self.end() // close the head-box
861 pub fn bclose_(&mut self, span: syntax_pos::Span,
862 indented: usize) -> io::Result<()> {
863 self.bclose_maybe_open(span, indented, true)
865 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
866 indented: usize, close_box: bool) -> io::Result<()> {
867 self.maybe_print_comment(span.hi)?;
868 self.break_offset_if_not_bol(1, -(indented as isize))?;
869 word(&mut self.s, "}")?;
871 self.end()?; // close the outer-box
875 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
876 self.bclose_(span, INDENT_UNIT)
879 pub fn in_cbox(&self) -> bool {
880 match self.boxes.last() {
881 Some(&last_box) => last_box == pp::Breaks::Consistent,
886 pub fn break_offset_if_not_bol(&mut self, n: usize,
887 off: isize) -> io::Result<()> {
889 break_offset(&mut self.s, n, off)
891 if off != 0 && self.s.last_token().is_hardbreak_tok() {
892 // We do something pretty sketchy here: tuck the nonzero
893 // offset-adjustment we were going to deposit along with the
894 // break into the previous hardbreak.
895 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
901 // Synthesizes a comment that was not textually present in the original source
903 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
904 word(&mut self.s, "/*")?;
906 word(&mut self.s, &text[..])?;
908 word(&mut self.s, "*/")
913 pub fn commasep_cmnt<T, F, G>(&mut self,
917 mut get_span: G) -> io::Result<()> where
918 F: FnMut(&mut State, &T) -> io::Result<()>,
919 G: FnMut(&T) -> syntax_pos::Span,
922 let len = elts.len();
925 self.maybe_print_comment(get_span(elt).hi)?;
929 word(&mut self.s, ",")?;
930 self.maybe_print_trailing_comment(get_span(elt),
931 Some(get_span(&elts[i]).hi))?;
932 self.space_if_not_bol()?;
938 pub fn commasep_exprs(&mut self, b: Breaks,
939 exprs: &[P<ast::Expr>]) -> io::Result<()> {
940 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
943 pub fn print_mod(&mut self, _mod: &ast::Mod,
944 attrs: &[ast::Attribute]) -> io::Result<()> {
945 self.print_inner_attributes(attrs)?;
946 for item in &_mod.items {
947 self.print_item(&item)?;
952 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
953 attrs: &[ast::Attribute]) -> io::Result<()> {
954 self.print_inner_attributes(attrs)?;
955 for item in &nmod.items {
956 self.print_foreign_item(item)?;
961 pub fn print_opt_lifetime(&mut self,
962 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
963 if let Some(l) = *lifetime {
964 self.print_lifetime(&l)?;
970 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
971 self.maybe_print_comment(ty.span.lo)?;
974 ast::TyKind::Slice(ref ty) => {
975 word(&mut self.s, "[")?;
976 self.print_type(&ty)?;
977 word(&mut self.s, "]")?;
979 ast::TyKind::Ptr(ref mt) => {
980 word(&mut self.s, "*")?;
982 ast::Mutability::Mutable => self.word_nbsp("mut")?,
983 ast::Mutability::Immutable => self.word_nbsp("const")?,
985 self.print_type(&mt.ty)?;
987 ast::TyKind::Rptr(ref lifetime, ref mt) => {
988 word(&mut self.s, "&")?;
989 self.print_opt_lifetime(lifetime)?;
992 ast::TyKind::Never => {
993 word(&mut self.s, "!")?;
995 ast::TyKind::Tup(ref elts) => {
997 self.commasep(Inconsistent, &elts[..],
998 |s, ty| s.print_type(&ty))?;
1000 word(&mut self.s, ",")?;
1004 ast::TyKind::Paren(ref typ) => {
1006 self.print_type(&typ)?;
1009 ast::TyKind::BareFn(ref f) => {
1010 let generics = ast::Generics {
1011 lifetimes: f.lifetimes.clone(),
1012 ty_params: P::new(),
1013 where_clause: ast::WhereClause {
1014 id: ast::DUMMY_NODE_ID,
1015 predicates: Vec::new(),
1017 span: syntax_pos::DUMMY_SP,
1019 self.print_ty_fn(f.abi,
1025 ast::TyKind::Path(None, ref path) => {
1026 self.print_path(path, false, 0, false)?;
1028 ast::TyKind::Path(Some(ref qself), ref path) => {
1029 self.print_qpath(path, qself, false)?
1031 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
1032 self.print_type(&ty)?;
1033 self.print_bounds("+", &bounds[..])?;
1035 ast::TyKind::PolyTraitRef(ref bounds) => {
1036 self.print_bounds("", &bounds[..])?;
1038 ast::TyKind::ImplTrait(ref bounds) => {
1039 self.print_bounds("impl ", &bounds[..])?;
1041 ast::TyKind::Array(ref ty, ref v) => {
1042 word(&mut self.s, "[")?;
1043 self.print_type(&ty)?;
1044 word(&mut self.s, "; ")?;
1045 self.print_expr(&v)?;
1046 word(&mut self.s, "]")?;
1048 ast::TyKind::Typeof(ref e) => {
1049 word(&mut self.s, "typeof(")?;
1050 self.print_expr(&e)?;
1051 word(&mut self.s, ")")?;
1053 ast::TyKind::Infer => {
1054 word(&mut self.s, "_")?;
1056 ast::TyKind::ImplicitSelf => {
1057 word(&mut self.s, "Self")?;
1059 ast::TyKind::Mac(ref m) => {
1060 self.print_mac(m, token::Paren)?;
1066 pub fn print_foreign_item(&mut self,
1067 item: &ast::ForeignItem) -> io::Result<()> {
1068 self.hardbreak_if_not_bol()?;
1069 self.maybe_print_comment(item.span.lo)?;
1070 self.print_outer_attributes(&item.attrs)?;
1072 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1074 self.print_fn(decl, ast::Unsafety::Normal,
1075 ast::Constness::NotConst,
1076 Abi::Rust, Some(item.ident),
1077 generics, &item.vis)?;
1078 self.end()?; // end head-ibox
1079 word(&mut self.s, ";")?;
1080 self.end() // end the outer fn box
1082 ast::ForeignItemKind::Static(ref t, m) => {
1083 self.head(&visibility_qualified(&item.vis, "static"))?;
1085 self.word_space("mut")?;
1087 self.print_ident(item.ident)?;
1088 self.word_space(":")?;
1089 self.print_type(&t)?;
1090 word(&mut self.s, ";")?;
1091 self.end()?; // end the head-ibox
1092 self.end() // end the outer cbox
1097 fn print_associated_const(&mut self,
1100 default: Option<&ast::Expr>,
1101 vis: &ast::Visibility)
1104 word(&mut self.s, &visibility_qualified(vis, ""))?;
1105 self.word_space("const")?;
1106 self.print_ident(ident)?;
1107 self.word_space(":")?;
1108 self.print_type(ty)?;
1109 if let Some(expr) = default {
1110 space(&mut self.s)?;
1111 self.word_space("=")?;
1112 self.print_expr(expr)?;
1114 word(&mut self.s, ";")
1117 fn print_associated_type(&mut self,
1119 bounds: Option<&ast::TyParamBounds>,
1120 ty: Option<&ast::Ty>)
1122 self.word_space("type")?;
1123 self.print_ident(ident)?;
1124 if let Some(bounds) = bounds {
1125 self.print_bounds(":", bounds)?;
1127 if let Some(ty) = ty {
1128 space(&mut self.s)?;
1129 self.word_space("=")?;
1130 self.print_type(ty)?;
1132 word(&mut self.s, ";")
1135 /// Pretty-print an item
1136 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1137 self.hardbreak_if_not_bol()?;
1138 self.maybe_print_comment(item.span.lo)?;
1139 self.print_outer_attributes(&item.attrs)?;
1140 self.ann.pre(self, NodeItem(item))?;
1142 ast::ItemKind::ExternCrate(ref optional_path) => {
1143 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1144 if let Some(p) = *optional_path {
1145 let val = p.as_str();
1146 if val.contains("-") {
1147 self.print_string(&val, ast::StrStyle::Cooked)?;
1149 self.print_name(p)?;
1151 space(&mut self.s)?;
1152 word(&mut self.s, "as")?;
1153 space(&mut self.s)?;
1155 self.print_ident(item.ident)?;
1156 word(&mut self.s, ";")?;
1157 self.end()?; // end inner head-block
1158 self.end()?; // end outer head-block
1160 ast::ItemKind::Use(ref vp) => {
1161 self.head(&visibility_qualified(&item.vis, "use"))?;
1162 self.print_view_path(&vp)?;
1163 word(&mut self.s, ";")?;
1164 self.end()?; // end inner head-block
1165 self.end()?; // end outer head-block
1167 ast::ItemKind::Static(ref ty, m, ref expr) => {
1168 self.head(&visibility_qualified(&item.vis, "static"))?;
1169 if m == ast::Mutability::Mutable {
1170 self.word_space("mut")?;
1172 self.print_ident(item.ident)?;
1173 self.word_space(":")?;
1174 self.print_type(&ty)?;
1175 space(&mut self.s)?;
1176 self.end()?; // end the head-ibox
1178 self.word_space("=")?;
1179 self.print_expr(&expr)?;
1180 word(&mut self.s, ";")?;
1181 self.end()?; // end the outer cbox
1183 ast::ItemKind::Const(ref ty, ref expr) => {
1184 self.head(&visibility_qualified(&item.vis, "const"))?;
1185 self.print_ident(item.ident)?;
1186 self.word_space(":")?;
1187 self.print_type(&ty)?;
1188 space(&mut self.s)?;
1189 self.end()?; // end the head-ibox
1191 self.word_space("=")?;
1192 self.print_expr(&expr)?;
1193 word(&mut self.s, ";")?;
1194 self.end()?; // end the outer cbox
1196 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1207 word(&mut self.s, " ")?;
1208 self.print_block_with_attrs(&body, &item.attrs)?;
1210 ast::ItemKind::Mod(ref _mod) => {
1211 self.head(&visibility_qualified(&item.vis, "mod"))?;
1212 self.print_ident(item.ident)?;
1215 self.print_mod(_mod, &item.attrs)?;
1216 self.bclose(item.span)?;
1218 ast::ItemKind::ForeignMod(ref nmod) => {
1219 self.head("extern")?;
1220 self.word_nbsp(&nmod.abi.to_string())?;
1222 self.print_foreign_mod(nmod, &item.attrs)?;
1223 self.bclose(item.span)?;
1225 ast::ItemKind::Ty(ref ty, ref params) => {
1226 self.ibox(INDENT_UNIT)?;
1228 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1229 self.print_ident(item.ident)?;
1230 self.print_generics(params)?;
1231 self.end()?; // end the inner ibox
1233 self.print_where_clause(¶ms.where_clause)?;
1234 space(&mut self.s)?;
1235 self.word_space("=")?;
1236 self.print_type(&ty)?;
1237 word(&mut self.s, ";")?;
1238 self.end()?; // end the outer ibox
1240 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1241 self.print_enum_def(
1249 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1250 self.head(&visibility_qualified(&item.vis, "struct"))?;
1251 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1253 ast::ItemKind::Union(ref struct_def, ref generics) => {
1254 self.head(&visibility_qualified(&item.vis, "union"))?;
1255 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1257 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1259 self.print_visibility(&item.vis)?;
1260 self.print_unsafety(unsafety)?;
1261 self.word_nbsp("impl")?;
1262 self.print_trait_ref(trait_ref)?;
1263 space(&mut self.s)?;
1264 self.word_space("for")?;
1265 self.word_space("..")?;
1267 self.bclose(item.span)?;
1269 ast::ItemKind::Impl(unsafety,
1274 ref impl_items) => {
1276 self.print_visibility(&item.vis)?;
1277 self.print_unsafety(unsafety)?;
1278 self.word_nbsp("impl")?;
1280 if generics.is_parameterized() {
1281 self.print_generics(generics)?;
1282 space(&mut self.s)?;
1286 ast::ImplPolarity::Negative => {
1287 word(&mut self.s, "!")?;
1292 if let Some(ref t) = *opt_trait {
1293 self.print_trait_ref(t)?;
1294 space(&mut self.s)?;
1295 self.word_space("for")?;
1298 self.print_type(&ty)?;
1299 self.print_where_clause(&generics.where_clause)?;
1301 space(&mut self.s)?;
1303 self.print_inner_attributes(&item.attrs)?;
1304 for impl_item in impl_items {
1305 self.print_impl_item(impl_item)?;
1307 self.bclose(item.span)?;
1309 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1311 self.print_visibility(&item.vis)?;
1312 self.print_unsafety(unsafety)?;
1313 self.word_nbsp("trait")?;
1314 self.print_ident(item.ident)?;
1315 self.print_generics(generics)?;
1316 let mut real_bounds = Vec::with_capacity(bounds.len());
1317 for b in bounds.iter() {
1318 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1319 space(&mut self.s)?;
1320 self.word_space("for ?")?;
1321 self.print_trait_ref(&ptr.trait_ref)?;
1323 real_bounds.push(b.clone());
1326 self.print_bounds(":", &real_bounds[..])?;
1327 self.print_where_clause(&generics.where_clause)?;
1328 word(&mut self.s, " ")?;
1330 for trait_item in trait_items {
1331 self.print_trait_item(trait_item)?;
1333 self.bclose(item.span)?;
1335 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1336 self.print_visibility(&item.vis)?;
1337 self.print_path(&node.path, false, 0, false)?;
1338 word(&mut self.s, "! ")?;
1339 self.print_ident(item.ident)?;
1340 self.cbox(INDENT_UNIT)?;
1342 self.print_tts(&node.tts[..])?;
1344 word(&mut self.s, ";")?;
1348 self.ann.post(self, NodeItem(item))
1351 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1352 self.print_path(&t.path, false, 0, false)
1355 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1356 if !lifetimes.is_empty() {
1357 word(&mut self.s, "for<")?;
1358 let mut comma = false;
1359 for lifetime_def in lifetimes {
1361 self.word_space(",")?
1363 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1364 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1367 word(&mut self.s, ">")?;
1372 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1373 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1374 self.print_trait_ref(&t.trait_ref)
1377 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1378 generics: &ast::Generics, ident: ast::Ident,
1379 span: syntax_pos::Span,
1380 visibility: &ast::Visibility) -> io::Result<()> {
1381 self.head(&visibility_qualified(visibility, "enum"))?;
1382 self.print_ident(ident)?;
1383 self.print_generics(generics)?;
1384 self.print_where_clause(&generics.where_clause)?;
1385 space(&mut self.s)?;
1386 self.print_variants(&enum_definition.variants, span)
1389 pub fn print_variants(&mut self,
1390 variants: &[ast::Variant],
1391 span: syntax_pos::Span) -> io::Result<()> {
1394 self.space_if_not_bol()?;
1395 self.maybe_print_comment(v.span.lo)?;
1396 self.print_outer_attributes(&v.node.attrs)?;
1397 self.ibox(INDENT_UNIT)?;
1398 self.print_variant(v)?;
1399 word(&mut self.s, ",")?;
1401 self.maybe_print_trailing_comment(v.span, None)?;
1406 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1408 ast::Visibility::Public => self.word_nbsp("pub"),
1409 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1410 ast::Visibility::Restricted { ref path, .. } => {
1411 let path = to_string(|s| s.print_path(path, false, 0, true));
1412 self.word_nbsp(&format!("pub({})", path))
1414 ast::Visibility::Inherited => Ok(())
1418 pub fn print_struct(&mut self,
1419 struct_def: &ast::VariantData,
1420 generics: &ast::Generics,
1422 span: syntax_pos::Span,
1423 print_finalizer: bool) -> io::Result<()> {
1424 self.print_ident(ident)?;
1425 self.print_generics(generics)?;
1426 if !struct_def.is_struct() {
1427 if struct_def.is_tuple() {
1430 Inconsistent, struct_def.fields(),
1432 s.maybe_print_comment(field.span.lo)?;
1433 s.print_outer_attributes(&field.attrs)?;
1434 s.print_visibility(&field.vis)?;
1435 s.print_type(&field.ty)
1440 self.print_where_clause(&generics.where_clause)?;
1441 if print_finalizer {
1442 word(&mut self.s, ";")?;
1445 self.end() // close the outer-box
1447 self.print_where_clause(&generics.where_clause)?;
1450 self.hardbreak_if_not_bol()?;
1452 for field in struct_def.fields() {
1453 self.hardbreak_if_not_bol()?;
1454 self.maybe_print_comment(field.span.lo)?;
1455 self.print_outer_attributes(&field.attrs)?;
1456 self.print_visibility(&field.vis)?;
1457 self.print_ident(field.ident.unwrap())?;
1458 self.word_nbsp(":")?;
1459 self.print_type(&field.ty)?;
1460 word(&mut self.s, ",")?;
1467 /// This doesn't deserve to be called "pretty" printing, but it should be
1468 /// meaning-preserving. A quick hack that might help would be to look at the
1469 /// spans embedded in the TTs to decide where to put spaces and newlines.
1470 /// But it'd be better to parse these according to the grammar of the
1471 /// appropriate macro, transcribe back into the grammar we just parsed from,
1472 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1473 /// expression arguments as expressions). It can be done! I think.
1474 pub fn print_tt(&mut self, tt: &tokenstream::TokenTree) -> io::Result<()> {
1476 TokenTree::Token(_, ref tk) => {
1477 word(&mut self.s, &token_to_string(tk))?;
1479 parse::token::DocComment(..) => {
1480 hardbreak(&mut self.s)
1485 TokenTree::Delimited(_, ref delimed) => {
1486 word(&mut self.s, &token_to_string(&delimed.open_token()))?;
1487 space(&mut self.s)?;
1488 self.print_tts(&delimed.tts)?;
1489 space(&mut self.s)?;
1490 word(&mut self.s, &token_to_string(&delimed.close_token()))
1492 TokenTree::Sequence(_, ref seq) => {
1493 word(&mut self.s, "$(")?;
1494 for tt_elt in &seq.tts {
1495 self.print_tt(tt_elt)?;
1497 word(&mut self.s, ")")?;
1498 if let Some(ref tk) = seq.separator {
1499 word(&mut self.s, &token_to_string(tk))?;
1502 tokenstream::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),
1503 tokenstream::KleeneOp::OneOrMore => word(&mut self.s, "+"),
1509 pub fn print_tts(&mut self, tts: &[tokenstream::TokenTree]) -> io::Result<()> {
1511 for (i, tt) in tts.iter().enumerate() {
1513 space(&mut self.s)?;
1520 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1522 let generics = ast::Generics::default();
1523 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1524 match v.node.disr_expr {
1526 space(&mut self.s)?;
1527 self.word_space("=")?;
1534 pub fn print_method_sig(&mut self,
1537 vis: &ast::Visibility)
1539 self.print_fn(&m.decl,
1548 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1550 self.ann.pre(self, NodeSubItem(ti.id))?;
1551 self.hardbreak_if_not_bol()?;
1552 self.maybe_print_comment(ti.span.lo)?;
1553 self.print_outer_attributes(&ti.attrs)?;
1555 ast::TraitItemKind::Const(ref ty, ref default) => {
1556 self.print_associated_const(ti.ident, &ty,
1557 default.as_ref().map(|expr| &**expr),
1558 &ast::Visibility::Inherited)?;
1560 ast::TraitItemKind::Method(ref sig, ref body) => {
1564 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1565 if let Some(ref body) = *body {
1567 self.print_block_with_attrs(body, &ti.attrs)?;
1569 word(&mut self.s, ";")?;
1572 ast::TraitItemKind::Type(ref bounds, ref default) => {
1573 self.print_associated_type(ti.ident, Some(bounds),
1574 default.as_ref().map(|ty| &**ty))?;
1576 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1577 // code copied from ItemKind::Mac:
1578 self.print_path(&node.path, false, 0, false)?;
1579 word(&mut self.s, "! ")?;
1580 self.cbox(INDENT_UNIT)?;
1582 self.print_tts(&node.tts[..])?;
1584 word(&mut self.s, ";")?;
1588 self.ann.post(self, NodeSubItem(ti.id))
1591 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1592 self.ann.pre(self, NodeSubItem(ii.id))?;
1593 self.hardbreak_if_not_bol()?;
1594 self.maybe_print_comment(ii.span.lo)?;
1595 self.print_outer_attributes(&ii.attrs)?;
1596 if let ast::Defaultness::Default = ii.defaultness {
1597 self.word_nbsp("default")?;
1600 ast::ImplItemKind::Const(ref ty, ref expr) => {
1601 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1603 ast::ImplItemKind::Method(ref sig, ref body) => {
1605 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1607 self.print_block_with_attrs(body, &ii.attrs)?;
1609 ast::ImplItemKind::Type(ref ty) => {
1610 self.print_associated_type(ii.ident, None, Some(ty))?;
1612 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1613 // code copied from ItemKind::Mac:
1614 self.print_path(&node.path, false, 0, false)?;
1615 word(&mut self.s, "! ")?;
1616 self.cbox(INDENT_UNIT)?;
1618 self.print_tts(&node.tts[..])?;
1620 word(&mut self.s, ";")?;
1624 self.ann.post(self, NodeSubItem(ii.id))
1627 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1628 self.maybe_print_comment(st.span.lo)?;
1630 ast::StmtKind::Local(ref loc) => {
1631 self.print_outer_attributes(&loc.attrs)?;
1632 self.space_if_not_bol()?;
1633 self.ibox(INDENT_UNIT)?;
1634 self.word_nbsp("let")?;
1636 self.ibox(INDENT_UNIT)?;
1637 self.print_local_decl(&loc)?;
1639 if let Some(ref init) = loc.init {
1641 self.word_space("=")?;
1642 self.print_expr(&init)?;
1644 word(&mut self.s, ";")?;
1647 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1648 ast::StmtKind::Expr(ref expr) => {
1649 self.space_if_not_bol()?;
1650 self.print_expr_outer_attr_style(&expr, false)?;
1651 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1652 word(&mut self.s, ";")?;
1655 ast::StmtKind::Semi(ref expr) => {
1656 self.space_if_not_bol()?;
1657 self.print_expr_outer_attr_style(&expr, false)?;
1658 word(&mut self.s, ";")?;
1660 ast::StmtKind::Mac(ref mac) => {
1661 let (ref mac, style, ref attrs) = **mac;
1662 self.space_if_not_bol()?;
1663 self.print_outer_attributes(&attrs)?;
1664 let delim = match style {
1665 ast::MacStmtStyle::Braces => token::Brace,
1668 self.print_mac(&mac, delim)?;
1669 if style == ast::MacStmtStyle::Semicolon {
1670 word(&mut self.s, ";")?;
1674 self.maybe_print_trailing_comment(st.span, None)
1677 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1678 self.print_block_with_attrs(blk, &[])
1681 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1682 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1685 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1686 attrs: &[ast::Attribute])
1688 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1691 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1692 indented: usize) -> io::Result<()> {
1693 self.print_block_maybe_unclosed(blk, indented, &[], false)
1696 pub fn print_block_with_attrs(&mut self,
1698 attrs: &[ast::Attribute]) -> io::Result<()> {
1699 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1702 pub fn print_block_maybe_unclosed(&mut self,
1705 attrs: &[ast::Attribute],
1706 close_box: bool) -> io::Result<()> {
1708 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1709 BlockCheckMode::Default => ()
1711 self.maybe_print_comment(blk.span.lo)?;
1712 self.ann.pre(self, NodeBlock(blk))?;
1715 self.print_inner_attributes(attrs)?;
1717 for (i, st) in blk.stmts.iter().enumerate() {
1719 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1720 self.maybe_print_comment(st.span.lo)?;
1721 self.space_if_not_bol()?;
1722 self.print_expr_outer_attr_style(&expr, false)?;
1723 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1725 _ => self.print_stmt(st)?,
1729 self.bclose_maybe_open(blk.span, indented, close_box)?;
1730 self.ann.post(self, NodeBlock(blk))
1733 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1737 // "another else-if"
1738 ast::ExprKind::If(ref i, ref then, ref e) => {
1739 self.cbox(INDENT_UNIT - 1)?;
1741 word(&mut self.s, " else if ")?;
1742 self.print_expr(&i)?;
1743 space(&mut self.s)?;
1744 self.print_block(&then)?;
1745 self.print_else(e.as_ref().map(|e| &**e))
1747 // "another else-if-let"
1748 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1749 self.cbox(INDENT_UNIT - 1)?;
1751 word(&mut self.s, " else if let ")?;
1752 self.print_pat(&pat)?;
1753 space(&mut self.s)?;
1754 self.word_space("=")?;
1755 self.print_expr(&expr)?;
1756 space(&mut self.s)?;
1757 self.print_block(&then)?;
1758 self.print_else(e.as_ref().map(|e| &**e))
1761 ast::ExprKind::Block(ref b) => {
1762 self.cbox(INDENT_UNIT - 1)?;
1764 word(&mut self.s, " else ")?;
1765 self.print_block(&b)
1767 // BLEAH, constraints would be great here
1769 panic!("print_if saw if with weird alternative");
1777 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1778 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1780 self.print_expr(test)?;
1781 space(&mut self.s)?;
1782 self.print_block(blk)?;
1783 self.print_else(elseopt)
1786 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1787 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1788 self.head("if let")?;
1789 self.print_pat(pat)?;
1790 space(&mut self.s)?;
1791 self.word_space("=")?;
1792 self.print_expr(expr)?;
1793 space(&mut self.s)?;
1794 self.print_block(blk)?;
1795 self.print_else(elseopt)
1798 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1800 self.print_path(&m.node.path, false, 0, false)?;
1801 word(&mut self.s, "!")?;
1803 token::Paren => self.popen()?,
1804 token::Bracket => word(&mut self.s, "[")?,
1809 token::NoDelim => {}
1811 self.print_tts(&m.node.tts)?;
1813 token::Paren => self.pclose(),
1814 token::Bracket => word(&mut self.s, "]"),
1815 token::Brace => self.bclose(m.span),
1816 token::NoDelim => Ok(()),
1821 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1823 self.commasep_exprs(Inconsistent, args)?;
1827 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1828 binop: ast::BinOp) -> bool {
1829 match sub_expr.node {
1830 ast::ExprKind::Binary(ref sub_op, _, _) => {
1831 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1832 AssocOp::from_ast_binop(binop.node).precedence() {
1842 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1843 let needs_par = needs_parentheses(expr);
1847 self.print_expr(expr)?;
1854 fn print_expr_in_place(&mut self,
1856 expr: &ast::Expr) -> io::Result<()> {
1857 self.print_expr_maybe_paren(place)?;
1858 space(&mut self.s)?;
1859 self.word_space("<-")?;
1860 self.print_expr_maybe_paren(expr)
1863 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1864 attrs: &[Attribute]) -> io::Result<()> {
1865 self.ibox(INDENT_UNIT)?;
1866 word(&mut self.s, "[")?;
1867 self.print_inner_attributes_inline(attrs)?;
1868 self.commasep_exprs(Inconsistent, &exprs[..])?;
1869 word(&mut self.s, "]")?;
1873 fn print_expr_repeat(&mut self,
1874 element: &ast::Expr,
1876 attrs: &[Attribute]) -> io::Result<()> {
1877 self.ibox(INDENT_UNIT)?;
1878 word(&mut self.s, "[")?;
1879 self.print_inner_attributes_inline(attrs)?;
1880 self.print_expr(element)?;
1881 self.word_space(";")?;
1882 self.print_expr(count)?;
1883 word(&mut self.s, "]")?;
1887 fn print_expr_struct(&mut self,
1889 fields: &[ast::Field],
1890 wth: &Option<P<ast::Expr>>,
1891 attrs: &[Attribute]) -> io::Result<()> {
1892 self.print_path(path, true, 0, false)?;
1893 word(&mut self.s, "{")?;
1894 self.print_inner_attributes_inline(attrs)?;
1899 s.ibox(INDENT_UNIT)?;
1900 if !field.is_shorthand {
1901 s.print_ident(field.ident.node)?;
1904 s.print_expr(&field.expr)?;
1910 self.ibox(INDENT_UNIT)?;
1911 if !fields.is_empty() {
1912 word(&mut self.s, ",")?;
1913 space(&mut self.s)?;
1915 word(&mut self.s, "..")?;
1916 self.print_expr(&expr)?;
1919 _ => if !fields.is_empty() {
1920 word(&mut self.s, ",")?
1923 word(&mut self.s, "}")?;
1927 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1928 attrs: &[Attribute]) -> io::Result<()> {
1930 self.print_inner_attributes_inline(attrs)?;
1931 self.commasep_exprs(Inconsistent, &exprs[..])?;
1932 if exprs.len() == 1 {
1933 word(&mut self.s, ",")?;
1938 fn print_expr_call(&mut self,
1940 args: &[P<ast::Expr>]) -> io::Result<()> {
1941 self.print_expr_maybe_paren(func)?;
1942 self.print_call_post(args)
1945 fn print_expr_method_call(&mut self,
1946 ident: ast::SpannedIdent,
1948 args: &[P<ast::Expr>]) -> io::Result<()> {
1949 let base_args = &args[1..];
1950 self.print_expr(&args[0])?;
1951 word(&mut self.s, ".")?;
1952 self.print_ident(ident.node)?;
1953 if !tys.is_empty() {
1954 word(&mut self.s, "::<")?;
1955 self.commasep(Inconsistent, tys,
1956 |s, ty| s.print_type(&ty))?;
1957 word(&mut self.s, ">")?;
1959 self.print_call_post(base_args)
1962 fn print_expr_binary(&mut self,
1965 rhs: &ast::Expr) -> io::Result<()> {
1966 if self.check_expr_bin_needs_paren(lhs, op) {
1967 self.print_expr_maybe_paren(lhs)?;
1969 self.print_expr(lhs)?;
1971 space(&mut self.s)?;
1972 self.word_space(op.node.to_string())?;
1973 if self.check_expr_bin_needs_paren(rhs, op) {
1974 self.print_expr_maybe_paren(rhs)
1976 self.print_expr(rhs)
1980 fn print_expr_unary(&mut self,
1982 expr: &ast::Expr) -> io::Result<()> {
1983 word(&mut self.s, ast::UnOp::to_string(op))?;
1984 self.print_expr_maybe_paren(expr)
1987 fn print_expr_addr_of(&mut self,
1988 mutability: ast::Mutability,
1989 expr: &ast::Expr) -> io::Result<()> {
1990 word(&mut self.s, "&")?;
1991 self.print_mutability(mutability)?;
1992 self.print_expr_maybe_paren(expr)
1995 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1996 self.print_expr_outer_attr_style(expr, true)
1999 fn print_expr_outer_attr_style(&mut self,
2001 is_inline: bool) -> io::Result<()> {
2002 self.maybe_print_comment(expr.span.lo)?;
2004 let attrs = &expr.attrs;
2006 self.print_outer_attributes_inline(attrs)?;
2008 self.print_outer_attributes(attrs)?;
2011 self.ibox(INDENT_UNIT)?;
2012 self.ann.pre(self, NodeExpr(expr))?;
2014 ast::ExprKind::Box(ref expr) => {
2015 self.word_space("box")?;
2016 self.print_expr(expr)?;
2018 ast::ExprKind::InPlace(ref place, ref expr) => {
2019 self.print_expr_in_place(place, expr)?;
2021 ast::ExprKind::Array(ref exprs) => {
2022 self.print_expr_vec(&exprs[..], attrs)?;
2024 ast::ExprKind::Repeat(ref element, ref count) => {
2025 self.print_expr_repeat(&element, &count, attrs)?;
2027 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2028 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2030 ast::ExprKind::Tup(ref exprs) => {
2031 self.print_expr_tup(&exprs[..], attrs)?;
2033 ast::ExprKind::Call(ref func, ref args) => {
2034 self.print_expr_call(&func, &args[..])?;
2036 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2037 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2039 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2040 self.print_expr_binary(op, &lhs, &rhs)?;
2042 ast::ExprKind::Unary(op, ref expr) => {
2043 self.print_expr_unary(op, &expr)?;
2045 ast::ExprKind::AddrOf(m, ref expr) => {
2046 self.print_expr_addr_of(m, &expr)?;
2048 ast::ExprKind::Lit(ref lit) => {
2049 self.print_literal(&lit)?;
2051 ast::ExprKind::Cast(ref expr, ref ty) => {
2052 if let ast::ExprKind::Cast(..) = expr.node {
2053 self.print_expr(&expr)?;
2055 self.print_expr_maybe_paren(&expr)?;
2057 space(&mut self.s)?;
2058 self.word_space("as")?;
2059 self.print_type(&ty)?;
2061 ast::ExprKind::Type(ref expr, ref ty) => {
2062 self.print_expr(&expr)?;
2063 self.word_space(":")?;
2064 self.print_type(&ty)?;
2066 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2067 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2069 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2070 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2072 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2073 if let Some(ident) = opt_ident {
2074 self.print_ident(ident.node)?;
2075 self.word_space(":")?;
2077 self.head("while")?;
2078 self.print_expr(&test)?;
2079 space(&mut self.s)?;
2080 self.print_block_with_attrs(&blk, attrs)?;
2082 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2083 if let Some(ident) = opt_ident {
2084 self.print_ident(ident.node)?;
2085 self.word_space(":")?;
2087 self.head("while let")?;
2088 self.print_pat(&pat)?;
2089 space(&mut self.s)?;
2090 self.word_space("=")?;
2091 self.print_expr(&expr)?;
2092 space(&mut self.s)?;
2093 self.print_block_with_attrs(&blk, attrs)?;
2095 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2096 if let Some(ident) = opt_ident {
2097 self.print_ident(ident.node)?;
2098 self.word_space(":")?;
2101 self.print_pat(&pat)?;
2102 space(&mut self.s)?;
2103 self.word_space("in")?;
2104 self.print_expr(&iter)?;
2105 space(&mut self.s)?;
2106 self.print_block_with_attrs(&blk, attrs)?;
2108 ast::ExprKind::Loop(ref blk, opt_ident) => {
2109 if let Some(ident) = opt_ident {
2110 self.print_ident(ident.node)?;
2111 self.word_space(":")?;
2114 space(&mut self.s)?;
2115 self.print_block_with_attrs(&blk, attrs)?;
2117 ast::ExprKind::Match(ref expr, ref arms) => {
2118 self.cbox(INDENT_UNIT)?;
2120 self.word_nbsp("match")?;
2121 self.print_expr(&expr)?;
2122 space(&mut self.s)?;
2124 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2126 self.print_arm(arm)?;
2128 self.bclose_(expr.span, INDENT_UNIT)?;
2130 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2131 self.print_capture_clause(capture_clause)?;
2133 self.print_fn_block_args(&decl)?;
2134 space(&mut self.s)?;
2135 self.print_expr(body)?;
2136 self.end()?; // need to close a box
2138 // a box will be closed by print_expr, but we didn't want an overall
2139 // wrapper so we closed the corresponding opening. so create an
2140 // empty box to satisfy the close.
2143 ast::ExprKind::Block(ref blk) => {
2144 // containing cbox, will be closed by print-block at }
2145 self.cbox(INDENT_UNIT)?;
2146 // head-box, will be closed by print-block after {
2148 self.print_block_with_attrs(&blk, attrs)?;
2150 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2151 self.print_expr(&lhs)?;
2152 space(&mut self.s)?;
2153 self.word_space("=")?;
2154 self.print_expr(&rhs)?;
2156 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2157 self.print_expr(&lhs)?;
2158 space(&mut self.s)?;
2159 word(&mut self.s, op.node.to_string())?;
2160 self.word_space("=")?;
2161 self.print_expr(&rhs)?;
2163 ast::ExprKind::Field(ref expr, id) => {
2164 self.print_expr(&expr)?;
2165 word(&mut self.s, ".")?;
2166 self.print_ident(id.node)?;
2168 ast::ExprKind::TupField(ref expr, id) => {
2169 self.print_expr(&expr)?;
2170 word(&mut self.s, ".")?;
2171 self.print_usize(id.node)?;
2173 ast::ExprKind::Index(ref expr, ref index) => {
2174 self.print_expr(&expr)?;
2175 word(&mut self.s, "[")?;
2176 self.print_expr(&index)?;
2177 word(&mut self.s, "]")?;
2179 ast::ExprKind::Range(ref start, ref end, limits) => {
2180 if let &Some(ref e) = start {
2181 self.print_expr(&e)?;
2183 if limits == ast::RangeLimits::HalfOpen {
2184 word(&mut self.s, "..")?;
2186 word(&mut self.s, "...")?;
2188 if let &Some(ref e) = end {
2189 self.print_expr(&e)?;
2192 ast::ExprKind::Path(None, ref path) => {
2193 self.print_path(path, true, 0, false)?
2195 ast::ExprKind::Path(Some(ref qself), ref path) => {
2196 self.print_qpath(path, qself, true)?
2198 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2199 word(&mut self.s, "break")?;
2200 space(&mut self.s)?;
2201 if let Some(ident) = opt_ident {
2202 self.print_ident(ident.node)?;
2203 space(&mut self.s)?;
2205 if let Some(ref expr) = *opt_expr {
2206 self.print_expr(expr)?;
2207 space(&mut self.s)?;
2210 ast::ExprKind::Continue(opt_ident) => {
2211 word(&mut self.s, "continue")?;
2212 space(&mut self.s)?;
2213 if let Some(ident) = opt_ident {
2214 self.print_ident(ident.node)?;
2218 ast::ExprKind::Ret(ref result) => {
2219 word(&mut self.s, "return")?;
2222 word(&mut self.s, " ")?;
2223 self.print_expr(&expr)?;
2228 ast::ExprKind::InlineAsm(ref a) => {
2229 word(&mut self.s, "asm!")?;
2231 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2232 self.word_space(":")?;
2234 self.commasep(Inconsistent, &a.outputs, |s, out| {
2235 let constraint = out.constraint.as_str();
2236 let mut ch = constraint.chars();
2238 Some('=') if out.is_rw => {
2239 s.print_string(&format!("+{}", ch.as_str()),
2240 ast::StrStyle::Cooked)?
2242 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2245 s.print_expr(&out.expr)?;
2249 space(&mut self.s)?;
2250 self.word_space(":")?;
2252 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2253 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2259 space(&mut self.s)?;
2260 self.word_space(":")?;
2262 self.commasep(Inconsistent, &a.clobbers,
2264 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2268 let mut options = vec![];
2270 options.push("volatile");
2273 options.push("alignstack");
2275 if a.dialect == ast::AsmDialect::Intel {
2276 options.push("intel");
2279 if !options.is_empty() {
2280 space(&mut self.s)?;
2281 self.word_space(":")?;
2282 self.commasep(Inconsistent, &options,
2284 s.print_string(co, ast::StrStyle::Cooked)?;
2291 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2292 ast::ExprKind::Paren(ref e) => {
2294 self.print_inner_attributes_inline(attrs)?;
2295 self.print_expr(&e)?;
2298 ast::ExprKind::Try(ref e) => {
2299 self.print_expr(e)?;
2300 word(&mut self.s, "?")?
2303 self.ann.post(self, NodeExpr(expr))?;
2307 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2308 self.print_pat(&loc.pat)?;
2309 if let Some(ref ty) = loc.ty {
2310 self.word_space(":")?;
2311 self.print_type(&ty)?;
2316 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2317 word(&mut self.s, &ident.name.as_str())?;
2318 self.ann.post(self, NodeIdent(&ident))
2321 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2322 word(&mut self.s, &i.to_string())
2325 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2326 word(&mut self.s, &name.as_str())?;
2327 self.ann.post(self, NodeName(&name))
2330 pub fn print_for_decl(&mut self, loc: &ast::Local,
2331 coll: &ast::Expr) -> io::Result<()> {
2332 self.print_local_decl(loc)?;
2333 space(&mut self.s)?;
2334 self.word_space("in")?;
2335 self.print_expr(coll)
2338 fn print_path(&mut self,
2340 colons_before_params: bool,
2342 defaults_to_global: bool)
2345 self.maybe_print_comment(path.span.lo)?;
2347 let mut segments = path.segments[..path.segments.len()-depth].iter();
2348 if defaults_to_global && path.is_global() {
2351 for (i, segment) in segments.enumerate() {
2353 word(&mut self.s, "::")?
2355 if segment.identifier.name != keywords::CrateRoot.name() &&
2356 segment.identifier.name != "$crate" {
2357 self.print_ident(segment.identifier)?;
2358 if let Some(ref parameters) = segment.parameters {
2359 self.print_path_parameters(parameters, colons_before_params)?;
2367 fn print_qpath(&mut self,
2370 colons_before_params: bool)
2373 word(&mut self.s, "<")?;
2374 self.print_type(&qself.ty)?;
2375 if qself.position > 0 {
2376 space(&mut self.s)?;
2377 self.word_space("as")?;
2378 let depth = path.segments.len() - qself.position;
2379 self.print_path(&path, false, depth, false)?;
2381 word(&mut self.s, ">")?;
2382 word(&mut self.s, "::")?;
2383 let item_segment = path.segments.last().unwrap();
2384 self.print_ident(item_segment.identifier)?;
2385 match item_segment.parameters {
2386 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2391 fn print_path_parameters(&mut self,
2392 parameters: &ast::PathParameters,
2393 colons_before_params: bool)
2396 if colons_before_params {
2397 word(&mut self.s, "::")?
2401 ast::PathParameters::AngleBracketed(ref data) => {
2402 word(&mut self.s, "<")?;
2404 let mut comma = false;
2405 for lifetime in &data.lifetimes {
2407 self.word_space(",")?
2409 self.print_lifetime(lifetime)?;
2413 if !data.types.is_empty() {
2415 self.word_space(",")?
2420 |s, ty| s.print_type(&ty))?;
2424 for binding in data.bindings.iter() {
2426 self.word_space(",")?
2428 self.print_ident(binding.ident)?;
2429 space(&mut self.s)?;
2430 self.word_space("=")?;
2431 self.print_type(&binding.ty)?;
2435 word(&mut self.s, ">")?
2438 ast::PathParameters::Parenthesized(ref data) => {
2439 word(&mut self.s, "(")?;
2443 |s, ty| s.print_type(&ty))?;
2444 word(&mut self.s, ")")?;
2446 if let Some(ref ty) = data.output {
2447 self.space_if_not_bol()?;
2448 self.word_space("->")?;
2449 self.print_type(&ty)?;
2457 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2458 self.maybe_print_comment(pat.span.lo)?;
2459 self.ann.pre(self, NodePat(pat))?;
2460 /* Pat isn't normalized, but the beauty of it
2461 is that it doesn't matter */
2463 PatKind::Wild => word(&mut self.s, "_")?,
2464 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2465 match binding_mode {
2466 ast::BindingMode::ByRef(mutbl) => {
2467 self.word_nbsp("ref")?;
2468 self.print_mutability(mutbl)?;
2470 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2471 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2472 self.word_nbsp("mut")?;
2475 self.print_ident(path1.node)?;
2476 if let Some(ref p) = *sub {
2477 word(&mut self.s, "@")?;
2478 self.print_pat(&p)?;
2481 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2482 self.print_path(path, true, 0, false)?;
2484 if let Some(ddpos) = ddpos {
2485 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2487 self.word_space(",")?;
2489 word(&mut self.s, "..")?;
2490 if ddpos != elts.len() {
2491 word(&mut self.s, ",")?;
2492 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2495 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2499 PatKind::Path(None, ref path) => {
2500 self.print_path(path, true, 0, false)?;
2502 PatKind::Path(Some(ref qself), ref path) => {
2503 self.print_qpath(path, qself, false)?;
2505 PatKind::Struct(ref path, ref fields, etc) => {
2506 self.print_path(path, true, 0, false)?;
2508 self.word_space("{")?;
2510 Consistent, &fields[..],
2512 s.cbox(INDENT_UNIT)?;
2513 if !f.node.is_shorthand {
2514 s.print_ident(f.node.ident)?;
2517 s.print_pat(&f.node.pat)?;
2520 |f| f.node.pat.span)?;
2522 if !fields.is_empty() { self.word_space(",")?; }
2523 word(&mut self.s, "..")?;
2525 space(&mut self.s)?;
2526 word(&mut self.s, "}")?;
2528 PatKind::Tuple(ref elts, ddpos) => {
2530 if let Some(ddpos) = ddpos {
2531 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2533 self.word_space(",")?;
2535 word(&mut self.s, "..")?;
2536 if ddpos != elts.len() {
2537 word(&mut self.s, ",")?;
2538 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2541 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2542 if elts.len() == 1 {
2543 word(&mut self.s, ",")?;
2548 PatKind::Box(ref inner) => {
2549 word(&mut self.s, "box ")?;
2550 self.print_pat(&inner)?;
2552 PatKind::Ref(ref inner, mutbl) => {
2553 word(&mut self.s, "&")?;
2554 if mutbl == ast::Mutability::Mutable {
2555 word(&mut self.s, "mut ")?;
2557 self.print_pat(&inner)?;
2559 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2560 PatKind::Range(ref begin, ref end) => {
2561 self.print_expr(&begin)?;
2562 space(&mut self.s)?;
2563 word(&mut self.s, "...")?;
2564 self.print_expr(&end)?;
2566 PatKind::Slice(ref before, ref slice, ref after) => {
2567 word(&mut self.s, "[")?;
2568 self.commasep(Inconsistent,
2570 |s, p| s.print_pat(&p))?;
2571 if let Some(ref p) = *slice {
2572 if !before.is_empty() { self.word_space(",")?; }
2573 if p.node != PatKind::Wild {
2574 self.print_pat(&p)?;
2576 word(&mut self.s, "..")?;
2577 if !after.is_empty() { self.word_space(",")?; }
2579 self.commasep(Inconsistent,
2581 |s, p| s.print_pat(&p))?;
2582 word(&mut self.s, "]")?;
2584 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2586 self.ann.post(self, NodePat(pat))
2589 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2590 // I have no idea why this check is necessary, but here it
2592 if arm.attrs.is_empty() {
2593 space(&mut self.s)?;
2595 self.cbox(INDENT_UNIT)?;
2597 self.maybe_print_comment(arm.pats[0].span.lo)?;
2598 self.print_outer_attributes(&arm.attrs)?;
2599 let mut first = true;
2600 for p in &arm.pats {
2604 space(&mut self.s)?;
2605 self.word_space("|")?;
2607 self.print_pat(&p)?;
2609 space(&mut self.s)?;
2610 if let Some(ref e) = arm.guard {
2611 self.word_space("if")?;
2612 self.print_expr(&e)?;
2613 space(&mut self.s)?;
2615 self.word_space("=>")?;
2617 match arm.body.node {
2618 ast::ExprKind::Block(ref blk) => {
2619 // the block will close the pattern's ibox
2620 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2622 // If it is a user-provided unsafe block, print a comma after it
2623 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2624 word(&mut self.s, ",")?;
2628 self.end()?; // close the ibox for the pattern
2629 self.print_expr(&arm.body)?;
2630 word(&mut self.s, ",")?;
2633 self.end() // close enclosing cbox
2636 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2637 match explicit_self.node {
2638 SelfKind::Value(m) => {
2639 self.print_mutability(m)?;
2640 word(&mut self.s, "self")
2642 SelfKind::Region(ref lt, m) => {
2643 word(&mut self.s, "&")?;
2644 self.print_opt_lifetime(lt)?;
2645 self.print_mutability(m)?;
2646 word(&mut self.s, "self")
2648 SelfKind::Explicit(ref typ, m) => {
2649 self.print_mutability(m)?;
2650 word(&mut self.s, "self")?;
2651 self.word_space(":")?;
2652 self.print_type(&typ)
2657 pub fn print_fn(&mut self,
2659 unsafety: ast::Unsafety,
2660 constness: ast::Constness,
2662 name: Option<ast::Ident>,
2663 generics: &ast::Generics,
2664 vis: &ast::Visibility) -> io::Result<()> {
2665 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2667 if let Some(name) = name {
2669 self.print_ident(name)?;
2671 self.print_generics(generics)?;
2672 self.print_fn_args_and_ret(decl)?;
2673 self.print_where_clause(&generics.where_clause)
2676 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2679 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2681 word(&mut self.s, ", ...")?;
2685 self.print_fn_output(decl)
2688 pub fn print_fn_block_args(
2692 word(&mut self.s, "|")?;
2693 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2694 word(&mut self.s, "|")?;
2696 if let ast::FunctionRetTy::Default(..) = decl.output {
2700 self.space_if_not_bol()?;
2701 self.word_space("->")?;
2703 ast::FunctionRetTy::Ty(ref ty) => {
2704 self.print_type(&ty)?;
2705 self.maybe_print_comment(ty.span.lo)
2707 ast::FunctionRetTy::Default(..) => unreachable!(),
2711 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2713 match capture_clause {
2714 ast::CaptureBy::Value => self.word_space("move"),
2715 ast::CaptureBy::Ref => Ok(()),
2719 pub fn print_bounds(&mut self,
2721 bounds: &[ast::TyParamBound])
2723 if !bounds.is_empty() {
2724 word(&mut self.s, prefix)?;
2725 let mut first = true;
2726 for bound in bounds {
2731 self.word_space("+")?;
2735 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2736 self.print_poly_trait_ref(tref)
2738 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2739 word(&mut self.s, "?")?;
2740 self.print_poly_trait_ref(tref)
2742 RegionTyParamBound(ref lt) => {
2743 self.print_lifetime(lt)
2753 pub fn print_lifetime(&mut self,
2754 lifetime: &ast::Lifetime)
2757 self.print_name(lifetime.name)
2760 pub fn print_lifetime_bounds(&mut self,
2761 lifetime: &ast::Lifetime,
2762 bounds: &[ast::Lifetime])
2765 self.print_lifetime(lifetime)?;
2766 if !bounds.is_empty() {
2767 word(&mut self.s, ": ")?;
2768 for (i, bound) in bounds.iter().enumerate() {
2770 word(&mut self.s, " + ")?;
2772 self.print_lifetime(bound)?;
2778 pub fn print_generics(&mut self,
2779 generics: &ast::Generics)
2782 let total = generics.lifetimes.len() + generics.ty_params.len();
2787 word(&mut self.s, "<")?;
2789 let mut ints = Vec::new();
2794 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2795 if idx < generics.lifetimes.len() {
2796 let lifetime_def = &generics.lifetimes[idx];
2797 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2798 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2800 let idx = idx - generics.lifetimes.len();
2801 let param = &generics.ty_params[idx];
2802 s.print_ty_param(param)
2806 word(&mut self.s, ">")?;
2810 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2811 self.print_outer_attributes_inline(¶m.attrs)?;
2812 self.print_ident(param.ident)?;
2813 self.print_bounds(":", ¶m.bounds)?;
2814 match param.default {
2815 Some(ref default) => {
2816 space(&mut self.s)?;
2817 self.word_space("=")?;
2818 self.print_type(&default)
2824 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2826 if where_clause.predicates.is_empty() {
2830 space(&mut self.s)?;
2831 self.word_space("where")?;
2833 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2835 self.word_space(",")?;
2839 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2843 self.print_formal_lifetime_list(bound_lifetimes)?;
2844 self.print_type(&bounded_ty)?;
2845 self.print_bounds(":", bounds)?;
2847 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2850 self.print_lifetime_bounds(lifetime, bounds)?;
2852 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2853 self.print_path(path, false, 0, false)?;
2854 space(&mut self.s)?;
2855 self.word_space("=")?;
2856 self.print_type(&ty)?;
2864 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2866 ast::ViewPathSimple(ident, ref path) => {
2867 self.print_path(path, false, 0, true)?;
2869 if path.segments.last().unwrap().identifier.name !=
2871 space(&mut self.s)?;
2872 self.word_space("as")?;
2873 self.print_ident(ident)?;
2879 ast::ViewPathGlob(ref path) => {
2880 self.print_path(path, false, 0, true)?;
2881 word(&mut self.s, "::*")
2884 ast::ViewPathList(ref path, ref idents) => {
2885 if path.segments.is_empty() {
2886 word(&mut self.s, "{")?;
2888 self.print_path(path, false, 0, true)?;
2889 word(&mut self.s, "::{")?;
2891 self.commasep(Inconsistent, &idents[..], |s, w| {
2892 s.print_ident(w.node.name)?;
2893 if let Some(ident) = w.node.rename {
2895 s.word_space("as")?;
2896 s.print_ident(ident)?;
2900 word(&mut self.s, "}")
2905 pub fn print_mutability(&mut self,
2906 mutbl: ast::Mutability) -> io::Result<()> {
2908 ast::Mutability::Mutable => self.word_nbsp("mut"),
2909 ast::Mutability::Immutable => Ok(()),
2913 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2914 self.print_mutability(mt.mutbl)?;
2915 self.print_type(&mt.ty)
2918 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2919 self.ibox(INDENT_UNIT)?;
2920 match input.ty.node {
2921 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2923 if let Some(eself) = input.to_self() {
2924 self.print_explicit_self(&eself)?;
2926 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2927 ident.node.name == keywords::Invalid.name()
2932 self.print_pat(&input.pat)?;
2933 word(&mut self.s, ":")?;
2934 space(&mut self.s)?;
2936 self.print_type(&input.ty)?;
2943 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2944 if let ast::FunctionRetTy::Default(..) = decl.output {
2948 self.space_if_not_bol()?;
2949 self.ibox(INDENT_UNIT)?;
2950 self.word_space("->")?;
2952 ast::FunctionRetTy::Default(..) => unreachable!(),
2953 ast::FunctionRetTy::Ty(ref ty) =>
2954 self.print_type(&ty)?
2959 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2964 pub fn print_ty_fn(&mut self,
2966 unsafety: ast::Unsafety,
2968 name: Option<ast::Ident>,
2969 generics: &ast::Generics)
2971 self.ibox(INDENT_UNIT)?;
2972 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2973 word(&mut self.s, "for")?;
2974 self.print_generics(generics)?;
2976 let generics = ast::Generics {
2977 lifetimes: Vec::new(),
2978 ty_params: P::new(),
2979 where_clause: ast::WhereClause {
2980 id: ast::DUMMY_NODE_ID,
2981 predicates: Vec::new(),
2983 span: syntax_pos::DUMMY_SP,
2987 ast::Constness::NotConst,
2991 &ast::Visibility::Inherited)?;
2995 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2996 next_pos: Option<BytePos>)
2998 let cm = match self.cm {
3002 if let Some(ref cmnt) = self.next_comment() {
3003 if cmnt.style != comments::Trailing { return Ok(()) }
3004 let span_line = cm.lookup_char_pos(span.hi);
3005 let comment_line = cm.lookup_char_pos(cmnt.pos);
3006 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3007 if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3008 self.print_comment(cmnt)?;
3009 self.cur_cmnt_and_lit.cur_cmnt += 1;
3015 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3016 // If there aren't any remaining comments, then we need to manually
3017 // make sure there is a line break at the end.
3018 if self.next_comment().is_none() {
3019 hardbreak(&mut self.s)?;
3022 match self.next_comment() {
3024 self.print_comment(cmnt)?;
3025 self.cur_cmnt_and_lit.cur_cmnt += 1;
3033 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3034 opt_abi: Option<Abi>)
3037 Some(Abi::Rust) => Ok(()),
3039 self.word_nbsp("extern")?;
3040 self.word_nbsp(&abi.to_string())
3046 pub fn print_extern_opt_abi(&mut self,
3047 opt_abi: Option<Abi>) -> io::Result<()> {
3050 self.word_nbsp("extern")?;
3051 self.word_nbsp(&abi.to_string())
3057 pub fn print_fn_header_info(&mut self,
3058 unsafety: ast::Unsafety,
3059 constness: ast::Constness,
3061 vis: &ast::Visibility) -> io::Result<()> {
3062 word(&mut self.s, &visibility_qualified(vis, ""))?;
3065 ast::Constness::NotConst => {}
3066 ast::Constness::Const => self.word_nbsp("const")?
3069 self.print_unsafety(unsafety)?;
3071 if abi != Abi::Rust {
3072 self.word_nbsp("extern")?;
3073 self.word_nbsp(&abi.to_string())?;
3076 word(&mut self.s, "fn")
3079 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3081 ast::Unsafety::Normal => Ok(()),
3082 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3087 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3098 fn test_fun_to_string() {
3099 let abba_ident = ast::Ident::from_str("abba");
3101 let decl = ast::FnDecl {
3103 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3106 let generics = ast::Generics::default();
3107 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3108 ast::Constness::NotConst,
3109 abba_ident, &generics),
3114 fn test_variant_to_string() {
3115 let ident = ast::Ident::from_str("principal_skinner");
3117 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3120 // making this up as I go.... ?
3121 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3125 let varstr = variant_to_string(&var);
3126 assert_eq!(varstr, "principal_skinner");