1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
14 use ast::{self, BlockCheckMode, PatKind, RangeEnd};
15 use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use util::parser::AssocOp;
19 use codemap::{self, CodeMap};
20 use syntax_pos::{self, BytePos};
21 use parse::token::{self, BinOpToken, Token};
22 use parse::lexer::comments;
23 use parse::{self, ParseSess};
24 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
25 use print::pp::{Breaks, eof};
26 use print::pp::Breaks::{Consistent, Inconsistent};
29 use symbol::{Symbol, keywords};
30 use syntax_pos::DUMMY_SP;
31 use tokenstream::{self, TokenStream, TokenTree};
34 use std::io::{self, Write, Read};
37 pub enum AnnNode<'a> {
38 NodeIdent(&'a ast::Ident),
39 NodeName(&'a ast::Name),
40 NodeBlock(&'a ast::Block),
41 NodeItem(&'a ast::Item),
42 NodeSubItem(ast::NodeId),
43 NodeExpr(&'a ast::Expr),
44 NodePat(&'a ast::Pat),
48 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
49 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
52 #[derive(Copy, Clone)]
55 impl PpAnn for NoAnn {}
57 #[derive(Copy, Clone)]
58 pub struct CurrentCommentAndLiteral {
63 pub struct State<'a> {
64 pub s: pp::Printer<'a>,
65 cm: Option<&'a CodeMap>,
66 comments: Option<Vec<comments::Comment> >,
67 literals: Option<Vec<comments::Literal> >,
68 cur_cmnt_and_lit: CurrentCommentAndLiteral,
69 boxes: Vec<pp::Breaks>,
73 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
74 static NO_ANN: NoAnn = NoAnn;
75 rust_printer_annotated(writer, &NO_ANN)
78 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
79 ann: &'a PpAnn) -> State<'a> {
81 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
85 cur_cmnt_and_lit: CurrentCommentAndLiteral {
94 pub const INDENT_UNIT: usize = 4;
96 pub const DEFAULT_COLUMNS: usize = 78;
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
101 pub fn print_crate<'a>(cm: &'a CodeMap,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
111 if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
112 // We need to print `#![no_std]` (and its feature gate) so that
113 // compiling pretty-printed source won't inject libstd again.
114 // However we don't want these attributes in the AST because
115 // of the feature gate, so we fake them up here.
117 // #![feature(prelude_import)]
118 let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
119 let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
120 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
121 s.print_attribute(&fake_attr)?;
124 let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
125 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
126 s.print_attribute(&fake_attr)?;
129 s.print_mod(&krate.module, &krate.attrs)?;
130 s.print_remaining_comments()?;
135 pub fn new_from_input(cm: &'a CodeMap,
141 is_expanded: bool) -> State<'a> {
142 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
149 // If the code is post expansion, don't use the table of
150 // literals, since it doesn't correspond with the literals
151 // in the AST anymore.
152 if is_expanded { None } else { Some(lits) })
155 pub fn new(cm: &'a CodeMap,
158 comments: Option<Vec<comments::Comment>>,
159 literals: Option<Vec<comments::Literal>>) -> State<'a> {
161 s: pp::mk_printer(out, DEFAULT_COLUMNS),
165 cur_cmnt_and_lit: CurrentCommentAndLiteral {
175 pub fn to_string<F>(f: F) -> String where
176 F: FnOnce(&mut State) -> io::Result<()>,
178 let mut wr = Vec::new();
180 let mut printer = rust_printer(Box::new(&mut wr));
181 f(&mut printer).unwrap();
182 eof(&mut printer.s).unwrap();
184 String::from_utf8(wr).unwrap()
187 pub fn binop_to_string(op: BinOpToken) -> &'static str {
193 token::Percent => "%",
202 pub fn token_to_string(tok: &Token) -> String {
204 token::Eq => "=".to_string(),
205 token::Lt => "<".to_string(),
206 token::Le => "<=".to_string(),
207 token::EqEq => "==".to_string(),
208 token::Ne => "!=".to_string(),
209 token::Ge => ">=".to_string(),
210 token::Gt => ">".to_string(),
211 token::Not => "!".to_string(),
212 token::Tilde => "~".to_string(),
213 token::OrOr => "||".to_string(),
214 token::AndAnd => "&&".to_string(),
215 token::BinOp(op) => binop_to_string(op).to_string(),
216 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
218 /* Structural symbols */
219 token::At => "@".to_string(),
220 token::Dot => ".".to_string(),
221 token::DotDot => "..".to_string(),
222 token::DotDotDot => "...".to_string(),
223 token::Comma => ",".to_string(),
224 token::Semi => ";".to_string(),
225 token::Colon => ":".to_string(),
226 token::ModSep => "::".to_string(),
227 token::RArrow => "->".to_string(),
228 token::LArrow => "<-".to_string(),
229 token::FatArrow => "=>".to_string(),
230 token::OpenDelim(token::Paren) => "(".to_string(),
231 token::CloseDelim(token::Paren) => ")".to_string(),
232 token::OpenDelim(token::Bracket) => "[".to_string(),
233 token::CloseDelim(token::Bracket) => "]".to_string(),
234 token::OpenDelim(token::Brace) => "{".to_string(),
235 token::CloseDelim(token::Brace) => "}".to_string(),
236 token::OpenDelim(token::NoDelim) => " ".to_string(),
237 token::CloseDelim(token::NoDelim) => " ".to_string(),
238 token::Pound => "#".to_string(),
239 token::Dollar => "$".to_string(),
240 token::Question => "?".to_string(),
243 token::Literal(lit, suf) => {
244 let mut out = match lit {
245 token::Byte(b) => format!("b'{}'", b),
246 token::Char(c) => format!("'{}'", c),
247 token::Float(c) => c.to_string(),
248 token::Integer(c) => c.to_string(),
249 token::Str_(s) => format!("\"{}\"", s),
250 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
251 delim=repeat("#", n),
253 token::ByteStr(v) => format!("b\"{}\"", v),
254 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
255 delim=repeat("#", n),
259 if let Some(s) = suf {
260 out.push_str(&s.as_str())
266 /* Name components */
267 token::Ident(s) => s.to_string(),
268 token::Lifetime(s) => s.to_string(),
269 token::Underscore => "_".to_string(),
272 token::DocComment(s) => s.to_string(),
273 token::SubstNt(s) => format!("${}", s),
274 token::Eof => "<eof>".to_string(),
275 token::Whitespace => " ".to_string(),
276 token::Comment => "/* */".to_string(),
277 token::Shebang(s) => format!("/* shebang: {}*/", s),
279 token::Interpolated(ref nt) => match **nt {
280 token::NtExpr(ref e) => expr_to_string(&e),
281 token::NtMeta(ref e) => meta_item_to_string(&e),
282 token::NtTy(ref e) => ty_to_string(&e),
283 token::NtPath(ref e) => path_to_string(&e),
284 token::NtItem(ref e) => item_to_string(&e),
285 token::NtBlock(ref e) => block_to_string(&e),
286 token::NtStmt(ref e) => stmt_to_string(&e),
287 token::NtPat(ref e) => pat_to_string(&e),
288 token::NtIdent(ref e) => ident_to_string(e.node),
289 token::NtTT(ref tree) => tt_to_string(tree.clone()),
290 token::NtArm(ref e) => arm_to_string(&e),
291 token::NtImplItem(ref e) => impl_item_to_string(&e),
292 token::NtTraitItem(ref e) => trait_item_to_string(&e),
293 token::NtGenerics(ref e) => generics_to_string(&e),
294 token::NtWhereClause(ref e) => where_clause_to_string(&e),
295 token::NtArg(ref e) => arg_to_string(&e),
300 pub fn ty_to_string(ty: &ast::Ty) -> String {
301 to_string(|s| s.print_type(ty))
304 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
305 to_string(|s| s.print_bounds("", bounds))
308 pub fn pat_to_string(pat: &ast::Pat) -> String {
309 to_string(|s| s.print_pat(pat))
312 pub fn arm_to_string(arm: &ast::Arm) -> String {
313 to_string(|s| s.print_arm(arm))
316 pub fn expr_to_string(e: &ast::Expr) -> String {
317 to_string(|s| s.print_expr(e))
320 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
321 to_string(|s| s.print_lifetime(e))
324 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
325 to_string(|s| s.print_tt(tt))
328 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
329 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
332 pub fn tokens_to_string(tokens: TokenStream) -> String {
333 to_string(|s| s.print_tts(tokens))
336 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
337 to_string(|s| s.print_stmt(stmt))
340 pub fn attr_to_string(attr: &ast::Attribute) -> String {
341 to_string(|s| s.print_attribute(attr))
344 pub fn item_to_string(i: &ast::Item) -> String {
345 to_string(|s| s.print_item(i))
348 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
349 to_string(|s| s.print_impl_item(i))
352 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
353 to_string(|s| s.print_trait_item(i))
356 pub fn generics_to_string(generics: &ast::Generics) -> String {
357 to_string(|s| s.print_generics(generics))
360 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
361 to_string(|s| s.print_where_clause(i))
364 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
365 to_string(|s| s.print_fn_block_args(p))
368 pub fn path_to_string(p: &ast::Path) -> String {
369 to_string(|s| s.print_path(p, false, 0, false))
372 pub fn ident_to_string(id: ast::Ident) -> String {
373 to_string(|s| s.print_ident(id))
376 pub fn fun_to_string(decl: &ast::FnDecl,
377 unsafety: ast::Unsafety,
378 constness: ast::Constness,
380 generics: &ast::Generics)
384 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
385 generics, &ast::Visibility::Inherited)?;
386 s.end()?; // Close the head box
387 s.end() // Close the outer box
391 pub fn block_to_string(blk: &ast::Block) -> String {
393 // containing cbox, will be closed by print-block at }
394 s.cbox(INDENT_UNIT)?;
395 // head-ibox, will be closed by print-block after {
401 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
402 to_string(|s| s.print_meta_list_item(li))
405 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
406 to_string(|s| s.print_meta_item(mi))
409 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
410 to_string(|s| s.print_attribute(attr))
413 pub fn lit_to_string(l: &ast::Lit) -> String {
414 to_string(|s| s.print_literal(l))
417 pub fn variant_to_string(var: &ast::Variant) -> String {
418 to_string(|s| s.print_variant(var))
421 pub fn arg_to_string(arg: &ast::Arg) -> String {
422 to_string(|s| s.print_arg(arg, false))
425 pub fn mac_to_string(arg: &ast::Mac) -> String {
426 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
429 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 ast::Visibility::Public => format!("pub {}", s),
432 ast::Visibility::Crate(_) => format!("pub(crate) {}", s),
433 ast::Visibility::Restricted { ref path, .. } =>
434 format!("pub({}) {}", to_string(|s| s.print_path(path, false, 0, true)), s),
435 ast::Visibility::Inherited => s.to_string()
439 fn needs_parentheses(expr: &ast::Expr) -> bool {
441 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
442 ast::ExprKind::Closure(..) |
443 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
444 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
449 pub trait PrintState<'a> {
450 fn writer(&mut self) -> &mut pp::Printer<'a>;
451 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
452 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
453 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
454 fn literals(&self) -> &Option<Vec<comments::Literal>>;
456 fn word_space(&mut self, w: &str) -> io::Result<()> {
457 word(self.writer(), w)?;
461 fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }
463 fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }
465 fn is_begin(&mut self) -> bool {
466 match self.writer().last_token() {
467 pp::Token::Begin(_) => true,
472 fn is_end(&mut self) -> bool {
473 match self.writer().last_token() {
474 pp::Token::End => true,
479 // is this the beginning of a line?
480 fn is_bol(&mut self) -> bool {
481 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
484 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
486 hardbreak(self.writer())?
492 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
493 self.boxes().push(b);
494 pp::rbox(self.writer(), u, b)
497 fn ibox(&mut self, u: usize) -> io::Result<()> {
498 self.boxes().push(pp::Breaks::Inconsistent);
499 pp::ibox(self.writer(), u)
502 fn end(&mut self) -> io::Result<()> {
503 self.boxes().pop().unwrap();
504 pp::end(self.writer())
507 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
508 where F: FnMut(&mut Self, &T) -> io::Result<()>,
511 let mut first = true;
513 if first { first = false; } else { self.word_space(",")?; }
519 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
520 let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;
522 let mut result = None;
524 if let &Some(ref lits) = self.literals()
526 while cur_lit < lits.len() {
527 let ltrl = (*lits)[cur_lit].clone();
528 if ltrl.pos > pos { break; }
537 self.cur_cmnt_and_lit().cur_lit = cur_lit;
541 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
542 while let Some(ref cmnt) = self.next_comment() {
544 self.print_comment(cmnt)?;
545 self.cur_cmnt_and_lit().cur_cmnt += 1;
553 fn print_comment(&mut self,
554 cmnt: &comments::Comment) -> io::Result<()> {
557 assert_eq!(cmnt.lines.len(), 1);
558 zerobreak(self.writer())?;
559 word(self.writer(), &cmnt.lines[0])?;
560 zerobreak(self.writer())
562 comments::Isolated => {
563 self.hardbreak_if_not_bol()?;
564 for line in &cmnt.lines {
565 // Don't print empty lines because they will end up as trailing
567 if !line.is_empty() {
568 word(self.writer(), &line[..])?;
570 hardbreak(self.writer())?;
574 comments::Trailing => {
576 word(self.writer(), " ")?;
578 if cmnt.lines.len() == 1 {
579 word(self.writer(), &cmnt.lines[0])?;
580 hardbreak(self.writer())
583 for line in &cmnt.lines {
584 if !line.is_empty() {
585 word(self.writer(), &line[..])?;
587 hardbreak(self.writer())?;
592 comments::BlankLine => {
593 // We need to do at least one, possibly two hardbreaks.
594 let is_semi = match self.writer().last_token() {
595 pp::Token::String(s, _) => ";" == s,
598 if is_semi || self.is_begin() || self.is_end() {
599 hardbreak(self.writer())?;
601 hardbreak(self.writer())
606 fn next_comment(&mut self) -> Option<comments::Comment> {
607 let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
608 match *self.comments() {
610 if cur_cmnt < cmnts.len() {
611 Some(cmnts[cur_cmnt].clone())
620 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
621 self.maybe_print_comment(lit.span.lo)?;
622 match self.next_lit(lit.span.lo) {
624 return word(self.writer(), &(*ltrl).lit);
629 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
630 ast::LitKind::Byte(byte) => {
631 let mut res = String::from("b'");
632 res.extend(ascii::escape_default(byte).map(|c| c as char));
634 word(self.writer(), &res[..])
636 ast::LitKind::Char(ch) => {
637 let mut res = String::from("'");
638 res.extend(ch.escape_default());
640 word(self.writer(), &res[..])
642 ast::LitKind::Int(i, t) => {
644 ast::LitIntType::Signed(st) => {
645 word(self.writer(), &st.val_to_string(i as i128))
647 ast::LitIntType::Unsigned(ut) => {
648 word(self.writer(), &ut.val_to_string(i))
650 ast::LitIntType::Unsuffixed => {
651 word(self.writer(), &format!("{}", i))
655 ast::LitKind::Float(ref f, t) => {
662 ast::LitKind::FloatUnsuffixed(ref f) => word(self.writer(), &f.as_str()),
663 ast::LitKind::Bool(val) => {
664 if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
666 ast::LitKind::ByteStr(ref v) => {
667 let mut escaped: String = String::new();
668 for &ch in v.iter() {
669 escaped.extend(ascii::escape_default(ch)
670 .map(|c| c as char));
672 word(self.writer(), &format!("b\"{}\"", escaped))
677 fn print_string(&mut self, st: &str,
678 style: ast::StrStyle) -> io::Result<()> {
679 let st = match style {
680 ast::StrStyle::Cooked => {
681 (format!("\"{}\"", st.escape_default()))
683 ast::StrStyle::Raw(n) => {
684 (format!("r{delim}\"{string}\"{delim}",
685 delim=repeat("#", n),
689 word(self.writer(), &st[..])
692 fn print_inner_attributes(&mut self,
693 attrs: &[ast::Attribute]) -> io::Result<()> {
694 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
697 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
698 attrs: &[ast::Attribute])
700 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
703 fn print_outer_attributes(&mut self,
704 attrs: &[ast::Attribute]) -> io::Result<()> {
705 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
708 fn print_inner_attributes_inline(&mut self,
709 attrs: &[ast::Attribute]) -> io::Result<()> {
710 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
713 fn print_outer_attributes_inline(&mut self,
714 attrs: &[ast::Attribute]) -> io::Result<()> {
715 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
718 fn print_either_attributes(&mut self,
719 attrs: &[ast::Attribute],
720 kind: ast::AttrStyle,
722 trailing_hardbreak: bool) -> io::Result<()> {
725 if attr.style == kind {
726 self.print_attribute_inline(attr, is_inline)?;
733 if count > 0 && trailing_hardbreak && !is_inline {
734 self.hardbreak_if_not_bol()?;
739 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
740 self.print_attribute_inline(attr, false)
743 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
744 is_inline: bool) -> io::Result<()> {
746 self.hardbreak_if_not_bol()?;
748 self.maybe_print_comment(attr.span.lo)?;
749 if attr.is_sugared_doc {
750 word(self.writer(), &attr.value_str().unwrap().as_str())?;
751 hardbreak(self.writer())
754 ast::AttrStyle::Inner => word(self.writer(), "#![")?,
755 ast::AttrStyle::Outer => word(self.writer(), "#[")?,
757 if let Some(mi) = attr.meta() {
758 self.print_meta_item(&mi)?
760 for (i, segment) in attr.path.segments.iter().enumerate() {
762 word(self.writer(), "::")?
764 if segment.identifier.name != keywords::CrateRoot.name() &&
765 segment.identifier.name != "$crate" {
766 word(self.writer(), &segment.identifier.name.as_str())?;
769 space(self.writer())?;
770 self.print_tts(attr.tokens.clone())?;
772 word(self.writer(), "]")
776 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
778 ast::NestedMetaItemKind::MetaItem(ref mi) => {
779 self.print_meta_item(mi)
781 ast::NestedMetaItemKind::Literal(ref lit) => {
782 self.print_literal(lit)
787 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
788 self.ibox(INDENT_UNIT)?;
790 ast::MetaItemKind::Word => {
791 word(self.writer(), &item.name.as_str())?;
793 ast::MetaItemKind::NameValue(ref value) => {
794 self.word_space(&item.name.as_str())?;
795 self.word_space("=")?;
796 self.print_literal(value)?;
798 ast::MetaItemKind::List(ref items) => {
799 word(self.writer(), &item.name.as_str())?;
801 self.commasep(Consistent,
803 |s, i| s.print_meta_list_item(&i))?;
810 /// This doesn't deserve to be called "pretty" printing, but it should be
811 /// meaning-preserving. A quick hack that might help would be to look at the
812 /// spans embedded in the TTs to decide where to put spaces and newlines.
813 /// But it'd be better to parse these according to the grammar of the
814 /// appropriate macro, transcribe back into the grammar we just parsed from,
815 /// and then pretty-print the resulting AST nodes (so, e.g., we print
816 /// expression arguments as expressions). It can be done! I think.
817 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
819 TokenTree::Token(_, ref tk) => {
820 word(self.writer(), &token_to_string(tk))?;
822 parse::token::DocComment(..) => {
823 hardbreak(self.writer())
828 TokenTree::Delimited(_, ref delimed) => {
829 word(self.writer(), &token_to_string(&delimed.open_token()))?;
830 space(self.writer())?;
831 self.print_tts(delimed.stream())?;
832 space(self.writer())?;
833 word(self.writer(), &token_to_string(&delimed.close_token()))
838 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
840 for (i, tt) in tts.into_trees().enumerate() {
842 space(self.writer())?;
849 fn space_if_not_bol(&mut self) -> io::Result<()> {
850 if !self.is_bol() { space(self.writer())?; }
854 fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
857 impl<'a> PrintState<'a> for State<'a> {
858 fn writer(&mut self) -> &mut pp::Printer<'a> {
862 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
866 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
870 fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
871 &mut self.cur_cmnt_and_lit
874 fn literals(&self) -> &Option<Vec<comments::Literal>> {
880 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
881 self.boxes.push(pp::Breaks::Consistent);
882 pp::cbox(&mut self.s, u)
885 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
886 word(&mut self.s, w)?;
890 pub fn head(&mut self, w: &str) -> io::Result<()> {
891 // outer-box is consistent
892 self.cbox(INDENT_UNIT)?;
893 // head-box is inconsistent
894 self.ibox(w.len() + 1)?;
895 // keyword that starts the head
902 pub fn bopen(&mut self) -> io::Result<()> {
903 word(&mut self.s, "{")?;
904 self.end() // close the head-box
907 pub fn bclose_(&mut self, span: syntax_pos::Span,
908 indented: usize) -> io::Result<()> {
909 self.bclose_maybe_open(span, indented, true)
911 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
912 indented: usize, close_box: bool) -> io::Result<()> {
913 self.maybe_print_comment(span.hi)?;
914 self.break_offset_if_not_bol(1, -(indented as isize))?;
915 word(&mut self.s, "}")?;
917 self.end()?; // close the outer-box
921 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
922 self.bclose_(span, INDENT_UNIT)
925 pub fn in_cbox(&self) -> bool {
926 match self.boxes.last() {
927 Some(&last_box) => last_box == pp::Breaks::Consistent,
932 pub fn break_offset_if_not_bol(&mut self, n: usize,
933 off: isize) -> io::Result<()> {
935 break_offset(&mut self.s, n, off)
937 if off != 0 && self.s.last_token().is_hardbreak_tok() {
938 // We do something pretty sketchy here: tuck the nonzero
939 // offset-adjustment we were going to deposit along with the
940 // break into the previous hardbreak.
941 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
947 // Synthesizes a comment that was not textually present in the original source
949 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
950 word(&mut self.s, "/*")?;
952 word(&mut self.s, &text[..])?;
954 word(&mut self.s, "*/")
959 pub fn commasep_cmnt<T, F, G>(&mut self,
963 mut get_span: G) -> io::Result<()> where
964 F: FnMut(&mut State, &T) -> io::Result<()>,
965 G: FnMut(&T) -> syntax_pos::Span,
968 let len = elts.len();
971 self.maybe_print_comment(get_span(elt).hi)?;
975 word(&mut self.s, ",")?;
976 self.maybe_print_trailing_comment(get_span(elt),
977 Some(get_span(&elts[i]).hi))?;
978 self.space_if_not_bol()?;
984 pub fn commasep_exprs(&mut self, b: Breaks,
985 exprs: &[P<ast::Expr>]) -> io::Result<()> {
986 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
989 pub fn print_mod(&mut self, _mod: &ast::Mod,
990 attrs: &[ast::Attribute]) -> io::Result<()> {
991 self.print_inner_attributes(attrs)?;
992 for item in &_mod.items {
993 self.print_item(&item)?;
998 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
999 attrs: &[ast::Attribute]) -> io::Result<()> {
1000 self.print_inner_attributes(attrs)?;
1001 for item in &nmod.items {
1002 self.print_foreign_item(item)?;
1007 pub fn print_opt_lifetime(&mut self,
1008 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1009 if let Some(l) = *lifetime {
1010 self.print_lifetime(&l)?;
1016 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1017 self.maybe_print_comment(ty.span.lo)?;
1020 ast::TyKind::Slice(ref ty) => {
1021 word(&mut self.s, "[")?;
1022 self.print_type(&ty)?;
1023 word(&mut self.s, "]")?;
1025 ast::TyKind::Ptr(ref mt) => {
1026 word(&mut self.s, "*")?;
1028 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1029 ast::Mutability::Immutable => self.word_nbsp("const")?,
1031 self.print_type(&mt.ty)?;
1033 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1034 word(&mut self.s, "&")?;
1035 self.print_opt_lifetime(lifetime)?;
1038 ast::TyKind::Never => {
1039 word(&mut self.s, "!")?;
1041 ast::TyKind::Tup(ref elts) => {
1043 self.commasep(Inconsistent, &elts[..],
1044 |s, ty| s.print_type(&ty))?;
1045 if elts.len() == 1 {
1046 word(&mut self.s, ",")?;
1050 ast::TyKind::Paren(ref typ) => {
1052 self.print_type(&typ)?;
1055 ast::TyKind::BareFn(ref f) => {
1056 let generics = ast::Generics {
1057 lifetimes: f.lifetimes.clone(),
1058 ty_params: Vec::new(),
1059 where_clause: ast::WhereClause {
1060 id: ast::DUMMY_NODE_ID,
1061 predicates: Vec::new(),
1063 span: syntax_pos::DUMMY_SP,
1065 self.print_ty_fn(f.abi,
1071 ast::TyKind::Path(None, ref path) => {
1072 self.print_path(path, false, 0, false)?;
1074 ast::TyKind::Path(Some(ref qself), ref path) => {
1075 self.print_qpath(path, qself, false)?
1077 ast::TyKind::TraitObject(ref bounds) => {
1078 self.print_bounds("", &bounds[..])?;
1080 ast::TyKind::ImplTrait(ref bounds) => {
1081 self.print_bounds("impl ", &bounds[..])?;
1083 ast::TyKind::Array(ref ty, ref v) => {
1084 word(&mut self.s, "[")?;
1085 self.print_type(&ty)?;
1086 word(&mut self.s, "; ")?;
1087 self.print_expr(&v)?;
1088 word(&mut self.s, "]")?;
1090 ast::TyKind::Typeof(ref e) => {
1091 word(&mut self.s, "typeof(")?;
1092 self.print_expr(&e)?;
1093 word(&mut self.s, ")")?;
1095 ast::TyKind::Infer => {
1096 word(&mut self.s, "_")?;
1098 ast::TyKind::Err => {
1099 word(&mut self.s, "?")?;
1101 ast::TyKind::ImplicitSelf => {
1102 word(&mut self.s, "Self")?;
1104 ast::TyKind::Mac(ref m) => {
1105 self.print_mac(m, token::Paren)?;
1111 pub fn print_foreign_item(&mut self,
1112 item: &ast::ForeignItem) -> io::Result<()> {
1113 self.hardbreak_if_not_bol()?;
1114 self.maybe_print_comment(item.span.lo)?;
1115 self.print_outer_attributes(&item.attrs)?;
1117 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1119 self.print_fn(decl, ast::Unsafety::Normal,
1120 ast::Constness::NotConst,
1121 Abi::Rust, Some(item.ident),
1122 generics, &item.vis)?;
1123 self.end()?; // end head-ibox
1124 word(&mut self.s, ";")?;
1125 self.end() // end the outer fn box
1127 ast::ForeignItemKind::Static(ref t, m) => {
1128 self.head(&visibility_qualified(&item.vis, "static"))?;
1130 self.word_space("mut")?;
1132 self.print_ident(item.ident)?;
1133 self.word_space(":")?;
1134 self.print_type(&t)?;
1135 word(&mut self.s, ";")?;
1136 self.end()?; // end the head-ibox
1137 self.end() // end the outer cbox
1142 fn print_associated_const(&mut self,
1145 default: Option<&ast::Expr>,
1146 vis: &ast::Visibility)
1149 word(&mut self.s, &visibility_qualified(vis, ""))?;
1150 self.word_space("const")?;
1151 self.print_ident(ident)?;
1152 self.word_space(":")?;
1153 self.print_type(ty)?;
1154 if let Some(expr) = default {
1155 space(&mut self.s)?;
1156 self.word_space("=")?;
1157 self.print_expr(expr)?;
1159 word(&mut self.s, ";")
1162 fn print_associated_type(&mut self,
1164 bounds: Option<&ast::TyParamBounds>,
1165 ty: Option<&ast::Ty>)
1167 self.word_space("type")?;
1168 self.print_ident(ident)?;
1169 if let Some(bounds) = bounds {
1170 self.print_bounds(":", bounds)?;
1172 if let Some(ty) = ty {
1173 space(&mut self.s)?;
1174 self.word_space("=")?;
1175 self.print_type(ty)?;
1177 word(&mut self.s, ";")
1180 /// Pretty-print an item
1181 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1182 self.hardbreak_if_not_bol()?;
1183 self.maybe_print_comment(item.span.lo)?;
1184 self.print_outer_attributes(&item.attrs)?;
1185 self.ann.pre(self, NodeItem(item))?;
1187 ast::ItemKind::ExternCrate(ref optional_path) => {
1188 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1189 if let Some(p) = *optional_path {
1190 let val = p.as_str();
1191 if val.contains("-") {
1192 self.print_string(&val, ast::StrStyle::Cooked)?;
1194 self.print_name(p)?;
1196 space(&mut self.s)?;
1197 word(&mut self.s, "as")?;
1198 space(&mut self.s)?;
1200 self.print_ident(item.ident)?;
1201 word(&mut self.s, ";")?;
1202 self.end()?; // end inner head-block
1203 self.end()?; // end outer head-block
1205 ast::ItemKind::Use(ref vp) => {
1206 self.head(&visibility_qualified(&item.vis, "use"))?;
1207 self.print_view_path(&vp)?;
1208 word(&mut self.s, ";")?;
1209 self.end()?; // end inner head-block
1210 self.end()?; // end outer head-block
1212 ast::ItemKind::Static(ref ty, m, ref expr) => {
1213 self.head(&visibility_qualified(&item.vis, "static"))?;
1214 if m == ast::Mutability::Mutable {
1215 self.word_space("mut")?;
1217 self.print_ident(item.ident)?;
1218 self.word_space(":")?;
1219 self.print_type(&ty)?;
1220 space(&mut self.s)?;
1221 self.end()?; // end the head-ibox
1223 self.word_space("=")?;
1224 self.print_expr(&expr)?;
1225 word(&mut self.s, ";")?;
1226 self.end()?; // end the outer cbox
1228 ast::ItemKind::Const(ref ty, ref expr) => {
1229 self.head(&visibility_qualified(&item.vis, "const"))?;
1230 self.print_ident(item.ident)?;
1231 self.word_space(":")?;
1232 self.print_type(&ty)?;
1233 space(&mut self.s)?;
1234 self.end()?; // end the head-ibox
1236 self.word_space("=")?;
1237 self.print_expr(&expr)?;
1238 word(&mut self.s, ";")?;
1239 self.end()?; // end the outer cbox
1241 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1252 word(&mut self.s, " ")?;
1253 self.print_block_with_attrs(&body, &item.attrs)?;
1255 ast::ItemKind::Mod(ref _mod) => {
1256 self.head(&visibility_qualified(&item.vis, "mod"))?;
1257 self.print_ident(item.ident)?;
1260 self.print_mod(_mod, &item.attrs)?;
1261 self.bclose(item.span)?;
1263 ast::ItemKind::ForeignMod(ref nmod) => {
1264 self.head("extern")?;
1265 self.word_nbsp(&nmod.abi.to_string())?;
1267 self.print_foreign_mod(nmod, &item.attrs)?;
1268 self.bclose(item.span)?;
1270 ast::ItemKind::Ty(ref ty, ref params) => {
1271 self.ibox(INDENT_UNIT)?;
1273 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1274 self.print_ident(item.ident)?;
1275 self.print_generics(params)?;
1276 self.end()?; // end the inner ibox
1278 self.print_where_clause(¶ms.where_clause)?;
1279 space(&mut self.s)?;
1280 self.word_space("=")?;
1281 self.print_type(&ty)?;
1282 word(&mut self.s, ";")?;
1283 self.end()?; // end the outer ibox
1285 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1286 self.print_enum_def(
1294 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1295 self.head(&visibility_qualified(&item.vis, "struct"))?;
1296 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1298 ast::ItemKind::Union(ref struct_def, ref generics) => {
1299 self.head(&visibility_qualified(&item.vis, "union"))?;
1300 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1302 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1304 self.print_visibility(&item.vis)?;
1305 self.print_unsafety(unsafety)?;
1306 self.word_nbsp("impl")?;
1307 self.print_trait_ref(trait_ref)?;
1308 space(&mut self.s)?;
1309 self.word_space("for")?;
1310 self.word_space("..")?;
1312 self.bclose(item.span)?;
1314 ast::ItemKind::Impl(unsafety,
1319 ref impl_items) => {
1321 self.print_visibility(&item.vis)?;
1322 self.print_unsafety(unsafety)?;
1323 self.word_nbsp("impl")?;
1325 if generics.is_parameterized() {
1326 self.print_generics(generics)?;
1327 space(&mut self.s)?;
1331 ast::ImplPolarity::Negative => {
1332 word(&mut self.s, "!")?;
1337 if let Some(ref t) = *opt_trait {
1338 self.print_trait_ref(t)?;
1339 space(&mut self.s)?;
1340 self.word_space("for")?;
1343 self.print_type(&ty)?;
1344 self.print_where_clause(&generics.where_clause)?;
1346 space(&mut self.s)?;
1348 self.print_inner_attributes(&item.attrs)?;
1349 for impl_item in impl_items {
1350 self.print_impl_item(impl_item)?;
1352 self.bclose(item.span)?;
1354 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1356 self.print_visibility(&item.vis)?;
1357 self.print_unsafety(unsafety)?;
1358 self.word_nbsp("trait")?;
1359 self.print_ident(item.ident)?;
1360 self.print_generics(generics)?;
1361 let mut real_bounds = Vec::with_capacity(bounds.len());
1362 for b in bounds.iter() {
1363 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1364 space(&mut self.s)?;
1365 self.word_space("for ?")?;
1366 self.print_trait_ref(&ptr.trait_ref)?;
1368 real_bounds.push(b.clone());
1371 self.print_bounds(":", &real_bounds[..])?;
1372 self.print_where_clause(&generics.where_clause)?;
1373 word(&mut self.s, " ")?;
1375 for trait_item in trait_items {
1376 self.print_trait_item(trait_item)?;
1378 self.bclose(item.span)?;
1380 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1381 self.print_path(&node.path, false, 0, false)?;
1382 word(&mut self.s, "! ")?;
1383 self.print_ident(item.ident)?;
1384 self.cbox(INDENT_UNIT)?;
1386 self.print_tts(node.stream())?;
1388 word(&mut self.s, ";")?;
1391 ast::ItemKind::MacroDef(ref tts) => {
1392 word(&mut self.s, "macro_rules! ")?;
1393 self.print_ident(item.ident)?;
1394 self.cbox(INDENT_UNIT)?;
1396 self.print_tts(tts.clone().into())?;
1398 word(&mut self.s, ";")?;
1402 self.ann.post(self, NodeItem(item))
1405 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1406 self.print_path(&t.path, false, 0, false)
1409 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1410 if !lifetimes.is_empty() {
1411 word(&mut self.s, "for<")?;
1412 let mut comma = false;
1413 for lifetime_def in lifetimes {
1415 self.word_space(",")?
1417 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1418 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1421 word(&mut self.s, ">")?;
1426 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1427 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1428 self.print_trait_ref(&t.trait_ref)
1431 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1432 generics: &ast::Generics, ident: ast::Ident,
1433 span: syntax_pos::Span,
1434 visibility: &ast::Visibility) -> io::Result<()> {
1435 self.head(&visibility_qualified(visibility, "enum"))?;
1436 self.print_ident(ident)?;
1437 self.print_generics(generics)?;
1438 self.print_where_clause(&generics.where_clause)?;
1439 space(&mut self.s)?;
1440 self.print_variants(&enum_definition.variants, span)
1443 pub fn print_variants(&mut self,
1444 variants: &[ast::Variant],
1445 span: syntax_pos::Span) -> io::Result<()> {
1448 self.space_if_not_bol()?;
1449 self.maybe_print_comment(v.span.lo)?;
1450 self.print_outer_attributes(&v.node.attrs)?;
1451 self.ibox(INDENT_UNIT)?;
1452 self.print_variant(v)?;
1453 word(&mut self.s, ",")?;
1455 self.maybe_print_trailing_comment(v.span, None)?;
1460 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1462 ast::Visibility::Public => self.word_nbsp("pub"),
1463 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1464 ast::Visibility::Restricted { ref path, .. } => {
1465 let path = to_string(|s| s.print_path(path, false, 0, true));
1466 self.word_nbsp(&format!("pub({})", path))
1468 ast::Visibility::Inherited => Ok(())
1472 pub fn print_struct(&mut self,
1473 struct_def: &ast::VariantData,
1474 generics: &ast::Generics,
1476 span: syntax_pos::Span,
1477 print_finalizer: bool) -> io::Result<()> {
1478 self.print_ident(ident)?;
1479 self.print_generics(generics)?;
1480 if !struct_def.is_struct() {
1481 if struct_def.is_tuple() {
1484 Inconsistent, struct_def.fields(),
1486 s.maybe_print_comment(field.span.lo)?;
1487 s.print_outer_attributes(&field.attrs)?;
1488 s.print_visibility(&field.vis)?;
1489 s.print_type(&field.ty)
1494 self.print_where_clause(&generics.where_clause)?;
1495 if print_finalizer {
1496 word(&mut self.s, ";")?;
1499 self.end() // close the outer-box
1501 self.print_where_clause(&generics.where_clause)?;
1504 self.hardbreak_if_not_bol()?;
1506 for field in struct_def.fields() {
1507 self.hardbreak_if_not_bol()?;
1508 self.maybe_print_comment(field.span.lo)?;
1509 self.print_outer_attributes(&field.attrs)?;
1510 self.print_visibility(&field.vis)?;
1511 self.print_ident(field.ident.unwrap())?;
1512 self.word_nbsp(":")?;
1513 self.print_type(&field.ty)?;
1514 word(&mut self.s, ",")?;
1521 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1523 let generics = ast::Generics::default();
1524 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1525 match v.node.disr_expr {
1527 space(&mut self.s)?;
1528 self.word_space("=")?;
1535 pub fn print_method_sig(&mut self,
1538 vis: &ast::Visibility)
1540 self.print_fn(&m.decl,
1549 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1551 self.ann.pre(self, NodeSubItem(ti.id))?;
1552 self.hardbreak_if_not_bol()?;
1553 self.maybe_print_comment(ti.span.lo)?;
1554 self.print_outer_attributes(&ti.attrs)?;
1556 ast::TraitItemKind::Const(ref ty, ref default) => {
1557 self.print_associated_const(ti.ident, &ty,
1558 default.as_ref().map(|expr| &**expr),
1559 &ast::Visibility::Inherited)?;
1561 ast::TraitItemKind::Method(ref sig, ref body) => {
1565 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1566 if let Some(ref body) = *body {
1568 self.print_block_with_attrs(body, &ti.attrs)?;
1570 word(&mut self.s, ";")?;
1573 ast::TraitItemKind::Type(ref bounds, ref default) => {
1574 self.print_associated_type(ti.ident, Some(bounds),
1575 default.as_ref().map(|ty| &**ty))?;
1577 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1578 // code copied from ItemKind::Mac:
1579 self.print_path(&node.path, false, 0, false)?;
1580 word(&mut self.s, "! ")?;
1581 self.cbox(INDENT_UNIT)?;
1583 self.print_tts(node.stream())?;
1585 word(&mut self.s, ";")?;
1589 self.ann.post(self, NodeSubItem(ti.id))
1592 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1593 self.ann.pre(self, NodeSubItem(ii.id))?;
1594 self.hardbreak_if_not_bol()?;
1595 self.maybe_print_comment(ii.span.lo)?;
1596 self.print_outer_attributes(&ii.attrs)?;
1597 if let ast::Defaultness::Default = ii.defaultness {
1598 self.word_nbsp("default")?;
1601 ast::ImplItemKind::Const(ref ty, ref expr) => {
1602 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1604 ast::ImplItemKind::Method(ref sig, ref body) => {
1606 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1608 self.print_block_with_attrs(body, &ii.attrs)?;
1610 ast::ImplItemKind::Type(ref ty) => {
1611 self.print_associated_type(ii.ident, None, Some(ty))?;
1613 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1614 // code copied from ItemKind::Mac:
1615 self.print_path(&node.path, false, 0, false)?;
1616 word(&mut self.s, "! ")?;
1617 self.cbox(INDENT_UNIT)?;
1619 self.print_tts(node.stream())?;
1621 word(&mut self.s, ";")?;
1625 self.ann.post(self, NodeSubItem(ii.id))
1628 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1629 self.maybe_print_comment(st.span.lo)?;
1631 ast::StmtKind::Local(ref loc) => {
1632 self.print_outer_attributes(&loc.attrs)?;
1633 self.space_if_not_bol()?;
1634 self.ibox(INDENT_UNIT)?;
1635 self.word_nbsp("let")?;
1637 self.ibox(INDENT_UNIT)?;
1638 self.print_local_decl(&loc)?;
1640 if let Some(ref init) = loc.init {
1642 self.word_space("=")?;
1643 self.print_expr(&init)?;
1645 word(&mut self.s, ";")?;
1648 ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1649 ast::StmtKind::Expr(ref expr) => {
1650 self.space_if_not_bol()?;
1651 self.print_expr_outer_attr_style(&expr, false)?;
1652 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1653 word(&mut self.s, ";")?;
1656 ast::StmtKind::Semi(ref expr) => {
1657 self.space_if_not_bol()?;
1658 self.print_expr_outer_attr_style(&expr, false)?;
1659 word(&mut self.s, ";")?;
1661 ast::StmtKind::Mac(ref mac) => {
1662 let (ref mac, style, ref attrs) = **mac;
1663 self.space_if_not_bol()?;
1664 self.print_outer_attributes(&attrs)?;
1665 let delim = match style {
1666 ast::MacStmtStyle::Braces => token::Brace,
1669 self.print_mac(&mac, delim)?;
1670 if style == ast::MacStmtStyle::Semicolon {
1671 word(&mut self.s, ";")?;
1675 self.maybe_print_trailing_comment(st.span, None)
1678 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1679 self.print_block_with_attrs(blk, &[])
1682 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1683 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1686 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1687 attrs: &[ast::Attribute])
1689 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1692 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1693 indented: usize) -> io::Result<()> {
1694 self.print_block_maybe_unclosed(blk, indented, &[], false)
1697 pub fn print_block_with_attrs(&mut self,
1699 attrs: &[ast::Attribute]) -> io::Result<()> {
1700 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1703 pub fn print_block_maybe_unclosed(&mut self,
1706 attrs: &[ast::Attribute],
1707 close_box: bool) -> io::Result<()> {
1709 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1710 BlockCheckMode::Default => ()
1712 self.maybe_print_comment(blk.span.lo)?;
1713 self.ann.pre(self, NodeBlock(blk))?;
1716 self.print_inner_attributes(attrs)?;
1718 for (i, st) in blk.stmts.iter().enumerate() {
1720 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1721 self.maybe_print_comment(st.span.lo)?;
1722 self.space_if_not_bol()?;
1723 self.print_expr_outer_attr_style(&expr, false)?;
1724 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1726 _ => self.print_stmt(st)?,
1730 self.bclose_maybe_open(blk.span, indented, close_box)?;
1731 self.ann.post(self, NodeBlock(blk))
1734 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1738 // "another else-if"
1739 ast::ExprKind::If(ref i, ref then, ref e) => {
1740 self.cbox(INDENT_UNIT - 1)?;
1742 word(&mut self.s, " else if ")?;
1743 self.print_expr(&i)?;
1744 space(&mut self.s)?;
1745 self.print_block(&then)?;
1746 self.print_else(e.as_ref().map(|e| &**e))
1748 // "another else-if-let"
1749 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1750 self.cbox(INDENT_UNIT - 1)?;
1752 word(&mut self.s, " else if let ")?;
1753 self.print_pat(&pat)?;
1754 space(&mut self.s)?;
1755 self.word_space("=")?;
1756 self.print_expr(&expr)?;
1757 space(&mut self.s)?;
1758 self.print_block(&then)?;
1759 self.print_else(e.as_ref().map(|e| &**e))
1762 ast::ExprKind::Block(ref b) => {
1763 self.cbox(INDENT_UNIT - 1)?;
1765 word(&mut self.s, " else ")?;
1766 self.print_block(&b)
1768 // BLEAH, constraints would be great here
1770 panic!("print_if saw if with weird alternative");
1778 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1779 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1781 self.print_expr(test)?;
1782 space(&mut self.s)?;
1783 self.print_block(blk)?;
1784 self.print_else(elseopt)
1787 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1788 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1789 self.head("if let")?;
1790 self.print_pat(pat)?;
1791 space(&mut self.s)?;
1792 self.word_space("=")?;
1793 self.print_expr(expr)?;
1794 space(&mut self.s)?;
1795 self.print_block(blk)?;
1796 self.print_else(elseopt)
1799 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1801 self.print_path(&m.node.path, false, 0, false)?;
1802 word(&mut self.s, "!")?;
1804 token::Paren => self.popen()?,
1805 token::Bracket => word(&mut self.s, "[")?,
1810 token::NoDelim => {}
1812 self.print_tts(m.node.stream())?;
1814 token::Paren => self.pclose(),
1815 token::Bracket => word(&mut self.s, "]"),
1816 token::Brace => self.bclose(m.span),
1817 token::NoDelim => Ok(()),
1822 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1824 self.commasep_exprs(Inconsistent, args)?;
1828 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1829 binop: ast::BinOp) -> bool {
1830 match sub_expr.node {
1831 ast::ExprKind::Binary(ref sub_op, _, _) => {
1832 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1833 AssocOp::from_ast_binop(binop.node).precedence() {
1843 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1844 let needs_par = needs_parentheses(expr);
1848 self.print_expr(expr)?;
1855 fn print_expr_in_place(&mut self,
1857 expr: &ast::Expr) -> io::Result<()> {
1858 self.print_expr_maybe_paren(place)?;
1859 space(&mut self.s)?;
1860 self.word_space("<-")?;
1861 self.print_expr_maybe_paren(expr)
1864 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1865 attrs: &[Attribute]) -> io::Result<()> {
1866 self.ibox(INDENT_UNIT)?;
1867 word(&mut self.s, "[")?;
1868 self.print_inner_attributes_inline(attrs)?;
1869 self.commasep_exprs(Inconsistent, &exprs[..])?;
1870 word(&mut self.s, "]")?;
1874 fn print_expr_repeat(&mut self,
1875 element: &ast::Expr,
1877 attrs: &[Attribute]) -> io::Result<()> {
1878 self.ibox(INDENT_UNIT)?;
1879 word(&mut self.s, "[")?;
1880 self.print_inner_attributes_inline(attrs)?;
1881 self.print_expr(element)?;
1882 self.word_space(";")?;
1883 self.print_expr(count)?;
1884 word(&mut self.s, "]")?;
1888 fn print_expr_struct(&mut self,
1890 fields: &[ast::Field],
1891 wth: &Option<P<ast::Expr>>,
1892 attrs: &[Attribute]) -> io::Result<()> {
1893 self.print_path(path, true, 0, false)?;
1894 word(&mut self.s, "{")?;
1895 self.print_inner_attributes_inline(attrs)?;
1900 s.ibox(INDENT_UNIT)?;
1901 if !field.is_shorthand {
1902 s.print_ident(field.ident.node)?;
1905 s.print_expr(&field.expr)?;
1911 self.ibox(INDENT_UNIT)?;
1912 if !fields.is_empty() {
1913 word(&mut self.s, ",")?;
1914 space(&mut self.s)?;
1916 word(&mut self.s, "..")?;
1917 self.print_expr(&expr)?;
1920 _ => if !fields.is_empty() {
1921 word(&mut self.s, ",")?
1924 word(&mut self.s, "}")?;
1928 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1929 attrs: &[Attribute]) -> io::Result<()> {
1931 self.print_inner_attributes_inline(attrs)?;
1932 self.commasep_exprs(Inconsistent, &exprs[..])?;
1933 if exprs.len() == 1 {
1934 word(&mut self.s, ",")?;
1939 fn print_expr_call(&mut self,
1941 args: &[P<ast::Expr>]) -> io::Result<()> {
1942 self.print_expr_maybe_paren(func)?;
1943 self.print_call_post(args)
1946 fn print_expr_method_call(&mut self,
1947 ident: ast::SpannedIdent,
1949 args: &[P<ast::Expr>]) -> io::Result<()> {
1950 let base_args = &args[1..];
1951 self.print_expr(&args[0])?;
1952 word(&mut self.s, ".")?;
1953 self.print_ident(ident.node)?;
1954 if !tys.is_empty() {
1955 word(&mut self.s, "::<")?;
1956 self.commasep(Inconsistent, tys,
1957 |s, ty| s.print_type(&ty))?;
1958 word(&mut self.s, ">")?;
1960 self.print_call_post(base_args)
1963 fn print_expr_binary(&mut self,
1966 rhs: &ast::Expr) -> io::Result<()> {
1967 if self.check_expr_bin_needs_paren(lhs, op) {
1968 self.print_expr_maybe_paren(lhs)?;
1970 self.print_expr(lhs)?;
1972 space(&mut self.s)?;
1973 self.word_space(op.node.to_string())?;
1974 if self.check_expr_bin_needs_paren(rhs, op) {
1975 self.print_expr_maybe_paren(rhs)
1977 self.print_expr(rhs)
1981 fn print_expr_unary(&mut self,
1983 expr: &ast::Expr) -> io::Result<()> {
1984 word(&mut self.s, ast::UnOp::to_string(op))?;
1985 self.print_expr_maybe_paren(expr)
1988 fn print_expr_addr_of(&mut self,
1989 mutability: ast::Mutability,
1990 expr: &ast::Expr) -> io::Result<()> {
1991 word(&mut self.s, "&")?;
1992 self.print_mutability(mutability)?;
1993 self.print_expr_maybe_paren(expr)
1996 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1997 self.print_expr_outer_attr_style(expr, true)
2000 fn print_expr_outer_attr_style(&mut self,
2002 is_inline: bool) -> io::Result<()> {
2003 self.maybe_print_comment(expr.span.lo)?;
2005 let attrs = &expr.attrs;
2007 self.print_outer_attributes_inline(attrs)?;
2009 self.print_outer_attributes(attrs)?;
2012 self.ibox(INDENT_UNIT)?;
2013 self.ann.pre(self, NodeExpr(expr))?;
2015 ast::ExprKind::Box(ref expr) => {
2016 self.word_space("box")?;
2017 self.print_expr(expr)?;
2019 ast::ExprKind::InPlace(ref place, ref expr) => {
2020 self.print_expr_in_place(place, expr)?;
2022 ast::ExprKind::Array(ref exprs) => {
2023 self.print_expr_vec(&exprs[..], attrs)?;
2025 ast::ExprKind::Repeat(ref element, ref count) => {
2026 self.print_expr_repeat(&element, &count, attrs)?;
2028 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2029 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2031 ast::ExprKind::Tup(ref exprs) => {
2032 self.print_expr_tup(&exprs[..], attrs)?;
2034 ast::ExprKind::Call(ref func, ref args) => {
2035 self.print_expr_call(&func, &args[..])?;
2037 ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2038 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2040 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2041 self.print_expr_binary(op, &lhs, &rhs)?;
2043 ast::ExprKind::Unary(op, ref expr) => {
2044 self.print_expr_unary(op, &expr)?;
2046 ast::ExprKind::AddrOf(m, ref expr) => {
2047 self.print_expr_addr_of(m, &expr)?;
2049 ast::ExprKind::Lit(ref lit) => {
2050 self.print_literal(&lit)?;
2052 ast::ExprKind::Cast(ref expr, ref ty) => {
2053 if let ast::ExprKind::Cast(..) = expr.node {
2054 self.print_expr(&expr)?;
2056 self.print_expr_maybe_paren(&expr)?;
2058 space(&mut self.s)?;
2059 self.word_space("as")?;
2060 self.print_type(&ty)?;
2062 ast::ExprKind::Type(ref expr, ref ty) => {
2063 self.print_expr(&expr)?;
2064 self.word_space(":")?;
2065 self.print_type(&ty)?;
2067 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2068 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2070 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2071 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2073 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2074 if let Some(ident) = opt_ident {
2075 self.print_ident(ident.node)?;
2076 self.word_space(":")?;
2078 self.head("while")?;
2079 self.print_expr(&test)?;
2080 space(&mut self.s)?;
2081 self.print_block_with_attrs(&blk, attrs)?;
2083 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2084 if let Some(ident) = opt_ident {
2085 self.print_ident(ident.node)?;
2086 self.word_space(":")?;
2088 self.head("while let")?;
2089 self.print_pat(&pat)?;
2090 space(&mut self.s)?;
2091 self.word_space("=")?;
2092 self.print_expr(&expr)?;
2093 space(&mut self.s)?;
2094 self.print_block_with_attrs(&blk, attrs)?;
2096 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2097 if let Some(ident) = opt_ident {
2098 self.print_ident(ident.node)?;
2099 self.word_space(":")?;
2102 self.print_pat(&pat)?;
2103 space(&mut self.s)?;
2104 self.word_space("in")?;
2105 self.print_expr(&iter)?;
2106 space(&mut self.s)?;
2107 self.print_block_with_attrs(&blk, attrs)?;
2109 ast::ExprKind::Loop(ref blk, opt_ident) => {
2110 if let Some(ident) = opt_ident {
2111 self.print_ident(ident.node)?;
2112 self.word_space(":")?;
2115 space(&mut self.s)?;
2116 self.print_block_with_attrs(&blk, attrs)?;
2118 ast::ExprKind::Match(ref expr, ref arms) => {
2119 self.cbox(INDENT_UNIT)?;
2121 self.word_nbsp("match")?;
2122 self.print_expr(&expr)?;
2123 space(&mut self.s)?;
2125 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2127 self.print_arm(arm)?;
2129 self.bclose_(expr.span, INDENT_UNIT)?;
2131 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2132 self.print_capture_clause(capture_clause)?;
2134 self.print_fn_block_args(&decl)?;
2135 space(&mut self.s)?;
2136 self.print_expr(body)?;
2137 self.end()?; // need to close a box
2139 // a box will be closed by print_expr, but we didn't want an overall
2140 // wrapper so we closed the corresponding opening. so create an
2141 // empty box to satisfy the close.
2144 ast::ExprKind::Block(ref blk) => {
2145 // containing cbox, will be closed by print-block at }
2146 self.cbox(INDENT_UNIT)?;
2147 // head-box, will be closed by print-block after {
2149 self.print_block_with_attrs(&blk, attrs)?;
2151 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2152 self.print_expr(&lhs)?;
2153 space(&mut self.s)?;
2154 self.word_space("=")?;
2155 self.print_expr(&rhs)?;
2157 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2158 self.print_expr(&lhs)?;
2159 space(&mut self.s)?;
2160 word(&mut self.s, op.node.to_string())?;
2161 self.word_space("=")?;
2162 self.print_expr(&rhs)?;
2164 ast::ExprKind::Field(ref expr, id) => {
2165 self.print_expr(&expr)?;
2166 word(&mut self.s, ".")?;
2167 self.print_ident(id.node)?;
2169 ast::ExprKind::TupField(ref expr, id) => {
2170 self.print_expr(&expr)?;
2171 word(&mut self.s, ".")?;
2172 self.print_usize(id.node)?;
2174 ast::ExprKind::Index(ref expr, ref index) => {
2175 self.print_expr(&expr)?;
2176 word(&mut self.s, "[")?;
2177 self.print_expr(&index)?;
2178 word(&mut self.s, "]")?;
2180 ast::ExprKind::Range(ref start, ref end, limits) => {
2181 if let &Some(ref e) = start {
2182 self.print_expr(&e)?;
2184 if limits == ast::RangeLimits::HalfOpen {
2185 word(&mut self.s, "..")?;
2187 word(&mut self.s, "...")?;
2189 if let &Some(ref e) = end {
2190 self.print_expr(&e)?;
2193 ast::ExprKind::Path(None, ref path) => {
2194 self.print_path(path, true, 0, false)?
2196 ast::ExprKind::Path(Some(ref qself), ref path) => {
2197 self.print_qpath(path, qself, true)?
2199 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2200 word(&mut self.s, "break")?;
2201 space(&mut self.s)?;
2202 if let Some(ident) = opt_ident {
2203 self.print_ident(ident.node)?;
2204 space(&mut self.s)?;
2206 if let Some(ref expr) = *opt_expr {
2207 self.print_expr(expr)?;
2208 space(&mut self.s)?;
2211 ast::ExprKind::Continue(opt_ident) => {
2212 word(&mut self.s, "continue")?;
2213 space(&mut self.s)?;
2214 if let Some(ident) = opt_ident {
2215 self.print_ident(ident.node)?;
2219 ast::ExprKind::Ret(ref result) => {
2220 word(&mut self.s, "return")?;
2223 word(&mut self.s, " ")?;
2224 self.print_expr(&expr)?;
2229 ast::ExprKind::InlineAsm(ref a) => {
2230 word(&mut self.s, "asm!")?;
2232 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2233 self.word_space(":")?;
2235 self.commasep(Inconsistent, &a.outputs, |s, out| {
2236 let constraint = out.constraint.as_str();
2237 let mut ch = constraint.chars();
2239 Some('=') if out.is_rw => {
2240 s.print_string(&format!("+{}", ch.as_str()),
2241 ast::StrStyle::Cooked)?
2243 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2246 s.print_expr(&out.expr)?;
2250 space(&mut self.s)?;
2251 self.word_space(":")?;
2253 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2254 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2260 space(&mut self.s)?;
2261 self.word_space(":")?;
2263 self.commasep(Inconsistent, &a.clobbers,
2265 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2269 let mut options = vec![];
2271 options.push("volatile");
2274 options.push("alignstack");
2276 if a.dialect == ast::AsmDialect::Intel {
2277 options.push("intel");
2280 if !options.is_empty() {
2281 space(&mut self.s)?;
2282 self.word_space(":")?;
2283 self.commasep(Inconsistent, &options,
2285 s.print_string(co, ast::StrStyle::Cooked)?;
2292 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2293 ast::ExprKind::Paren(ref e) => {
2295 self.print_inner_attributes_inline(attrs)?;
2296 self.print_expr(&e)?;
2299 ast::ExprKind::Try(ref e) => {
2300 self.print_expr(e)?;
2301 word(&mut self.s, "?")?
2303 ast::ExprKind::Catch(ref blk) => {
2304 self.head("do catch")?;
2305 space(&mut self.s)?;
2306 self.print_block_with_attrs(&blk, attrs)?
2309 self.ann.post(self, NodeExpr(expr))?;
2313 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2314 self.print_pat(&loc.pat)?;
2315 if let Some(ref ty) = loc.ty {
2316 self.word_space(":")?;
2317 self.print_type(&ty)?;
2322 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2323 word(&mut self.s, &ident.name.as_str())?;
2324 self.ann.post(self, NodeIdent(&ident))
2327 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2328 word(&mut self.s, &i.to_string())
2331 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2332 word(&mut self.s, &name.as_str())?;
2333 self.ann.post(self, NodeName(&name))
2336 pub fn print_for_decl(&mut self, loc: &ast::Local,
2337 coll: &ast::Expr) -> io::Result<()> {
2338 self.print_local_decl(loc)?;
2339 space(&mut self.s)?;
2340 self.word_space("in")?;
2341 self.print_expr(coll)
2344 fn print_path(&mut self,
2346 colons_before_params: bool,
2348 defaults_to_global: bool)
2351 self.maybe_print_comment(path.span.lo)?;
2353 let mut segments = path.segments[..path.segments.len()-depth].iter();
2354 if defaults_to_global && path.is_global() {
2357 for (i, segment) in segments.enumerate() {
2359 word(&mut self.s, "::")?
2361 if segment.identifier.name != keywords::CrateRoot.name() &&
2362 segment.identifier.name != "$crate" {
2363 self.print_ident(segment.identifier)?;
2364 if let Some(ref parameters) = segment.parameters {
2365 self.print_path_parameters(parameters, colons_before_params)?;
2373 fn print_qpath(&mut self,
2376 colons_before_params: bool)
2379 word(&mut self.s, "<")?;
2380 self.print_type(&qself.ty)?;
2381 if qself.position > 0 {
2382 space(&mut self.s)?;
2383 self.word_space("as")?;
2384 let depth = path.segments.len() - qself.position;
2385 self.print_path(&path, false, depth, false)?;
2387 word(&mut self.s, ">")?;
2388 word(&mut self.s, "::")?;
2389 let item_segment = path.segments.last().unwrap();
2390 self.print_ident(item_segment.identifier)?;
2391 match item_segment.parameters {
2392 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2397 fn print_path_parameters(&mut self,
2398 parameters: &ast::PathParameters,
2399 colons_before_params: bool)
2402 if colons_before_params {
2403 word(&mut self.s, "::")?
2407 ast::PathParameters::AngleBracketed(ref data) => {
2408 word(&mut self.s, "<")?;
2410 let mut comma = false;
2411 for lifetime in &data.lifetimes {
2413 self.word_space(",")?
2415 self.print_lifetime(lifetime)?;
2419 if !data.types.is_empty() {
2421 self.word_space(",")?
2426 |s, ty| s.print_type(&ty))?;
2430 for binding in data.bindings.iter() {
2432 self.word_space(",")?
2434 self.print_ident(binding.ident)?;
2435 space(&mut self.s)?;
2436 self.word_space("=")?;
2437 self.print_type(&binding.ty)?;
2441 word(&mut self.s, ">")?
2444 ast::PathParameters::Parenthesized(ref data) => {
2445 word(&mut self.s, "(")?;
2449 |s, ty| s.print_type(&ty))?;
2450 word(&mut self.s, ")")?;
2452 if let Some(ref ty) = data.output {
2453 self.space_if_not_bol()?;
2454 self.word_space("->")?;
2455 self.print_type(&ty)?;
2463 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2464 self.maybe_print_comment(pat.span.lo)?;
2465 self.ann.pre(self, NodePat(pat))?;
2466 /* Pat isn't normalized, but the beauty of it
2467 is that it doesn't matter */
2469 PatKind::Wild => word(&mut self.s, "_")?,
2470 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2471 match binding_mode {
2472 ast::BindingMode::ByRef(mutbl) => {
2473 self.word_nbsp("ref")?;
2474 self.print_mutability(mutbl)?;
2476 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2477 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2478 self.word_nbsp("mut")?;
2481 self.print_ident(path1.node)?;
2482 if let Some(ref p) = *sub {
2483 word(&mut self.s, "@")?;
2484 self.print_pat(&p)?;
2487 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2488 self.print_path(path, true, 0, false)?;
2490 if let Some(ddpos) = ddpos {
2491 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2493 self.word_space(",")?;
2495 word(&mut self.s, "..")?;
2496 if ddpos != elts.len() {
2497 word(&mut self.s, ",")?;
2498 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2501 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2505 PatKind::Path(None, ref path) => {
2506 self.print_path(path, true, 0, false)?;
2508 PatKind::Path(Some(ref qself), ref path) => {
2509 self.print_qpath(path, qself, false)?;
2511 PatKind::Struct(ref path, ref fields, etc) => {
2512 self.print_path(path, true, 0, false)?;
2514 self.word_space("{")?;
2516 Consistent, &fields[..],
2518 s.cbox(INDENT_UNIT)?;
2519 if !f.node.is_shorthand {
2520 s.print_ident(f.node.ident)?;
2523 s.print_pat(&f.node.pat)?;
2526 |f| f.node.pat.span)?;
2528 if !fields.is_empty() { self.word_space(",")?; }
2529 word(&mut self.s, "..")?;
2531 space(&mut self.s)?;
2532 word(&mut self.s, "}")?;
2534 PatKind::Tuple(ref elts, ddpos) => {
2536 if let Some(ddpos) = ddpos {
2537 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2539 self.word_space(",")?;
2541 word(&mut self.s, "..")?;
2542 if ddpos != elts.len() {
2543 word(&mut self.s, ",")?;
2544 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2547 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2548 if elts.len() == 1 {
2549 word(&mut self.s, ",")?;
2554 PatKind::Box(ref inner) => {
2555 word(&mut self.s, "box ")?;
2556 self.print_pat(&inner)?;
2558 PatKind::Ref(ref inner, mutbl) => {
2559 word(&mut self.s, "&")?;
2560 if mutbl == ast::Mutability::Mutable {
2561 word(&mut self.s, "mut ")?;
2563 self.print_pat(&inner)?;
2565 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2566 PatKind::Range(ref begin, ref end, ref end_kind) => {
2567 self.print_expr(&begin)?;
2568 space(&mut self.s)?;
2570 RangeEnd::Included => word(&mut self.s, "...")?,
2571 RangeEnd::Excluded => word(&mut self.s, "..")?,
2573 self.print_expr(&end)?;
2575 PatKind::Slice(ref before, ref slice, ref after) => {
2576 word(&mut self.s, "[")?;
2577 self.commasep(Inconsistent,
2579 |s, p| s.print_pat(&p))?;
2580 if let Some(ref p) = *slice {
2581 if !before.is_empty() { self.word_space(",")?; }
2582 if p.node != PatKind::Wild {
2583 self.print_pat(&p)?;
2585 word(&mut self.s, "..")?;
2586 if !after.is_empty() { self.word_space(",")?; }
2588 self.commasep(Inconsistent,
2590 |s, p| s.print_pat(&p))?;
2591 word(&mut self.s, "]")?;
2593 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2595 self.ann.post(self, NodePat(pat))
2598 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2599 // I have no idea why this check is necessary, but here it
2601 if arm.attrs.is_empty() {
2602 space(&mut self.s)?;
2604 self.cbox(INDENT_UNIT)?;
2606 self.maybe_print_comment(arm.pats[0].span.lo)?;
2607 self.print_outer_attributes(&arm.attrs)?;
2608 let mut first = true;
2609 for p in &arm.pats {
2613 space(&mut self.s)?;
2614 self.word_space("|")?;
2616 self.print_pat(&p)?;
2618 space(&mut self.s)?;
2619 if let Some(ref e) = arm.guard {
2620 self.word_space("if")?;
2621 self.print_expr(&e)?;
2622 space(&mut self.s)?;
2624 self.word_space("=>")?;
2626 match arm.body.node {
2627 ast::ExprKind::Block(ref blk) => {
2628 // the block will close the pattern's ibox
2629 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2631 // If it is a user-provided unsafe block, print a comma after it
2632 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2633 word(&mut self.s, ",")?;
2637 self.end()?; // close the ibox for the pattern
2638 self.print_expr(&arm.body)?;
2639 word(&mut self.s, ",")?;
2642 self.end() // close enclosing cbox
2645 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2646 match explicit_self.node {
2647 SelfKind::Value(m) => {
2648 self.print_mutability(m)?;
2649 word(&mut self.s, "self")
2651 SelfKind::Region(ref lt, m) => {
2652 word(&mut self.s, "&")?;
2653 self.print_opt_lifetime(lt)?;
2654 self.print_mutability(m)?;
2655 word(&mut self.s, "self")
2657 SelfKind::Explicit(ref typ, m) => {
2658 self.print_mutability(m)?;
2659 word(&mut self.s, "self")?;
2660 self.word_space(":")?;
2661 self.print_type(&typ)
2666 pub fn print_fn(&mut self,
2668 unsafety: ast::Unsafety,
2669 constness: ast::Constness,
2671 name: Option<ast::Ident>,
2672 generics: &ast::Generics,
2673 vis: &ast::Visibility) -> io::Result<()> {
2674 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2676 if let Some(name) = name {
2678 self.print_ident(name)?;
2680 self.print_generics(generics)?;
2681 self.print_fn_args_and_ret(decl)?;
2682 self.print_where_clause(&generics.where_clause)
2685 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2688 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2690 word(&mut self.s, ", ...")?;
2694 self.print_fn_output(decl)
2697 pub fn print_fn_block_args(
2701 word(&mut self.s, "|")?;
2702 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2703 word(&mut self.s, "|")?;
2705 if let ast::FunctionRetTy::Default(..) = decl.output {
2709 self.space_if_not_bol()?;
2710 self.word_space("->")?;
2712 ast::FunctionRetTy::Ty(ref ty) => {
2713 self.print_type(&ty)?;
2714 self.maybe_print_comment(ty.span.lo)
2716 ast::FunctionRetTy::Default(..) => unreachable!(),
2720 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2722 match capture_clause {
2723 ast::CaptureBy::Value => self.word_space("move"),
2724 ast::CaptureBy::Ref => Ok(()),
2728 pub fn print_bounds(&mut self,
2730 bounds: &[ast::TyParamBound])
2732 if !bounds.is_empty() {
2733 word(&mut self.s, prefix)?;
2734 let mut first = true;
2735 for bound in bounds {
2740 self.word_space("+")?;
2744 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2745 self.print_poly_trait_ref(tref)
2747 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2748 word(&mut self.s, "?")?;
2749 self.print_poly_trait_ref(tref)
2751 RegionTyParamBound(ref lt) => {
2752 self.print_lifetime(lt)
2762 pub fn print_lifetime(&mut self,
2763 lifetime: &ast::Lifetime)
2766 self.print_name(lifetime.name)
2769 pub fn print_lifetime_bounds(&mut self,
2770 lifetime: &ast::Lifetime,
2771 bounds: &[ast::Lifetime])
2774 self.print_lifetime(lifetime)?;
2775 if !bounds.is_empty() {
2776 word(&mut self.s, ": ")?;
2777 for (i, bound) in bounds.iter().enumerate() {
2779 word(&mut self.s, " + ")?;
2781 self.print_lifetime(bound)?;
2787 pub fn print_generics(&mut self,
2788 generics: &ast::Generics)
2791 let total = generics.lifetimes.len() + generics.ty_params.len();
2796 word(&mut self.s, "<")?;
2798 let mut ints = Vec::new();
2803 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2804 if idx < generics.lifetimes.len() {
2805 let lifetime_def = &generics.lifetimes[idx];
2806 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2807 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2809 let idx = idx - generics.lifetimes.len();
2810 let param = &generics.ty_params[idx];
2811 s.print_ty_param(param)
2815 word(&mut self.s, ">")?;
2819 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2820 self.print_outer_attributes_inline(¶m.attrs)?;
2821 self.print_ident(param.ident)?;
2822 self.print_bounds(":", ¶m.bounds)?;
2823 match param.default {
2824 Some(ref default) => {
2825 space(&mut self.s)?;
2826 self.word_space("=")?;
2827 self.print_type(&default)
2833 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2835 if where_clause.predicates.is_empty() {
2839 space(&mut self.s)?;
2840 self.word_space("where")?;
2842 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2844 self.word_space(",")?;
2848 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2852 self.print_formal_lifetime_list(bound_lifetimes)?;
2853 self.print_type(&bounded_ty)?;
2854 self.print_bounds(":", bounds)?;
2856 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2859 self.print_lifetime_bounds(lifetime, bounds)?;
2861 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2864 self.print_type(lhs_ty)?;
2865 space(&mut self.s)?;
2866 self.word_space("=")?;
2867 self.print_type(rhs_ty)?;
2875 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2877 ast::ViewPathSimple(ident, ref path) => {
2878 self.print_path(path, false, 0, true)?;
2880 if path.segments.last().unwrap().identifier.name !=
2882 space(&mut self.s)?;
2883 self.word_space("as")?;
2884 self.print_ident(ident)?;
2890 ast::ViewPathGlob(ref path) => {
2891 self.print_path(path, false, 0, true)?;
2892 word(&mut self.s, "::*")
2895 ast::ViewPathList(ref path, ref idents) => {
2896 if path.segments.is_empty() {
2897 word(&mut self.s, "{")?;
2899 self.print_path(path, false, 0, true)?;
2900 word(&mut self.s, "::{")?;
2902 self.commasep(Inconsistent, &idents[..], |s, w| {
2903 s.print_ident(w.node.name)?;
2904 if let Some(ident) = w.node.rename {
2906 s.word_space("as")?;
2907 s.print_ident(ident)?;
2911 word(&mut self.s, "}")
2916 pub fn print_mutability(&mut self,
2917 mutbl: ast::Mutability) -> io::Result<()> {
2919 ast::Mutability::Mutable => self.word_nbsp("mut"),
2920 ast::Mutability::Immutable => Ok(()),
2924 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2925 self.print_mutability(mt.mutbl)?;
2926 self.print_type(&mt.ty)
2929 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2930 self.ibox(INDENT_UNIT)?;
2931 match input.ty.node {
2932 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2934 if let Some(eself) = input.to_self() {
2935 self.print_explicit_self(&eself)?;
2937 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2938 ident.node.name == keywords::Invalid.name()
2943 self.print_pat(&input.pat)?;
2944 word(&mut self.s, ":")?;
2945 space(&mut self.s)?;
2947 self.print_type(&input.ty)?;
2954 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2955 if let ast::FunctionRetTy::Default(..) = decl.output {
2959 self.space_if_not_bol()?;
2960 self.ibox(INDENT_UNIT)?;
2961 self.word_space("->")?;
2963 ast::FunctionRetTy::Default(..) => unreachable!(),
2964 ast::FunctionRetTy::Ty(ref ty) =>
2965 self.print_type(&ty)?
2970 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2975 pub fn print_ty_fn(&mut self,
2977 unsafety: ast::Unsafety,
2979 name: Option<ast::Ident>,
2980 generics: &ast::Generics)
2982 self.ibox(INDENT_UNIT)?;
2983 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2984 word(&mut self.s, "for")?;
2985 self.print_generics(generics)?;
2987 let generics = ast::Generics {
2988 lifetimes: Vec::new(),
2989 ty_params: Vec::new(),
2990 where_clause: ast::WhereClause {
2991 id: ast::DUMMY_NODE_ID,
2992 predicates: Vec::new(),
2994 span: syntax_pos::DUMMY_SP,
2998 ast::Constness::NotConst,
3002 &ast::Visibility::Inherited)?;
3006 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3007 next_pos: Option<BytePos>)
3009 let cm = match self.cm {
3013 if let Some(ref cmnt) = self.next_comment() {
3014 if cmnt.style != comments::Trailing { return Ok(()) }
3015 let span_line = cm.lookup_char_pos(span.hi);
3016 let comment_line = cm.lookup_char_pos(cmnt.pos);
3017 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3018 if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3019 self.print_comment(cmnt)?;
3020 self.cur_cmnt_and_lit.cur_cmnt += 1;
3026 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3027 // If there aren't any remaining comments, then we need to manually
3028 // make sure there is a line break at the end.
3029 if self.next_comment().is_none() {
3030 hardbreak(&mut self.s)?;
3033 match self.next_comment() {
3035 self.print_comment(cmnt)?;
3036 self.cur_cmnt_and_lit.cur_cmnt += 1;
3044 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3045 opt_abi: Option<Abi>)
3048 Some(Abi::Rust) => Ok(()),
3050 self.word_nbsp("extern")?;
3051 self.word_nbsp(&abi.to_string())
3057 pub fn print_extern_opt_abi(&mut self,
3058 opt_abi: Option<Abi>) -> io::Result<()> {
3061 self.word_nbsp("extern")?;
3062 self.word_nbsp(&abi.to_string())
3068 pub fn print_fn_header_info(&mut self,
3069 unsafety: ast::Unsafety,
3070 constness: ast::Constness,
3072 vis: &ast::Visibility) -> io::Result<()> {
3073 word(&mut self.s, &visibility_qualified(vis, ""))?;
3076 ast::Constness::NotConst => {}
3077 ast::Constness::Const => self.word_nbsp("const")?
3080 self.print_unsafety(unsafety)?;
3082 if abi != Abi::Rust {
3083 self.word_nbsp("extern")?;
3084 self.word_nbsp(&abi.to_string())?;
3087 word(&mut self.s, "fn")
3090 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3092 ast::Unsafety::Normal => Ok(()),
3093 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3098 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3109 fn test_fun_to_string() {
3110 let abba_ident = ast::Ident::from_str("abba");
3112 let decl = ast::FnDecl {
3114 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3117 let generics = ast::Generics::default();
3118 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3119 ast::Constness::NotConst,
3120 abba_ident, &generics),
3125 fn test_variant_to_string() {
3126 let ident = ast::Ident::from_str("principal_skinner");
3128 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3131 // making this up as I go.... ?
3132 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3136 let varstr = variant_to_string(&var);
3137 assert_eq!(varstr, "principal_skinner");