1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
14 use ast::{self, BlockCheckMode, PatKind, RangeEnd};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use codemap::{self, CodeMap};
20 use syntax_pos::{self, BytePos};
21 use parse::token::{self, BinOpToken, Token};
22 use parse::lexer::comments;
23 use parse::{self, ParseSess};
24 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
25 use print::pp::{Breaks, eof};
26 use print::pp::Breaks::{Consistent, Inconsistent};
29 use symbol::{Symbol, keywords};
30 use syntax_pos::DUMMY_SP;
31 use tokenstream::{self, TokenStream, TokenTree};
34 use std::io::{self, Write, Read};
37 pub enum AnnNode<'a> {
38 NodeIdent(&'a ast::Ident),
39 NodeName(&'a ast::Name),
40 NodeBlock(&'a ast::Block),
41 NodeItem(&'a ast::Item),
42 NodeSubItem(ast::NodeId),
43 NodeExpr(&'a ast::Expr),
44 NodePat(&'a ast::Pat),
48 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
49 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
52 #[derive(Copy, Clone)]
55 impl PpAnn for NoAnn {}
57 #[derive(Copy, Clone)]
58 pub struct CurrentCommentAndLiteral {
63 pub struct State<'a> {
64 pub s: pp::Printer<'a>,
65 cm: Option<&'a CodeMap>,
66 comments: Option<Vec<comments::Comment> >,
67 literals: Option<Vec<comments::Literal> >,
68 cur_cmnt_and_lit: CurrentCommentAndLiteral,
69 boxes: Vec<pp::Breaks>,
73 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
74 static NO_ANN: NoAnn = NoAnn;
75 rust_printer_annotated(writer, &NO_ANN)
78 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
79 ann: &'a PpAnn) -> State<'a> {
81 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
85 cur_cmnt_and_lit: CurrentCommentAndLiteral {
94 pub const INDENT_UNIT: usize = 4;
96 pub const DEFAULT_COLUMNS: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
111 if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
112 // We need to print `#![no_std]` (and its feature gate) so that
113 // compiling pretty-printed source won't inject libstd again.
114 // However we don't want these attributes in the AST because
115 // of the feature gate, so we fake them up here.
117 // #![feature(prelude_import)]
118 let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
119 let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
120 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
121 s.print_attribute(&fake_attr)?;
124 let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
125 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
126 s.print_attribute(&fake_attr)?;
129 s.print_mod(&krate.module, &krate.attrs)?;
130 s.print_remaining_comments()?;
135 pub fn new_from_input(cm: &'a CodeMap,
141 is_expanded: bool) -> State<'a> {
142 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
149 // If the code is post expansion, don't use the table of
150 // literals, since it doesn't correspond with the literals
151 // in the AST anymore.
152 if is_expanded { None } else { Some(lits) })
155 pub fn new(cm: &'a CodeMap,
158 comments: Option<Vec<comments::Comment>>,
159 literals: Option<Vec<comments::Literal>>) -> State<'a> {
161 s: pp::mk_printer(out, DEFAULT_COLUMNS),
165 cur_cmnt_and_lit: CurrentCommentAndLiteral {
175 pub fn to_string<F>(f: F) -> String where
176 F: FnOnce(&mut State) -> io::Result<()>,
178 let mut wr = Vec::new();
180 let mut printer = rust_printer(Box::new(&mut wr));
181 f(&mut printer).unwrap();
182 eof(&mut printer.s).unwrap();
184 String::from_utf8(wr).unwrap()
187 pub fn binop_to_string(op: BinOpToken) -> &'static str {
193 token::Percent => "%",
202 pub fn token_to_string(tok: &Token) -> String {
204 token::Eq => "=".to_string(),
205 token::Lt => "<".to_string(),
206 token::Le => "<=".to_string(),
207 token::EqEq => "==".to_string(),
208 token::Ne => "!=".to_string(),
209 token::Ge => ">=".to_string(),
210 token::Gt => ">".to_string(),
211 token::Not => "!".to_string(),
212 token::Tilde => "~".to_string(),
213 token::OrOr => "||".to_string(),
214 token::AndAnd => "&&".to_string(),
215 token::BinOp(op) => binop_to_string(op).to_string(),
216 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
218 /* Structural symbols */
219 token::At => "@".to_string(),
220 token::Dot => ".".to_string(),
221 token::DotDot => "..".to_string(),
222 token::DotDotDot => "...".to_string(),
223 token::Comma => ",".to_string(),
224 token::Semi => ";".to_string(),
225 token::Colon => ":".to_string(),
226 token::ModSep => "::".to_string(),
227 token::RArrow => "->".to_string(),
228 token::LArrow => "<-".to_string(),
229 token::FatArrow => "=>".to_string(),
230 token::OpenDelim(token::Paren) => "(".to_string(),
231 token::CloseDelim(token::Paren) => ")".to_string(),
232 token::OpenDelim(token::Bracket) => "[".to_string(),
233 token::CloseDelim(token::Bracket) => "]".to_string(),
234 token::OpenDelim(token::Brace) => "{".to_string(),
235 token::CloseDelim(token::Brace) => "}".to_string(),
236 token::OpenDelim(token::NoDelim) => " ".to_string(),
237 token::CloseDelim(token::NoDelim) => " ".to_string(),
238 token::Pound => "#".to_string(),
239 token::Dollar => "$".to_string(),
240 token::Question => "?".to_string(),
243 token::Literal(lit, suf) => {
244 let mut out = match lit {
245 token::Byte(b) => format!("b'{}'", b),
246 token::Char(c) => format!("'{}'", c),
247 token::Float(c) => c.to_string(),
248 token::Integer(c) => c.to_string(),
249 token::Str_(s) => format!("\"{}\"", s),
250 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
251 delim=repeat("#", n),
253 token::ByteStr(v) => format!("b\"{}\"", v),
254 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
255 delim=repeat("#", n),
259 if let Some(s) = suf {
260 out.push_str(&s.as_str())
266 /* Name components */
267 token::Ident(s) => s.to_string(),
268 token::Lifetime(s) => s.to_string(),
269 token::Underscore => "_".to_string(),
272 token::DocComment(s) => s.to_string(),
273 token::SubstNt(s) => format!("${}", s),
274 token::Eof => "<eof>".to_string(),
275 token::Whitespace => " ".to_string(),
276 token::Comment => "/* */".to_string(),
277 token::Shebang(s) => format!("/* shebang: {}*/", s),
279 token::Interpolated(ref nt) => match **nt {
280 token::NtExpr(ref e) => expr_to_string(&e),
281 token::NtMeta(ref e) => meta_item_to_string(&e),
282 token::NtTy(ref e) => ty_to_string(&e),
283 token::NtPath(ref e) => path_to_string(&e),
284 token::NtItem(ref e) => item_to_string(&e),
285 token::NtBlock(ref e) => block_to_string(&e),
286 token::NtStmt(ref e) => stmt_to_string(&e),
287 token::NtPat(ref e) => pat_to_string(&e),
288 token::NtIdent(ref e) => ident_to_string(e.node),
289 token::NtTT(ref tree) => tt_to_string(tree.clone()),
290 token::NtArm(ref e) => arm_to_string(&e),
291 token::NtImplItem(ref e) => impl_item_to_string(&e),
292 token::NtTraitItem(ref e) => trait_item_to_string(&e),
293 token::NtGenerics(ref e) => generics_to_string(&e),
294 token::NtWhereClause(ref e) => where_clause_to_string(&e),
295 token::NtArg(ref e) => arg_to_string(&e),
300 pub fn ty_to_string(ty: &ast::Ty) -> String {
301 to_string(|s| s.print_type(ty))
304 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
305 to_string(|s| s.print_bounds("", bounds))
308 pub fn pat_to_string(pat: &ast::Pat) -> String {
309 to_string(|s| s.print_pat(pat))
312 pub fn arm_to_string(arm: &ast::Arm) -> String {
313 to_string(|s| s.print_arm(arm))
316 pub fn expr_to_string(e: &ast::Expr) -> String {
317 to_string(|s| s.print_expr(e))
320 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
321 to_string(|s| s.print_lifetime(e))
324 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
325 to_string(|s| s.print_tt(tt))
328 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
329 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
332 pub fn tokens_to_string(tokens: TokenStream) -> String {
333 to_string(|s| s.print_tts(tokens))
336 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
337 to_string(|s| s.print_stmt(stmt))
340 pub fn attr_to_string(attr: &ast::Attribute) -> String {
341 to_string(|s| s.print_attribute(attr))
344 pub fn item_to_string(i: &ast::Item) -> String {
345 to_string(|s| s.print_item(i))
348 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
349 to_string(|s| s.print_impl_item(i))
352 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
353 to_string(|s| s.print_trait_item(i))
356 pub fn generics_to_string(generics: &ast::Generics) -> String {
357 to_string(|s| s.print_generics(generics))
360 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
361 to_string(|s| s.print_where_clause(i))
364 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
365 to_string(|s| s.print_fn_block_args(p))
368 pub fn path_to_string(p: &ast::Path) -> String {
369 to_string(|s| s.print_path(p, false, 0, false))
372 pub fn ident_to_string(id: ast::Ident) -> String {
373 to_string(|s| s.print_ident(id))
376 pub fn fun_to_string(decl: &ast::FnDecl,
377 unsafety: ast::Unsafety,
378 constness: ast::Constness,
380 generics: &ast::Generics)
384 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
385 generics, &ast::Visibility::Inherited)?;
386 s.end()?; // Close the head box
387 s.end() // Close the outer box
391 pub fn block_to_string(blk: &ast::Block) -> String {
393 // containing cbox, will be closed by print-block at }
394 s.cbox(INDENT_UNIT)?;
395 // head-ibox, will be closed by print-block after {
401 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
402 to_string(|s| s.print_meta_list_item(li))
405 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
406 to_string(|s| s.print_meta_item(mi))
409 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
410 to_string(|s| s.print_attribute(attr))
413 pub fn lit_to_string(l: &ast::Lit) -> String {
414 to_string(|s| s.print_literal(l))
417 pub fn variant_to_string(var: &ast::Variant) -> String {
418 to_string(|s| s.print_variant(var))
421 pub fn arg_to_string(arg: &ast::Arg) -> String {
422 to_string(|s| s.print_arg(arg, false))
425 pub fn mac_to_string(arg: &ast::Mac) -> String {
426 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
429 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 ast::Visibility::Public => format!("pub {}", s),
432 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
433 ast::Visibility::Restricted { ref path, .. } =>
434 format!("pub({}) {}", to_string(|s| s.print_path(path, false, 0, true)), s),
435 ast::Visibility::Inherited => s.to_string()
439 fn needs_parentheses(expr: &ast::Expr) -> bool {
441 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
442 ast::ExprKind::Closure(..) |
443 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
444 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
449 pub trait PrintState<'a> {
450 fn writer(&mut self) -> &mut pp::Printer<'a>;
451 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
452 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
453 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
454 fn literals(&self) -> &Option<Vec<comments::Literal>>;
456 fn word_space(&mut self, w: &str) -> io::Result<()> {
457 word(self.writer(), w)?;
461 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
463 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
465 fn is_begin(&mut self) -> bool {
466 match self.writer().last_token() {
467 pp::Token::Begin(_) => true,
472 fn is_end(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::End => true,
479 // is this the beginning of a line?
480 fn is_bol(&mut self) -> bool {
481 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
484 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
486 hardbreak(self.writer())?
492 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
493 self.boxes().push(b);
494 pp::rbox(self.writer(), u, b)
497 fn ibox(&mut self, u: usize) -> io::Result<()> {
498 self.boxes().push(pp::Breaks::Inconsistent);
499 pp::ibox(self.writer(), u)
502 fn end(&mut self) -> io::Result<()> {
503 self.boxes().pop().unwrap();
504 pp::end(self.writer())
507 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
508 where F: FnMut(&mut Self, &T) -> io::Result<()>,
511 let mut first = true;
513 if first { first = false; } else { self.word_space(",")?; }
519 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
520 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
522 let mut result = None;
524 if let &Some(ref lits) = self.literals()
526 while cur_lit < lits.len() {
527 let ltrl = (*lits)[cur_lit].clone();
528 if ltrl.pos > pos { break; }
537 self.cur_cmnt_and_lit().cur_lit = cur_lit;
541 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
542 while let Some(ref cmnt) = self.next_comment() {
544 self.print_comment(cmnt)?;
545 self.cur_cmnt_and_lit().cur_cmnt += 1;
553 fn print_comment(&mut self,
554 cmnt: &comments::Comment) -> io::Result<()> {
557 assert_eq!(cmnt.lines.len(), 1);
558 zerobreak(self.writer())?;
559 word(self.writer(), &cmnt.lines[0])?;
560 zerobreak(self.writer())
562 comments::Isolated => {
563 self.hardbreak_if_not_bol()?;
564 for line in &cmnt.lines {
565 // Don't print empty lines because they will end up as trailing
567 if !line.is_empty() {
568 word(self.writer(), &line[..])?;
570 hardbreak(self.writer())?;
574 comments::Trailing => {
576 word(self.writer(), " ")?;
578 if cmnt.lines.len() == 1 {
579 word(self.writer(), &cmnt.lines[0])?;
580 hardbreak(self.writer())
583 for line in &cmnt.lines {
584 if !line.is_empty() {
585 word(self.writer(), &line[..])?;
587 hardbreak(self.writer())?;
592 comments::BlankLine => {
593 // We need to do at least one, possibly two hardbreaks.
594 let is_semi = match self.writer().last_token() {
595 pp::Token::String(s, _) => ";" == s,
598 if is_semi || self.is_begin() || self.is_end() {
599 hardbreak(self.writer())?;
601 hardbreak(self.writer())
606 fn next_comment(&mut self) -> Option<comments::Comment> {
607 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
608 match *self.comments() {
610 if cur_cmnt < cmnts.len() {
611 Some(cmnts[cur_cmnt].clone())
620 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
621 self.maybe_print_comment(lit.span.lo)?;
622 match self.next_lit(lit.span.lo) {
624 return word(self.writer(), &(*ltrl).lit);
629 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
630 ast::LitKind::Byte(byte) => {
631 let mut res = String::from("b'");
632 res.extend(ascii::escape_default(byte).map(|c| c as char));
634 word(self.writer(), &res[..])
636 ast::LitKind::Char(ch) => {
637 let mut res = String::from("'");
638 res.extend(ch.escape_default());
640 word(self.writer(), &res[..])
642 ast::LitKind::Int(i, t) => {
644 ast::LitIntType::Signed(st) => {
645 word(self.writer(), &st.val_to_string(i as i128))
647 ast::LitIntType::Unsigned(ut) => {
648 word(self.writer(), &ut.val_to_string(i))
650 ast::LitIntType::Unsuffixed => {
651 word(self.writer(), &format!("{}", i))
655 ast::LitKind::Float(ref f, t) => {
662 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()),
663 ast::LitKind::Bool(val) => {
664 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
666 ast::LitKind::ByteStr(ref v) => {
667 let mut escaped: String = String::new();
668 for &ch in v.iter() {
669 escaped.extend(ascii::escape_default(ch)
670 .map(|c| c as char));
672 word(self.writer(), &format!("b\"{}\"", escaped))
677 fn print_string(&mut self, st: &str,
678 style: ast::StrStyle) -> io::Result<()> {
679 let st = match style {
680 ast::StrStyle::Cooked => {
681 (format!("\"{}\"", st.escape_default()))
683 ast::StrStyle::Raw(n) => {
684 (format!("r{delim}\"{string}\"{delim}",
685 delim=repeat("#", n),
689 word(self.writer(), &st[..])
692 fn print_inner_attributes(&mut self,
693 attrs: &[ast::Attribute]) -> io::Result<()> {
694 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
697 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
698 attrs: &[ast::Attribute])
700 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
703 fn print_outer_attributes(&mut self,
704 attrs: &[ast::Attribute]) -> io::Result<()> {
705 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
708 fn print_inner_attributes_inline(&mut self,
709 attrs: &[ast::Attribute]) -> io::Result<()> {
710 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
713 fn print_outer_attributes_inline(&mut self,
714 attrs: &[ast::Attribute]) -> io::Result<()> {
715 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
718 fn print_either_attributes(&mut self,
719 attrs: &[ast::Attribute],
720 kind: ast::AttrStyle,
722 trailing_hardbreak: bool) -> io::Result<()> {
725 if attr.style == kind {
726 self.print_attribute_inline(attr, is_inline)?;
733 if count > 0 && trailing_hardbreak && !is_inline {
734 self.hardbreak_if_not_bol()?;
739 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
740 self.print_attribute_inline(attr, false)
743 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
744 is_inline: bool) -> io::Result<()> {
746 self.hardbreak_if_not_bol()?;
748 self.maybe_print_comment(attr.span.lo)?;
749 if attr.is_sugared_doc {
750 word(self.writer(), &attr.value_str().unwrap().as_str())?;
751 hardbreak(self.writer())
754 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
755 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
757 if let Some(mi) = attr.meta() {
758 self.print_meta_item(&mi)?
760 for (i, segment) in attr.path.segments.iter().enumerate() {
762 word(self.writer(), "::")?
764 if segment.identifier.name != keywords::CrateRoot.name() &&
765 segment.identifier.name != "$crate" {
766 word(self.writer(), &segment.identifier.name.as_str())?;
769 space(self.writer())?;
770 self.print_tts(attr.tokens.clone())?;
772 word(self.writer(), "]")
776 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
778 ast::NestedMetaItemKind::MetaItem(ref mi) => {
779 self.print_meta_item(mi)
781 ast::NestedMetaItemKind::Literal(ref lit) => {
782 self.print_literal(lit)
787 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
788 self.ibox(INDENT_UNIT)?;
790 ast::MetaItemKind::Word => {
791 word(self.writer(), &item.name.as_str())?;
793 ast::MetaItemKind::NameValue(ref value) => {
794 self.word_space(&item.name.as_str())?;
795 self.word_space("=")?;
796 self.print_literal(value)?;
798 ast::MetaItemKind::List(ref items) => {
799 word(self.writer(), &item.name.as_str())?;
801 self.commasep(Consistent,
803 |s, i| s.print_meta_list_item(&i))?;
810 /// This doesn't deserve to be called "pretty" printing, but it should be
811 /// meaning-preserving. A quick hack that might help would be to look at the
812 /// spans embedded in the TTs to decide where to put spaces and newlines.
813 /// But it'd be better to parse these according to the grammar of the
814 /// appropriate macro, transcribe back into the grammar we just parsed from,
815 /// and then pretty-print the resulting AST nodes (so, e.g., we print
816 /// expression arguments as expressions). It can be done! I think.
817 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
819 TokenTree::Token(_, ref tk) => {
820 word(self.writer(), &token_to_string(tk))?;
822 parse::token::DocComment(..) => {
823 hardbreak(self.writer())
828 TokenTree::Delimited(_, ref delimed) => {
829 word(self.writer(), &token_to_string(&delimed.open_token()))?;
830 space(self.writer())?;
831 self.print_tts(delimed.stream())?;
832 space(self.writer())?;
833 word(self.writer(), &token_to_string(&delimed.close_token()))
838 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
840 for (i, tt) in tts.into_trees().enumerate() {
842 space(self.writer())?;
849 fn space_if_not_bol(&mut self) -> io::Result<()> {
850 if !self.is_bol() { space(self.writer())?; }
854 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
857 impl<'a> PrintState<'a> for State<'a> {
858 fn writer(&mut self) -> &mut pp::Printer<'a> {
862 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
866 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
870 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
871 &mut self.cur_cmnt_and_lit
874 fn literals(&self) -> &Option<Vec<comments::Literal>> {
880 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
881 self.boxes.push(pp::Breaks::Consistent);
882 pp::cbox(&mut self.s, u)
885 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
886 word(&mut self.s, w)?;
890 pub fn head(&mut self, w: &str) -> io::Result<()> {
891 // outer-box is consistent
892 self.cbox(INDENT_UNIT)?;
893 // head-box is inconsistent
894 self.ibox(w.len() + 1)?;
895 // keyword that starts the head
902 pub fn bopen(&mut self) -> io::Result<()> {
903 word(&mut self.s, "{")?;
904 self.end() // close the head-box
907 pub fn bclose_(&mut self, span: syntax_pos::Span,
908 indented: usize) -> io::Result<()> {
909 self.bclose_maybe_open(span, indented, true)
911 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
912 indented: usize, close_box: bool) -> io::Result<()> {
913 self.maybe_print_comment(span.hi)?;
914 self.break_offset_if_not_bol(1, -(indented as isize))?;
915 word(&mut self.s, "}")?;
917 self.end()?; // close the outer-box
921 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
922 self.bclose_(span, INDENT_UNIT)
925 pub fn in_cbox(&self) -> bool {
926 match self.boxes.last() {
927 Some(&last_box) => last_box == pp::Breaks::Consistent,
932 pub fn break_offset_if_not_bol(&mut self, n: usize,
933 off: isize) -> io::Result<()> {
935 break_offset(&mut self.s, n, off)
937 if off != 0 && self.s.last_token().is_hardbreak_tok() {
938 // We do something pretty sketchy here: tuck the nonzero
939 // offset-adjustment we were going to deposit along with the
940 // break into the previous hardbreak.
941 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
947 // Synthesizes a comment that was not textually present in the original source
949 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
950 word(&mut self.s, "/*")?;
952 word(&mut self.s, &text[..])?;
954 word(&mut self.s, "*/")
959 pub fn commasep_cmnt<T, F, G>(&mut self,
963 mut get_span: G) -> io::Result<()> where
964 F: FnMut(&mut State, &T) -> io::Result<()>,
965 G: FnMut(&T) -> syntax_pos::Span,
968 let len = elts.len();
971 self.maybe_print_comment(get_span(elt).hi)?;
975 word(&mut self.s, ",")?;
976 self.maybe_print_trailing_comment(get_span(elt),
977 Some(get_span(&elts[i]).hi))?;
978 self.space_if_not_bol()?;
984 pub fn commasep_exprs(&mut self, b: Breaks,
985 exprs: &[P<ast::Expr>]) -> io::Result<()> {
986 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
989 pub fn print_mod(&mut self, _mod: &ast::Mod,
990 attrs: &[ast::Attribute]) -> io::Result<()> {
991 self.print_inner_attributes(attrs)?;
992 for item in &_mod.items {
993 self.print_item(&item)?;
998 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
999 attrs: &[ast::Attribute]) -> io::Result<()> {
1000 self.print_inner_attributes(attrs)?;
1001 for item in &nmod.items {
1002 self.print_foreign_item(item)?;
1007 pub fn print_opt_lifetime(&mut self,
1008 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1009 if let Some(l) = *lifetime {
1010 self.print_lifetime(&l)?;
1016 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1017 self.maybe_print_comment(ty.span.lo)?;
1020 ast::TyKind::Slice(ref ty) => {
1021 word(&mut self.s, "[")?;
1022 self.print_type(&ty)?;
1023 word(&mut self.s, "]")?;
1025 ast::TyKind::Ptr(ref mt) => {
1026 word(&mut self.s, "*")?;
1028 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1029 ast::Mutability::Immutable => self.word_nbsp("const")?,
1031 self.print_type(&mt.ty)?;
1033 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1034 word(&mut self.s, "&")?;
1035 self.print_opt_lifetime(lifetime)?;
1038 ast::TyKind::Never => {
1039 word(&mut self.s, "!")?;
1041 ast::TyKind::Tup(ref elts) => {
1043 self.commasep(Inconsistent, &elts[..],
1044 |s, ty| s.print_type(&ty))?;
1045 if elts.len() == 1 {
1046 word(&mut self.s, ",")?;
1050 ast::TyKind::Paren(ref typ) => {
1052 self.print_type(&typ)?;
1055 ast::TyKind::BareFn(ref f) => {
1056 let generics = ast::Generics {
1057 lifetimes: f.lifetimes.clone(),
1058 ty_params: Vec::new(),
1059 where_clause: ast::WhereClause {
1060 id: ast::DUMMY_NODE_ID,
1061 predicates: Vec::new(),
1063 span: syntax_pos::DUMMY_SP,
1065 self.print_ty_fn(f.abi,
1071 ast::TyKind::Path(None, ref path) => {
1072 self.print_path(path, false, 0, false)?;
1074 ast::TyKind::Path(Some(ref qself), ref path) => {
1075 self.print_qpath(path, qself, false)?
1077 ast::TyKind::TraitObject(ref bounds) => {
1078 self.print_bounds("", &bounds[..])?;
1080 ast::TyKind::ImplTrait(ref bounds) => {
1081 self.print_bounds("impl ", &bounds[..])?;
1083 ast::TyKind::Array(ref ty, ref v) => {
1084 word(&mut self.s, "[")?;
1085 self.print_type(&ty)?;
1086 word(&mut self.s, "; ")?;
1087 self.print_expr(&v)?;
1088 word(&mut self.s, "]")?;
1090 ast::TyKind::Typeof(ref e) => {
1091 word(&mut self.s, "typeof(")?;
1092 self.print_expr(&e)?;
1093 word(&mut self.s, ")")?;
1095 ast::TyKind::Infer => {
1096 word(&mut self.s, "_")?;
1098 ast::TyKind::ImplicitSelf => {
1099 word(&mut self.s, "Self")?;
1101 ast::TyKind::Mac(ref m) => {
1102 self.print_mac(m, token::Paren)?;
1108 pub fn print_foreign_item(&mut self,
1109 item: &ast::ForeignItem) -> io::Result<()> {
1110 self.hardbreak_if_not_bol()?;
1111 self.maybe_print_comment(item.span.lo)?;
1112 self.print_outer_attributes(&item.attrs)?;
1114 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1116 self.print_fn(decl, ast::Unsafety::Normal,
1117 ast::Constness::NotConst,
1118 Abi::Rust, Some(item.ident),
1119 generics, &item.vis)?;
1120 self.end()?; // end head-ibox
1121 word(&mut self.s, ";")?;
1122 self.end() // end the outer fn box
1124 ast::ForeignItemKind::Static(ref t, m) => {
1125 self.head(&visibility_qualified(&item.vis, "static"))?;
1127 self.word_space("mut")?;
1129 self.print_ident(item.ident)?;
1130 self.word_space(":")?;
1131 self.print_type(&t)?;
1132 word(&mut self.s, ";")?;
1133 self.end()?; // end the head-ibox
1134 self.end() // end the outer cbox
1139 fn print_associated_const(&mut self,
1142 default: Option<&ast::Expr>,
1143 vis: &ast::Visibility)
1146 word(&mut self.s, &visibility_qualified(vis, ""))?;
1147 self.word_space("const")?;
1148 self.print_ident(ident)?;
1149 self.word_space(":")?;
1150 self.print_type(ty)?;
1151 if let Some(expr) = default {
1152 space(&mut self.s)?;
1153 self.word_space("=")?;
1154 self.print_expr(expr)?;
1156 word(&mut self.s, ";")
1159 fn print_associated_type(&mut self,
1161 bounds: Option<&ast::TyParamBounds>,
1162 ty: Option<&ast::Ty>)
1164 self.word_space("type")?;
1165 self.print_ident(ident)?;
1166 if let Some(bounds) = bounds {
1167 self.print_bounds(":", bounds)?;
1169 if let Some(ty) = ty {
1170 space(&mut self.s)?;
1171 self.word_space("=")?;
1172 self.print_type(ty)?;
1174 word(&mut self.s, ";")
1177 /// Pretty-print an item
1178 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1179 self.hardbreak_if_not_bol()?;
1180 self.maybe_print_comment(item.span.lo)?;
1181 self.print_outer_attributes(&item.attrs)?;
1182 self.ann.pre(self, NodeItem(item))?;
1184 ast::ItemKind::ExternCrate(ref optional_path) => {
1185 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1186 if let Some(p) = *optional_path {
1187 let val = p.as_str();
1188 if val.contains("-") {
1189 self.print_string(&val, ast::StrStyle::Cooked)?;
1191 self.print_name(p)?;
1193 space(&mut self.s)?;
1194 word(&mut self.s, "as")?;
1195 space(&mut self.s)?;
1197 self.print_ident(item.ident)?;
1198 word(&mut self.s, ";")?;
1199 self.end()?; // end inner head-block
1200 self.end()?; // end outer head-block
1202 ast::ItemKind::Use(ref vp) => {
1203 self.head(&visibility_qualified(&item.vis, "use"))?;
1204 self.print_view_path(&vp)?;
1205 word(&mut self.s, ";")?;
1206 self.end()?; // end inner head-block
1207 self.end()?; // end outer head-block
1209 ast::ItemKind::Static(ref ty, m, ref expr) => {
1210 self.head(&visibility_qualified(&item.vis, "static"))?;
1211 if m == ast::Mutability::Mutable {
1212 self.word_space("mut")?;
1214 self.print_ident(item.ident)?;
1215 self.word_space(":")?;
1216 self.print_type(&ty)?;
1217 space(&mut self.s)?;
1218 self.end()?; // end the head-ibox
1220 self.word_space("=")?;
1221 self.print_expr(&expr)?;
1222 word(&mut self.s, ";")?;
1223 self.end()?; // end the outer cbox
1225 ast::ItemKind::Const(ref ty, ref expr) => {
1226 self.head(&visibility_qualified(&item.vis, "const"))?;
1227 self.print_ident(item.ident)?;
1228 self.word_space(":")?;
1229 self.print_type(&ty)?;
1230 space(&mut self.s)?;
1231 self.end()?; // end the head-ibox
1233 self.word_space("=")?;
1234 self.print_expr(&expr)?;
1235 word(&mut self.s, ";")?;
1236 self.end()?; // end the outer cbox
1238 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1249 word(&mut self.s, " ")?;
1250 self.print_block_with_attrs(&body, &item.attrs)?;
1252 ast::ItemKind::Mod(ref _mod) => {
1253 self.head(&visibility_qualified(&item.vis, "mod"))?;
1254 self.print_ident(item.ident)?;
1257 self.print_mod(_mod, &item.attrs)?;
1258 self.bclose(item.span)?;
1260 ast::ItemKind::ForeignMod(ref nmod) => {
1261 self.head("extern")?;
1262 self.word_nbsp(&nmod.abi.to_string())?;
1264 self.print_foreign_mod(nmod, &item.attrs)?;
1265 self.bclose(item.span)?;
1267 ast::ItemKind::Ty(ref ty, ref params) => {
1268 self.ibox(INDENT_UNIT)?;
1270 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1271 self.print_ident(item.ident)?;
1272 self.print_generics(params)?;
1273 self.end()?; // end the inner ibox
1275 self.print_where_clause(¶ms.where_clause)?;
1276 space(&mut self.s)?;
1277 self.word_space("=")?;
1278 self.print_type(&ty)?;
1279 word(&mut self.s, ";")?;
1280 self.end()?; // end the outer ibox
1282 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1283 self.print_enum_def(
1291 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1292 self.head(&visibility_qualified(&item.vis, "struct"))?;
1293 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1295 ast::ItemKind::Union(ref struct_def, ref generics) => {
1296 self.head(&visibility_qualified(&item.vis, "union"))?;
1297 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1299 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1301 self.print_visibility(&item.vis)?;
1302 self.print_unsafety(unsafety)?;
1303 self.word_nbsp("impl")?;
1304 self.print_trait_ref(trait_ref)?;
1305 space(&mut self.s)?;
1306 self.word_space("for")?;
1307 self.word_space("..")?;
1309 self.bclose(item.span)?;
1311 ast::ItemKind::Impl(unsafety,
1316 ref impl_items) => {
1318 self.print_visibility(&item.vis)?;
1319 self.print_unsafety(unsafety)?;
1320 self.word_nbsp("impl")?;
1322 if generics.is_parameterized() {
1323 self.print_generics(generics)?;
1324 space(&mut self.s)?;
1328 ast::ImplPolarity::Negative => {
1329 word(&mut self.s, "!")?;
1334 if let Some(ref t) = *opt_trait {
1335 self.print_trait_ref(t)?;
1336 space(&mut self.s)?;
1337 self.word_space("for")?;
1340 self.print_type(&ty)?;
1341 self.print_where_clause(&generics.where_clause)?;
1343 space(&mut self.s)?;
1345 self.print_inner_attributes(&item.attrs)?;
1346 for impl_item in impl_items {
1347 self.print_impl_item(impl_item)?;
1349 self.bclose(item.span)?;
1351 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1353 self.print_visibility(&item.vis)?;
1354 self.print_unsafety(unsafety)?;
1355 self.word_nbsp("trait")?;
1356 self.print_ident(item.ident)?;
1357 self.print_generics(generics)?;
1358 let mut real_bounds = Vec::with_capacity(bounds.len());
1359 for b in bounds.iter() {
1360 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1361 space(&mut self.s)?;
1362 self.word_space("for ?")?;
1363 self.print_trait_ref(&ptr.trait_ref)?;
1365 real_bounds.push(b.clone());
1368 self.print_bounds(":", &real_bounds[..])?;
1369 self.print_where_clause(&generics.where_clause)?;
1370 word(&mut self.s, " ")?;
1372 for trait_item in trait_items {
1373 self.print_trait_item(trait_item)?;
1375 self.bclose(item.span)?;
1377 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1378 self.print_path(&node.path, false, 0, false)?;
1379 word(&mut self.s, "! ")?;
1380 self.print_ident(item.ident)?;
1381 self.cbox(INDENT_UNIT)?;
1383 self.print_tts(node.stream())?;
1385 word(&mut self.s, ";")?;
1388 ast::ItemKind::MacroDef(ref tts) => {
1389 word(&mut self.s, "macro_rules! ")?;
1390 self.print_ident(item.ident)?;
1391 self.cbox(INDENT_UNIT)?;
1393 self.print_tts(tts.clone().into())?;
1395 word(&mut self.s, ";")?;
1399 self.ann.post(self, NodeItem(item))
1402 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1403 self.print_path(&t.path, false, 0, false)
1406 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1407 if !lifetimes.is_empty() {
1408 word(&mut self.s, "for<")?;
1409 let mut comma = false;
1410 for lifetime_def in lifetimes {
1412 self.word_space(",")?
1414 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1415 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1418 word(&mut self.s, ">")?;
1423 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1424 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1425 self.print_trait_ref(&t.trait_ref)
1428 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1429 generics: &ast::Generics, ident: ast::Ident,
1430 span: syntax_pos::Span,
1431 visibility: &ast::Visibility) -> io::Result<()> {
1432 self.head(&visibility_qualified(visibility, "enum"))?;
1433 self.print_ident(ident)?;
1434 self.print_generics(generics)?;
1435 self.print_where_clause(&generics.where_clause)?;
1436 space(&mut self.s)?;
1437 self.print_variants(&enum_definition.variants, span)
1440 pub fn print_variants(&mut self,
1441 variants: &[ast::Variant],
1442 span: syntax_pos::Span) -> io::Result<()> {
1445 self.space_if_not_bol()?;
1446 self.maybe_print_comment(v.span.lo)?;
1447 self.print_outer_attributes(&v.node.attrs)?;
1448 self.ibox(INDENT_UNIT)?;
1449 self.print_variant(v)?;
1450 word(&mut self.s, ",")?;
1452 self.maybe_print_trailing_comment(v.span, None)?;
1457 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1459 ast::Visibility::Public => self.word_nbsp("pub"),
1460 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1461 ast::Visibility::Restricted { ref path, .. } => {
1462 let path = to_string(|s| s.print_path(path, false, 0, true));
1463 self.word_nbsp(&format!("pub({})", path))
1465 ast::Visibility::Inherited => Ok(())
1469 pub fn print_struct(&mut self,
1470 struct_def: &ast::VariantData,
1471 generics: &ast::Generics,
1473 span: syntax_pos::Span,
1474 print_finalizer: bool) -> io::Result<()> {
1475 self.print_ident(ident)?;
1476 self.print_generics(generics)?;
1477 if !struct_def.is_struct() {
1478 if struct_def.is_tuple() {
1481 Inconsistent, struct_def.fields(),
1483 s.maybe_print_comment(field.span.lo)?;
1484 s.print_outer_attributes(&field.attrs)?;
1485 s.print_visibility(&field.vis)?;
1486 s.print_type(&field.ty)
1491 self.print_where_clause(&generics.where_clause)?;
1492 if print_finalizer {
1493 word(&mut self.s, ";")?;
1496 self.end() // close the outer-box
1498 self.print_where_clause(&generics.where_clause)?;
1501 self.hardbreak_if_not_bol()?;
1503 for field in struct_def.fields() {
1504 self.hardbreak_if_not_bol()?;
1505 self.maybe_print_comment(field.span.lo)?;
1506 self.print_outer_attributes(&field.attrs)?;
1507 self.print_visibility(&field.vis)?;
1508 self.print_ident(field.ident.unwrap())?;
1509 self.word_nbsp(":")?;
1510 self.print_type(&field.ty)?;
1511 word(&mut self.s, ",")?;
1518 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1520 let generics = ast::Generics::default();
1521 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1522 match v.node.disr_expr {
1524 space(&mut self.s)?;
1525 self.word_space("=")?;
1532 pub fn print_method_sig(&mut self,
1535 vis: &ast::Visibility)
1537 self.print_fn(&m.decl,
1546 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1548 self.ann.pre(self, NodeSubItem(ti.id))?;
1549 self.hardbreak_if_not_bol()?;
1550 self.maybe_print_comment(ti.span.lo)?;
1551 self.print_outer_attributes(&ti.attrs)?;
1553 ast::TraitItemKind::Const(ref ty, ref default) => {
1554 self.print_associated_const(ti.ident, &ty,
1555 default.as_ref().map(|expr| &**expr),
1556 &ast::Visibility::Inherited)?;
1558 ast::TraitItemKind::Method(ref sig, ref body) => {
1562 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1563 if let Some(ref body) = *body {
1565 self.print_block_with_attrs(body, &ti.attrs)?;
1567 word(&mut self.s, ";")?;
1570 ast::TraitItemKind::Type(ref bounds, ref default) => {
1571 self.print_associated_type(ti.ident, Some(bounds),
1572 default.as_ref().map(|ty| &**ty))?;
1574 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1575 // code copied from ItemKind::Mac:
1576 self.print_path(&node.path, false, 0, false)?;
1577 word(&mut self.s, "! ")?;
1578 self.cbox(INDENT_UNIT)?;
1580 self.print_tts(node.stream())?;
1582 word(&mut self.s, ";")?;
1586 self.ann.post(self, NodeSubItem(ti.id))
1589 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1590 self.ann.pre(self, NodeSubItem(ii.id))?;
1591 self.hardbreak_if_not_bol()?;
1592 self.maybe_print_comment(ii.span.lo)?;
1593 self.print_outer_attributes(&ii.attrs)?;
1594 if let ast::Defaultness::Default = ii.defaultness {
1595 self.word_nbsp("default")?;
1598 ast::ImplItemKind::Const(ref ty, ref expr) => {
1599 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1601 ast::ImplItemKind::Method(ref sig, ref body) => {
1603 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1605 self.print_block_with_attrs(body, &ii.attrs)?;
1607 ast::ImplItemKind::Type(ref ty) => {
1608 self.print_associated_type(ii.ident, None, Some(ty))?;
1610 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1611 // code copied from ItemKind::Mac:
1612 self.print_path(&node.path, false, 0, false)?;
1613 word(&mut self.s, "! ")?;
1614 self.cbox(INDENT_UNIT)?;
1616 self.print_tts(node.stream())?;
1618 word(&mut self.s, ";")?;
1622 self.ann.post(self, NodeSubItem(ii.id))
1625 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1626 self.maybe_print_comment(st.span.lo)?;
1628 ast::StmtKind::Local(ref loc) => {
1629 self.print_outer_attributes(&loc.attrs)?;
1630 self.space_if_not_bol()?;
1631 self.ibox(INDENT_UNIT)?;
1632 self.word_nbsp("let")?;
1634 self.ibox(INDENT_UNIT)?;
1635 self.print_local_decl(&loc)?;
1637 if let Some(ref init) = loc.init {
1639 self.word_space("=")?;
1640 self.print_expr(&init)?;
1642 word(&mut self.s, ";")?;
1645 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1646 ast::StmtKind::Expr(ref expr) => {
1647 self.space_if_not_bol()?;
1648 self.print_expr_outer_attr_style(&expr, false)?;
1649 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1650 word(&mut self.s, ";")?;
1653 ast::StmtKind::Semi(ref expr) => {
1654 self.space_if_not_bol()?;
1655 self.print_expr_outer_attr_style(&expr, false)?;
1656 word(&mut self.s, ";")?;
1658 ast::StmtKind::Mac(ref mac) => {
1659 let (ref mac, style, ref attrs) = **mac;
1660 self.space_if_not_bol()?;
1661 self.print_outer_attributes(&attrs)?;
1662 let delim = match style {
1663 ast::MacStmtStyle::Braces => token::Brace,
1666 self.print_mac(&mac, delim)?;
1667 if style == ast::MacStmtStyle::Semicolon {
1668 word(&mut self.s, ";")?;
1672 self.maybe_print_trailing_comment(st.span, None)
1675 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1676 self.print_block_with_attrs(blk, &[])
1679 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1680 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1683 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1684 attrs: &[ast::Attribute])
1686 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1689 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1690 indented: usize) -> io::Result<()> {
1691 self.print_block_maybe_unclosed(blk, indented, &[], false)
1694 pub fn print_block_with_attrs(&mut self,
1696 attrs: &[ast::Attribute]) -> io::Result<()> {
1697 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1700 pub fn print_block_maybe_unclosed(&mut self,
1703 attrs: &[ast::Attribute],
1704 close_box: bool) -> io::Result<()> {
1706 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1707 BlockCheckMode::Default => ()
1709 self.maybe_print_comment(blk.span.lo)?;
1710 self.ann.pre(self, NodeBlock(blk))?;
1713 self.print_inner_attributes(attrs)?;
1715 for (i, st) in blk.stmts.iter().enumerate() {
1717 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1718 self.maybe_print_comment(st.span.lo)?;
1719 self.space_if_not_bol()?;
1720 self.print_expr_outer_attr_style(&expr, false)?;
1721 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1723 _ => self.print_stmt(st)?,
1727 self.bclose_maybe_open(blk.span, indented, close_box)?;
1728 self.ann.post(self, NodeBlock(blk))
1731 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1735 // "another else-if"
1736 ast::ExprKind::If(ref i, ref then, ref e) => {
1737 self.cbox(INDENT_UNIT - 1)?;
1739 word(&mut self.s, " else if ")?;
1740 self.print_expr(&i)?;
1741 space(&mut self.s)?;
1742 self.print_block(&then)?;
1743 self.print_else(e.as_ref().map(|e| &**e))
1745 // "another else-if-let"
1746 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1747 self.cbox(INDENT_UNIT - 1)?;
1749 word(&mut self.s, " else if let ")?;
1750 self.print_pat(&pat)?;
1751 space(&mut self.s)?;
1752 self.word_space("=")?;
1753 self.print_expr(&expr)?;
1754 space(&mut self.s)?;
1755 self.print_block(&then)?;
1756 self.print_else(e.as_ref().map(|e| &**e))
1759 ast::ExprKind::Block(ref b) => {
1760 self.cbox(INDENT_UNIT - 1)?;
1762 word(&mut self.s, " else ")?;
1763 self.print_block(&b)
1765 // BLEAH, constraints would be great here
1767 panic!("print_if saw if with weird alternative");
1775 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1776 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1778 self.print_expr(test)?;
1779 space(&mut self.s)?;
1780 self.print_block(blk)?;
1781 self.print_else(elseopt)
1784 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1785 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1786 self.head("if let")?;
1787 self.print_pat(pat)?;
1788 space(&mut self.s)?;
1789 self.word_space("=")?;
1790 self.print_expr(expr)?;
1791 space(&mut self.s)?;
1792 self.print_block(blk)?;
1793 self.print_else(elseopt)
1796 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1798 self.print_path(&m.node.path, false, 0, false)?;
1799 word(&mut self.s, "!")?;
1801 token::Paren => self.popen()?,
1802 token::Bracket => word(&mut self.s, "[")?,
1807 token::NoDelim => {}
1809 self.print_tts(m.node.stream())?;
1811 token::Paren => self.pclose(),
1812 token::Bracket => word(&mut self.s, "]"),
1813 token::Brace => self.bclose(m.span),
1814 token::NoDelim => Ok(()),
1819 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1821 self.commasep_exprs(Inconsistent, args)?;
1825 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1826 binop: ast::BinOp) -> bool {
1827 match sub_expr.node {
1828 ast::ExprKind::Binary(ref sub_op, _, _) => {
1829 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1830 AssocOp::from_ast_binop(binop.node).precedence() {
1840 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1841 let needs_par = needs_parentheses(expr);
1845 self.print_expr(expr)?;
1852 fn print_expr_in_place(&mut self,
1854 expr: &ast::Expr) -> io::Result<()> {
1855 self.print_expr_maybe_paren(place)?;
1856 space(&mut self.s)?;
1857 self.word_space("<-")?;
1858 self.print_expr_maybe_paren(expr)
1861 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1862 attrs: &[Attribute]) -> io::Result<()> {
1863 self.ibox(INDENT_UNIT)?;
1864 word(&mut self.s, "[")?;
1865 self.print_inner_attributes_inline(attrs)?;
1866 self.commasep_exprs(Inconsistent, &exprs[..])?;
1867 word(&mut self.s, "]")?;
1871 fn print_expr_repeat(&mut self,
1872 element: &ast::Expr,
1874 attrs: &[Attribute]) -> io::Result<()> {
1875 self.ibox(INDENT_UNIT)?;
1876 word(&mut self.s, "[")?;
1877 self.print_inner_attributes_inline(attrs)?;
1878 self.print_expr(element)?;
1879 self.word_space(";")?;
1880 self.print_expr(count)?;
1881 word(&mut self.s, "]")?;
1885 fn print_expr_struct(&mut self,
1887 fields: &[ast::Field],
1888 wth: &Option<P<ast::Expr>>,
1889 attrs: &[Attribute]) -> io::Result<()> {
1890 self.print_path(path, true, 0, false)?;
1891 word(&mut self.s, "{")?;
1892 self.print_inner_attributes_inline(attrs)?;
1897 s.ibox(INDENT_UNIT)?;
1898 if !field.is_shorthand {
1899 s.print_ident(field.ident.node)?;
1902 s.print_expr(&field.expr)?;
1908 self.ibox(INDENT_UNIT)?;
1909 if !fields.is_empty() {
1910 word(&mut self.s, ",")?;
1911 space(&mut self.s)?;
1913 word(&mut self.s, "..")?;
1914 self.print_expr(&expr)?;
1917 _ => if !fields.is_empty() {
1918 word(&mut self.s, ",")?
1921 word(&mut self.s, "}")?;
1925 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1926 attrs: &[Attribute]) -> io::Result<()> {
1928 self.print_inner_attributes_inline(attrs)?;
1929 self.commasep_exprs(Inconsistent, &exprs[..])?;
1930 if exprs.len() == 1 {
1931 word(&mut self.s, ",")?;
1936 fn print_expr_call(&mut self,
1938 args: &[P<ast::Expr>]) -> io::Result<()> {
1939 self.print_expr_maybe_paren(func)?;
1940 self.print_call_post(args)
1943 fn print_expr_method_call(&mut self,
1944 ident: ast::SpannedIdent,
1946 args: &[P<ast::Expr>]) -> io::Result<()> {
1947 let base_args = &args[1..];
1948 self.print_expr(&args[0])?;
1949 word(&mut self.s, ".")?;
1950 self.print_ident(ident.node)?;
1951 if !tys.is_empty() {
1952 word(&mut self.s, "::<")?;
1953 self.commasep(Inconsistent, tys,
1954 |s, ty| s.print_type(&ty))?;
1955 word(&mut self.s, ">")?;
1957 self.print_call_post(base_args)
1960 fn print_expr_binary(&mut self,
1963 rhs: &ast::Expr) -> io::Result<()> {
1964 if self.check_expr_bin_needs_paren(lhs, op) {
1965 self.print_expr_maybe_paren(lhs)?;
1967 self.print_expr(lhs)?;
1969 space(&mut self.s)?;
1970 self.word_space(op.node.to_string())?;
1971 if self.check_expr_bin_needs_paren(rhs, op) {
1972 self.print_expr_maybe_paren(rhs)
1974 self.print_expr(rhs)
1978 fn print_expr_unary(&mut self,
1980 expr: &ast::Expr) -> io::Result<()> {
1981 word(&mut self.s, ast::UnOp::to_string(op))?;
1982 self.print_expr_maybe_paren(expr)
1985 fn print_expr_addr_of(&mut self,
1986 mutability: ast::Mutability,
1987 expr: &ast::Expr) -> io::Result<()> {
1988 word(&mut self.s, "&")?;
1989 self.print_mutability(mutability)?;
1990 self.print_expr_maybe_paren(expr)
1993 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1994 self.print_expr_outer_attr_style(expr, true)
1997 fn print_expr_outer_attr_style(&mut self,
1999 is_inline: bool) -> io::Result<()> {
2000 self.maybe_print_comment(expr.span.lo)?;
2002 let attrs = &expr.attrs;
2004 self.print_outer_attributes_inline(attrs)?;
2006 self.print_outer_attributes(attrs)?;
2009 self.ibox(INDENT_UNIT)?;
2010 self.ann.pre(self, NodeExpr(expr))?;
2012 ast::ExprKind::Box(ref expr) => {
2013 self.word_space("box")?;
2014 self.print_expr(expr)?;
2016 ast::ExprKind::InPlace(ref place, ref expr) => {
2017 self.print_expr_in_place(place, expr)?;
2019 ast::ExprKind::Array(ref exprs) => {
2020 self.print_expr_vec(&exprs[..], attrs)?;
2022 ast::ExprKind::Repeat(ref element, ref count) => {
2023 self.print_expr_repeat(&element, &count, attrs)?;
2025 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2026 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2028 ast::ExprKind::Tup(ref exprs) => {
2029 self.print_expr_tup(&exprs[..], attrs)?;
2031 ast::ExprKind::Call(ref func, ref args) => {
2032 self.print_expr_call(&func, &args[..])?;
2034 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2035 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2037 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2038 self.print_expr_binary(op, &lhs, &rhs)?;
2040 ast::ExprKind::Unary(op, ref expr) => {
2041 self.print_expr_unary(op, &expr)?;
2043 ast::ExprKind::AddrOf(m, ref expr) => {
2044 self.print_expr_addr_of(m, &expr)?;
2046 ast::ExprKind::Lit(ref lit) => {
2047 self.print_literal(&lit)?;
2049 ast::ExprKind::Cast(ref expr, ref ty) => {
2050 if let ast::ExprKind::Cast(..) = expr.node {
2051 self.print_expr(&expr)?;
2053 self.print_expr_maybe_paren(&expr)?;
2055 space(&mut self.s)?;
2056 self.word_space("as")?;
2057 self.print_type(&ty)?;
2059 ast::ExprKind::Type(ref expr, ref ty) => {
2060 self.print_expr(&expr)?;
2061 self.word_space(":")?;
2062 self.print_type(&ty)?;
2064 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2065 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2067 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2068 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2070 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2071 if let Some(ident) = opt_ident {
2072 self.print_ident(ident.node)?;
2073 self.word_space(":")?;
2075 self.head("while")?;
2076 self.print_expr(&test)?;
2077 space(&mut self.s)?;
2078 self.print_block_with_attrs(&blk, attrs)?;
2080 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2081 if let Some(ident) = opt_ident {
2082 self.print_ident(ident.node)?;
2083 self.word_space(":")?;
2085 self.head("while let")?;
2086 self.print_pat(&pat)?;
2087 space(&mut self.s)?;
2088 self.word_space("=")?;
2089 self.print_expr(&expr)?;
2090 space(&mut self.s)?;
2091 self.print_block_with_attrs(&blk, attrs)?;
2093 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2094 if let Some(ident) = opt_ident {
2095 self.print_ident(ident.node)?;
2096 self.word_space(":")?;
2099 self.print_pat(&pat)?;
2100 space(&mut self.s)?;
2101 self.word_space("in")?;
2102 self.print_expr(&iter)?;
2103 space(&mut self.s)?;
2104 self.print_block_with_attrs(&blk, attrs)?;
2106 ast::ExprKind::Loop(ref blk, opt_ident) => {
2107 if let Some(ident) = opt_ident {
2108 self.print_ident(ident.node)?;
2109 self.word_space(":")?;
2112 space(&mut self.s)?;
2113 self.print_block_with_attrs(&blk, attrs)?;
2115 ast::ExprKind::Match(ref expr, ref arms) => {
2116 self.cbox(INDENT_UNIT)?;
2118 self.word_nbsp("match")?;
2119 self.print_expr(&expr)?;
2120 space(&mut self.s)?;
2122 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2124 self.print_arm(arm)?;
2126 self.bclose_(expr.span, INDENT_UNIT)?;
2128 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2129 self.print_capture_clause(capture_clause)?;
2131 self.print_fn_block_args(&decl)?;
2132 space(&mut self.s)?;
2133 self.print_expr(body)?;
2134 self.end()?; // need to close a box
2136 // a box will be closed by print_expr, but we didn't want an overall
2137 // wrapper so we closed the corresponding opening. so create an
2138 // empty box to satisfy the close.
2141 ast::ExprKind::Block(ref blk) => {
2142 // containing cbox, will be closed by print-block at }
2143 self.cbox(INDENT_UNIT)?;
2144 // head-box, will be closed by print-block after {
2146 self.print_block_with_attrs(&blk, attrs)?;
2148 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2149 self.print_expr(&lhs)?;
2150 space(&mut self.s)?;
2151 self.word_space("=")?;
2152 self.print_expr(&rhs)?;
2154 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2155 self.print_expr(&lhs)?;
2156 space(&mut self.s)?;
2157 word(&mut self.s, op.node.to_string())?;
2158 self.word_space("=")?;
2159 self.print_expr(&rhs)?;
2161 ast::ExprKind::Field(ref expr, id) => {
2162 self.print_expr(&expr)?;
2163 word(&mut self.s, ".")?;
2164 self.print_ident(id.node)?;
2166 ast::ExprKind::TupField(ref expr, id) => {
2167 self.print_expr(&expr)?;
2168 word(&mut self.s, ".")?;
2169 self.print_usize(id.node)?;
2171 ast::ExprKind::Index(ref expr, ref index) => {
2172 self.print_expr(&expr)?;
2173 word(&mut self.s, "[")?;
2174 self.print_expr(&index)?;
2175 word(&mut self.s, "]")?;
2177 ast::ExprKind::Range(ref start, ref end, limits) => {
2178 if let &Some(ref e) = start {
2179 self.print_expr(&e)?;
2181 if limits == ast::RangeLimits::HalfOpen {
2182 word(&mut self.s, "..")?;
2184 word(&mut self.s, "...")?;
2186 if let &Some(ref e) = end {
2187 self.print_expr(&e)?;
2190 ast::ExprKind::Path(None, ref path) => {
2191 self.print_path(path, true, 0, false)?
2193 ast::ExprKind::Path(Some(ref qself), ref path) => {
2194 self.print_qpath(path, qself, true)?
2196 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2197 word(&mut self.s, "break")?;
2198 space(&mut self.s)?;
2199 if let Some(ident) = opt_ident {
2200 self.print_ident(ident.node)?;
2201 space(&mut self.s)?;
2203 if let Some(ref expr) = *opt_expr {
2204 self.print_expr(expr)?;
2205 space(&mut self.s)?;
2208 ast::ExprKind::Continue(opt_ident) => {
2209 word(&mut self.s, "continue")?;
2210 space(&mut self.s)?;
2211 if let Some(ident) = opt_ident {
2212 self.print_ident(ident.node)?;
2216 ast::ExprKind::Ret(ref result) => {
2217 word(&mut self.s, "return")?;
2220 word(&mut self.s, " ")?;
2221 self.print_expr(&expr)?;
2226 ast::ExprKind::InlineAsm(ref a) => {
2227 word(&mut self.s, "asm!")?;
2229 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2230 self.word_space(":")?;
2232 self.commasep(Inconsistent, &a.outputs, |s, out| {
2233 let constraint = out.constraint.as_str();
2234 let mut ch = constraint.chars();
2236 Some('=') if out.is_rw => {
2237 s.print_string(&format!("+{}", ch.as_str()),
2238 ast::StrStyle::Cooked)?
2240 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2243 s.print_expr(&out.expr)?;
2247 space(&mut self.s)?;
2248 self.word_space(":")?;
2250 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2251 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2257 space(&mut self.s)?;
2258 self.word_space(":")?;
2260 self.commasep(Inconsistent, &a.clobbers,
2262 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2266 let mut options = vec![];
2268 options.push("volatile");
2271 options.push("alignstack");
2273 if a.dialect == ast::AsmDialect::Intel {
2274 options.push("intel");
2277 if !options.is_empty() {
2278 space(&mut self.s)?;
2279 self.word_space(":")?;
2280 self.commasep(Inconsistent, &options,
2282 s.print_string(co, ast::StrStyle::Cooked)?;
2289 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2290 ast::ExprKind::Paren(ref e) => {
2292 self.print_inner_attributes_inline(attrs)?;
2293 self.print_expr(&e)?;
2296 ast::ExprKind::Try(ref e) => {
2297 self.print_expr(e)?;
2298 word(&mut self.s, "?")?
2300 ast::ExprKind::Catch(ref blk) => {
2301 self.head("do catch")?;
2302 space(&mut self.s)?;
2303 self.print_block_with_attrs(&blk, attrs)?
2306 self.ann.post(self, NodeExpr(expr))?;
2310 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2311 self.print_pat(&loc.pat)?;
2312 if let Some(ref ty) = loc.ty {
2313 self.word_space(":")?;
2314 self.print_type(&ty)?;
2319 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2320 word(&mut self.s, &ident.name.as_str())?;
2321 self.ann.post(self, NodeIdent(&ident))
2324 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2325 word(&mut self.s, &i.to_string())
2328 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2329 word(&mut self.s, &name.as_str())?;
2330 self.ann.post(self, NodeName(&name))
2333 pub fn print_for_decl(&mut self, loc: &ast::Local,
2334 coll: &ast::Expr) -> io::Result<()> {
2335 self.print_local_decl(loc)?;
2336 space(&mut self.s)?;
2337 self.word_space("in")?;
2338 self.print_expr(coll)
2341 fn print_path(&mut self,
2343 colons_before_params: bool,
2345 defaults_to_global: bool)
2348 self.maybe_print_comment(path.span.lo)?;
2350 let mut segments = path.segments[..path.segments.len()-depth].iter();
2351 if defaults_to_global && path.is_global() {
2354 for (i, segment) in segments.enumerate() {
2356 word(&mut self.s, "::")?
2358 if segment.identifier.name != keywords::CrateRoot.name() &&
2359 segment.identifier.name != "$crate" {
2360 self.print_ident(segment.identifier)?;
2361 if let Some(ref parameters) = segment.parameters {
2362 self.print_path_parameters(parameters, colons_before_params)?;
2370 fn print_qpath(&mut self,
2373 colons_before_params: bool)
2376 word(&mut self.s, "<")?;
2377 self.print_type(&qself.ty)?;
2378 if qself.position > 0 {
2379 space(&mut self.s)?;
2380 self.word_space("as")?;
2381 let depth = path.segments.len() - qself.position;
2382 self.print_path(&path, false, depth, false)?;
2384 word(&mut self.s, ">")?;
2385 word(&mut self.s, "::")?;
2386 let item_segment = path.segments.last().unwrap();
2387 self.print_ident(item_segment.identifier)?;
2388 match item_segment.parameters {
2389 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2394 fn print_path_parameters(&mut self,
2395 parameters: &ast::PathParameters,
2396 colons_before_params: bool)
2399 if colons_before_params {
2400 word(&mut self.s, "::")?
2404 ast::PathParameters::AngleBracketed(ref data) => {
2405 word(&mut self.s, "<")?;
2407 let mut comma = false;
2408 for lifetime in &data.lifetimes {
2410 self.word_space(",")?
2412 self.print_lifetime(lifetime)?;
2416 if !data.types.is_empty() {
2418 self.word_space(",")?
2423 |s, ty| s.print_type(&ty))?;
2427 for binding in data.bindings.iter() {
2429 self.word_space(",")?
2431 self.print_ident(binding.ident)?;
2432 space(&mut self.s)?;
2433 self.word_space("=")?;
2434 self.print_type(&binding.ty)?;
2438 word(&mut self.s, ">")?
2441 ast::PathParameters::Parenthesized(ref data) => {
2442 word(&mut self.s, "(")?;
2446 |s, ty| s.print_type(&ty))?;
2447 word(&mut self.s, ")")?;
2449 if let Some(ref ty) = data.output {
2450 self.space_if_not_bol()?;
2451 self.word_space("->")?;
2452 self.print_type(&ty)?;
2460 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2461 self.maybe_print_comment(pat.span.lo)?;
2462 self.ann.pre(self, NodePat(pat))?;
2463 /* Pat isn't normalized, but the beauty of it
2464 is that it doesn't matter */
2466 PatKind::Wild => word(&mut self.s, "_")?,
2467 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2468 match binding_mode {
2469 ast::BindingMode::ByRef(mutbl) => {
2470 self.word_nbsp("ref")?;
2471 self.print_mutability(mutbl)?;
2473 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2474 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2475 self.word_nbsp("mut")?;
2478 self.print_ident(path1.node)?;
2479 if let Some(ref p) = *sub {
2480 word(&mut self.s, "@")?;
2481 self.print_pat(&p)?;
2484 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2485 self.print_path(path, true, 0, false)?;
2487 if let Some(ddpos) = ddpos {
2488 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2490 self.word_space(",")?;
2492 word(&mut self.s, "..")?;
2493 if ddpos != elts.len() {
2494 word(&mut self.s, ",")?;
2495 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2498 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2502 PatKind::Path(None, ref path) => {
2503 self.print_path(path, true, 0, false)?;
2505 PatKind::Path(Some(ref qself), ref path) => {
2506 self.print_qpath(path, qself, false)?;
2508 PatKind::Struct(ref path, ref fields, etc) => {
2509 self.print_path(path, true, 0, false)?;
2511 self.word_space("{")?;
2513 Consistent, &fields[..],
2515 s.cbox(INDENT_UNIT)?;
2516 if !f.node.is_shorthand {
2517 s.print_ident(f.node.ident)?;
2520 s.print_pat(&f.node.pat)?;
2523 |f| f.node.pat.span)?;
2525 if !fields.is_empty() { self.word_space(",")?; }
2526 word(&mut self.s, "..")?;
2528 space(&mut self.s)?;
2529 word(&mut self.s, "}")?;
2531 PatKind::Tuple(ref elts, ddpos) => {
2533 if let Some(ddpos) = ddpos {
2534 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2536 self.word_space(",")?;
2538 word(&mut self.s, "..")?;
2539 if ddpos != elts.len() {
2540 word(&mut self.s, ",")?;
2541 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2544 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2545 if elts.len() == 1 {
2546 word(&mut self.s, ",")?;
2551 PatKind::Box(ref inner) => {
2552 word(&mut self.s, "box ")?;
2553 self.print_pat(&inner)?;
2555 PatKind::Ref(ref inner, mutbl) => {
2556 word(&mut self.s, "&")?;
2557 if mutbl == ast::Mutability::Mutable {
2558 word(&mut self.s, "mut ")?;
2560 self.print_pat(&inner)?;
2562 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2563 PatKind::Range(ref begin, ref end, ref end_kind) => {
2564 self.print_expr(&begin)?;
2565 space(&mut self.s)?;
2567 RangeEnd::Included => word(&mut self.s, "...")?,
2568 RangeEnd::Excluded => word(&mut self.s, "..")?,
2570 self.print_expr(&end)?;
2572 PatKind::Slice(ref before, ref slice, ref after) => {
2573 word(&mut self.s, "[")?;
2574 self.commasep(Inconsistent,
2576 |s, p| s.print_pat(&p))?;
2577 if let Some(ref p) = *slice {
2578 if !before.is_empty() { self.word_space(",")?; }
2579 if p.node != PatKind::Wild {
2580 self.print_pat(&p)?;
2582 word(&mut self.s, "..")?;
2583 if !after.is_empty() { self.word_space(",")?; }
2585 self.commasep(Inconsistent,
2587 |s, p| s.print_pat(&p))?;
2588 word(&mut self.s, "]")?;
2590 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2592 self.ann.post(self, NodePat(pat))
2595 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2596 // I have no idea why this check is necessary, but here it
2598 if arm.attrs.is_empty() {
2599 space(&mut self.s)?;
2601 self.cbox(INDENT_UNIT)?;
2603 self.maybe_print_comment(arm.pats[0].span.lo)?;
2604 self.print_outer_attributes(&arm.attrs)?;
2605 let mut first = true;
2606 for p in &arm.pats {
2610 space(&mut self.s)?;
2611 self.word_space("|")?;
2613 self.print_pat(&p)?;
2615 space(&mut self.s)?;
2616 if let Some(ref e) = arm.guard {
2617 self.word_space("if")?;
2618 self.print_expr(&e)?;
2619 space(&mut self.s)?;
2621 self.word_space("=>")?;
2623 match arm.body.node {
2624 ast::ExprKind::Block(ref blk) => {
2625 // the block will close the pattern's ibox
2626 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2628 // If it is a user-provided unsafe block, print a comma after it
2629 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2630 word(&mut self.s, ",")?;
2634 self.end()?; // close the ibox for the pattern
2635 self.print_expr(&arm.body)?;
2636 word(&mut self.s, ",")?;
2639 self.end() // close enclosing cbox
2642 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2643 match explicit_self.node {
2644 SelfKind::Value(m) => {
2645 self.print_mutability(m)?;
2646 word(&mut self.s, "self")
2648 SelfKind::Region(ref lt, m) => {
2649 word(&mut self.s, "&")?;
2650 self.print_opt_lifetime(lt)?;
2651 self.print_mutability(m)?;
2652 word(&mut self.s, "self")
2654 SelfKind::Explicit(ref typ, m) => {
2655 self.print_mutability(m)?;
2656 word(&mut self.s, "self")?;
2657 self.word_space(":")?;
2658 self.print_type(&typ)
2663 pub fn print_fn(&mut self,
2665 unsafety: ast::Unsafety,
2666 constness: ast::Constness,
2668 name: Option<ast::Ident>,
2669 generics: &ast::Generics,
2670 vis: &ast::Visibility) -> io::Result<()> {
2671 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2673 if let Some(name) = name {
2675 self.print_ident(name)?;
2677 self.print_generics(generics)?;
2678 self.print_fn_args_and_ret(decl)?;
2679 self.print_where_clause(&generics.where_clause)
2682 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2685 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2687 word(&mut self.s, ", ...")?;
2691 self.print_fn_output(decl)
2694 pub fn print_fn_block_args(
2698 word(&mut self.s, "|")?;
2699 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2700 word(&mut self.s, "|")?;
2702 if let ast::FunctionRetTy::Default(..) = decl.output {
2706 self.space_if_not_bol()?;
2707 self.word_space("->")?;
2709 ast::FunctionRetTy::Ty(ref ty) => {
2710 self.print_type(&ty)?;
2711 self.maybe_print_comment(ty.span.lo)
2713 ast::FunctionRetTy::Default(..) => unreachable!(),
2717 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2719 match capture_clause {
2720 ast::CaptureBy::Value => self.word_space("move"),
2721 ast::CaptureBy::Ref => Ok(()),
2725 pub fn print_bounds(&mut self,
2727 bounds: &[ast::TyParamBound])
2729 if !bounds.is_empty() {
2730 word(&mut self.s, prefix)?;
2731 let mut first = true;
2732 for bound in bounds {
2737 self.word_space("+")?;
2741 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2742 self.print_poly_trait_ref(tref)
2744 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2745 word(&mut self.s, "?")?;
2746 self.print_poly_trait_ref(tref)
2748 RegionTyParamBound(ref lt) => {
2749 self.print_lifetime(lt)
2759 pub fn print_lifetime(&mut self,
2760 lifetime: &ast::Lifetime)
2763 self.print_name(lifetime.name)
2766 pub fn print_lifetime_bounds(&mut self,
2767 lifetime: &ast::Lifetime,
2768 bounds: &[ast::Lifetime])
2771 self.print_lifetime(lifetime)?;
2772 if !bounds.is_empty() {
2773 word(&mut self.s, ": ")?;
2774 for (i, bound) in bounds.iter().enumerate() {
2776 word(&mut self.s, " + ")?;
2778 self.print_lifetime(bound)?;
2784 pub fn print_generics(&mut self,
2785 generics: &ast::Generics)
2788 let total = generics.lifetimes.len() + generics.ty_params.len();
2793 word(&mut self.s, "<")?;
2795 let mut ints = Vec::new();
2800 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2801 if idx < generics.lifetimes.len() {
2802 let lifetime_def = &generics.lifetimes[idx];
2803 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2804 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2806 let idx = idx - generics.lifetimes.len();
2807 let param = &generics.ty_params[idx];
2808 s.print_ty_param(param)
2812 word(&mut self.s, ">")?;
2816 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2817 self.print_outer_attributes_inline(¶m.attrs)?;
2818 self.print_ident(param.ident)?;
2819 self.print_bounds(":", ¶m.bounds)?;
2820 match param.default {
2821 Some(ref default) => {
2822 space(&mut self.s)?;
2823 self.word_space("=")?;
2824 self.print_type(&default)
2830 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2832 if where_clause.predicates.is_empty() {
2836 space(&mut self.s)?;
2837 self.word_space("where")?;
2839 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2841 self.word_space(",")?;
2845 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2849 self.print_formal_lifetime_list(bound_lifetimes)?;
2850 self.print_type(&bounded_ty)?;
2851 self.print_bounds(":", bounds)?;
2853 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2856 self.print_lifetime_bounds(lifetime, bounds)?;
2858 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2861 self.print_type(lhs_ty)?;
2862 space(&mut self.s)?;
2863 self.word_space("=")?;
2864 self.print_type(rhs_ty)?;
2872 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2874 ast::ViewPathSimple(ident, ref path) => {
2875 self.print_path(path, false, 0, true)?;
2877 if path.segments.last().unwrap().identifier.name !=
2879 space(&mut self.s)?;
2880 self.word_space("as")?;
2881 self.print_ident(ident)?;
2887 ast::ViewPathGlob(ref path) => {
2888 self.print_path(path, false, 0, true)?;
2889 word(&mut self.s, "::*")
2892 ast::ViewPathList(ref path, ref idents) => {
2893 if path.segments.is_empty() {
2894 word(&mut self.s, "{")?;
2896 self.print_path(path, false, 0, true)?;
2897 word(&mut self.s, "::{")?;
2899 self.commasep(Inconsistent, &idents[..], |s, w| {
2900 s.print_ident(w.node.name)?;
2901 if let Some(ident) = w.node.rename {
2903 s.word_space("as")?;
2904 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::Default(..) => unreachable!(),
2961 ast::FunctionRetTy::Ty(ref ty) =>
2962 self.print_type(&ty)?
2967 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2972 pub fn print_ty_fn(&mut self,
2974 unsafety: ast::Unsafety,
2976 name: Option<ast::Ident>,
2977 generics: &ast::Generics)
2979 self.ibox(INDENT_UNIT)?;
2980 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2981 word(&mut self.s, "for")?;
2982 self.print_generics(generics)?;
2984 let generics = ast::Generics {
2985 lifetimes: Vec::new(),
2986 ty_params: Vec::new(),
2987 where_clause: ast::WhereClause {
2988 id: ast::DUMMY_NODE_ID,
2989 predicates: Vec::new(),
2991 span: syntax_pos::DUMMY_SP,
2995 ast::Constness::NotConst,
2999 &ast::Visibility::Inherited)?;
3003 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3004 next_pos: Option<BytePos>)
3006 let cm = match self.cm {
3010 if let Some(ref cmnt) = self.next_comment() {
3011 if cmnt.style != comments::Trailing { return Ok(()) }
3012 let span_line = cm.lookup_char_pos(span.hi);
3013 let comment_line = cm.lookup_char_pos(cmnt.pos);
3014 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3015 if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3016 self.print_comment(cmnt)?;
3017 self.cur_cmnt_and_lit.cur_cmnt += 1;
3023 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3024 // If there aren't any remaining comments, then we need to manually
3025 // make sure there is a line break at the end.
3026 if self.next_comment().is_none() {
3027 hardbreak(&mut self.s)?;
3030 match self.next_comment() {
3032 self.print_comment(cmnt)?;
3033 self.cur_cmnt_and_lit.cur_cmnt += 1;
3041 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3042 opt_abi: Option<Abi>)
3045 Some(Abi::Rust) => Ok(()),
3047 self.word_nbsp("extern")?;
3048 self.word_nbsp(&abi.to_string())
3054 pub fn print_extern_opt_abi(&mut self,
3055 opt_abi: Option<Abi>) -> io::Result<()> {
3058 self.word_nbsp("extern")?;
3059 self.word_nbsp(&abi.to_string())
3065 pub fn print_fn_header_info(&mut self,
3066 unsafety: ast::Unsafety,
3067 constness: ast::Constness,
3069 vis: &ast::Visibility) -> io::Result<()> {
3070 word(&mut self.s, &visibility_qualified(vis, ""))?;
3073 ast::Constness::NotConst => {}
3074 ast::Constness::Const => self.word_nbsp("const")?
3077 self.print_unsafety(unsafety)?;
3079 if abi != Abi::Rust {
3080 self.word_nbsp("extern")?;
3081 self.word_nbsp(&abi.to_string())?;
3084 word(&mut self.s, "fn")
3087 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3089 ast::Unsafety::Normal => Ok(()),
3090 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3095 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3106 fn test_fun_to_string() {
3107 let abba_ident = ast::Ident::from_str("abba");
3109 let decl = ast::FnDecl {
3111 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3114 let generics = ast::Generics::default();
3115 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3116 ast::Constness::NotConst,
3117 abba_ident, &generics),
3122 fn test_variant_to_string() {
3123 let ident = ast::Ident::from_str("principal_skinner");
3125 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3128 // making this up as I go.... ?
3129 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3133 let varstr = variant_to_string(&var);
3134 assert_eq!(varstr, "principal_skinner");