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, Breaks};
25 use print::pp::Breaks::{Consistent, Inconsistent};
28 use symbol::{Symbol, keywords};
29 use syntax_pos::DUMMY_SP;
30 use tokenstream::{self, TokenStream, TokenTree};
33 use std::io::{self, Write, Read};
34 use std::iter::{self, Peekable};
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 pub struct State<'a> {
58 pub s: pp::Printer<'a>,
59 cm: Option<&'a CodeMap>,
60 comments: Option<Vec<comments::Comment> >,
61 literals: Peekable<vec::IntoIter<comments::Literal>>,
63 boxes: Vec<pp::Breaks>,
67 fn rust_printer<'a>(writer: Box<Write+'a>, ann: &'a PpAnn) -> State<'a> {
69 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
72 literals: vec![].into_iter().peekable(),
79 pub const INDENT_UNIT: usize = 4;
81 pub const DEFAULT_COLUMNS: usize = 78;
83 /// Requires you to pass an input filename and reader so that
84 /// it can scan the input text for comments and literals to
86 pub fn print_crate<'a>(cm: &'a CodeMap,
93 is_expanded: bool) -> io::Result<()> {
94 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
96 if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
97 // We need to print `#![no_std]` (and its feature gate) so that
98 // compiling pretty-printed source won't inject libstd again.
99 // However we don't want these attributes in the AST because
100 // of the feature gate, so we fake them up here.
102 // #![feature(prelude_import)]
103 let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
104 let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
105 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
106 s.print_attribute(&fake_attr)?;
109 let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
110 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
111 s.print_attribute(&fake_attr)?;
114 s.print_mod(&krate.module, &krate.attrs)?;
115 s.print_remaining_comments()?;
120 pub fn new_from_input(cm: &'a CodeMap,
126 is_expanded: bool) -> State<'a> {
127 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
134 // If the code is post expansion, don't use the table of
135 // literals, since it doesn't correspond with the literals
136 // in the AST anymore.
137 if is_expanded { None } else { Some(lits) })
140 pub fn new(cm: &'a CodeMap,
143 comments: Option<Vec<comments::Comment>>,
144 literals: Option<Vec<comments::Literal>>) -> State<'a> {
146 s: pp::mk_printer(out, DEFAULT_COLUMNS),
149 literals: literals.unwrap_or_default().into_iter().peekable(),
157 pub fn to_string<F>(f: F) -> String where
158 F: FnOnce(&mut State) -> io::Result<()>,
160 let mut wr = Vec::new();
163 let mut printer = rust_printer(Box::new(&mut wr), &ann);
164 f(&mut printer).unwrap();
165 printer.s.eof().unwrap();
167 String::from_utf8(wr).unwrap()
170 fn binop_to_string(op: BinOpToken) -> &'static str {
176 token::Percent => "%",
185 pub fn token_to_string(tok: &Token) -> String {
187 token::Eq => "=".to_string(),
188 token::Lt => "<".to_string(),
189 token::Le => "<=".to_string(),
190 token::EqEq => "==".to_string(),
191 token::Ne => "!=".to_string(),
192 token::Ge => ">=".to_string(),
193 token::Gt => ">".to_string(),
194 token::Not => "!".to_string(),
195 token::Tilde => "~".to_string(),
196 token::OrOr => "||".to_string(),
197 token::AndAnd => "&&".to_string(),
198 token::BinOp(op) => binop_to_string(op).to_string(),
199 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
201 /* Structural symbols */
202 token::At => "@".to_string(),
203 token::Dot => ".".to_string(),
204 token::DotDot => "..".to_string(),
205 token::DotDotDot => "...".to_string(),
206 token::Comma => ",".to_string(),
207 token::Semi => ";".to_string(),
208 token::Colon => ":".to_string(),
209 token::ModSep => "::".to_string(),
210 token::RArrow => "->".to_string(),
211 token::LArrow => "<-".to_string(),
212 token::FatArrow => "=>".to_string(),
213 token::OpenDelim(token::Paren) => "(".to_string(),
214 token::CloseDelim(token::Paren) => ")".to_string(),
215 token::OpenDelim(token::Bracket) => "[".to_string(),
216 token::CloseDelim(token::Bracket) => "]".to_string(),
217 token::OpenDelim(token::Brace) => "{".to_string(),
218 token::CloseDelim(token::Brace) => "}".to_string(),
219 token::OpenDelim(token::NoDelim) |
220 token::CloseDelim(token::NoDelim) => " ".to_string(),
221 token::Pound => "#".to_string(),
222 token::Dollar => "$".to_string(),
223 token::Question => "?".to_string(),
226 token::Literal(lit, suf) => {
227 let mut out = match lit {
228 token::Byte(b) => format!("b'{}'", b),
229 token::Char(c) => format!("'{}'", c),
231 token::Integer(c) => c.to_string(),
232 token::Str_(s) => format!("\"{}\"", s),
233 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
234 delim=repeat("#", n),
236 token::ByteStr(v) => format!("b\"{}\"", v),
237 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
238 delim=repeat("#", n),
242 if let Some(s) = suf {
243 out.push_str(&s.as_str())
249 /* Name components */
250 token::Ident(s) => s.to_string(),
251 token::Lifetime(s) => s.to_string(),
252 token::Underscore => "_".to_string(),
255 token::DocComment(s) => s.to_string(),
256 token::Eof => "<eof>".to_string(),
257 token::Whitespace => " ".to_string(),
258 token::Comment => "/* */".to_string(),
259 token::Shebang(s) => format!("/* shebang: {}*/", s),
261 token::Interpolated(ref nt) => match nt.0 {
262 token::NtExpr(ref e) => expr_to_string(e),
263 token::NtMeta(ref e) => meta_item_to_string(e),
264 token::NtTy(ref e) => ty_to_string(e),
265 token::NtPath(ref e) => path_to_string(e),
266 token::NtItem(ref e) => item_to_string(e),
267 token::NtBlock(ref e) => block_to_string(e),
268 token::NtStmt(ref e) => stmt_to_string(e),
269 token::NtPat(ref e) => pat_to_string(e),
270 token::NtIdent(ref e) => ident_to_string(e.node),
271 token::NtTT(ref tree) => tt_to_string(tree.clone()),
272 token::NtArm(ref e) => arm_to_string(e),
273 token::NtImplItem(ref e) => impl_item_to_string(e),
274 token::NtTraitItem(ref e) => trait_item_to_string(e),
275 token::NtGenerics(ref e) => generics_to_string(e),
276 token::NtWhereClause(ref e) => where_clause_to_string(e),
277 token::NtArg(ref e) => arg_to_string(e),
278 token::NtVis(ref e) => vis_to_string(e),
283 pub fn ty_to_string(ty: &ast::Ty) -> String {
284 to_string(|s| s.print_type(ty))
287 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
288 to_string(|s| s.print_bounds("", bounds))
291 pub fn pat_to_string(pat: &ast::Pat) -> String {
292 to_string(|s| s.print_pat(pat))
295 pub fn arm_to_string(arm: &ast::Arm) -> String {
296 to_string(|s| s.print_arm(arm))
299 pub fn expr_to_string(e: &ast::Expr) -> String {
300 to_string(|s| s.print_expr(e))
303 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
304 to_string(|s| s.print_lifetime(e))
307 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
308 to_string(|s| s.print_tt(tt))
311 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
312 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
315 pub fn tokens_to_string(tokens: TokenStream) -> String {
316 to_string(|s| s.print_tts(tokens))
319 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
320 to_string(|s| s.print_stmt(stmt))
323 pub fn attr_to_string(attr: &ast::Attribute) -> String {
324 to_string(|s| s.print_attribute(attr))
327 pub fn item_to_string(i: &ast::Item) -> String {
328 to_string(|s| s.print_item(i))
331 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
332 to_string(|s| s.print_impl_item(i))
335 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
336 to_string(|s| s.print_trait_item(i))
339 pub fn generics_to_string(generics: &ast::Generics) -> String {
340 to_string(|s| s.print_generics(generics))
343 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
344 to_string(|s| s.print_where_clause(i))
347 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
348 to_string(|s| s.print_fn_block_args(p))
351 pub fn path_to_string(p: &ast::Path) -> String {
352 to_string(|s| s.print_path(p, false, 0, false))
355 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
356 to_string(|s| s.print_path_segment(p, false))
359 pub fn ident_to_string(id: ast::Ident) -> String {
360 to_string(|s| s.print_ident(id))
363 pub fn vis_to_string(v: &ast::Visibility) -> String {
364 to_string(|s| s.print_visibility(v))
367 pub fn fun_to_string(decl: &ast::FnDecl,
368 unsafety: ast::Unsafety,
369 constness: ast::Constness,
371 generics: &ast::Generics)
375 s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
376 generics, &ast::Visibility::Inherited)?;
377 s.end()?; // Close the head box
378 s.end() // Close the outer box
382 pub fn block_to_string(blk: &ast::Block) -> String {
384 // containing cbox, will be closed by print-block at }
385 s.cbox(INDENT_UNIT)?;
386 // head-ibox, will be closed by print-block after {
392 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
393 to_string(|s| s.print_meta_list_item(li))
396 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
397 to_string(|s| s.print_meta_item(mi))
400 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
401 to_string(|s| s.print_attribute(attr))
404 pub fn lit_to_string(l: &ast::Lit) -> String {
405 to_string(|s| s.print_literal(l))
408 pub fn variant_to_string(var: &ast::Variant) -> String {
409 to_string(|s| s.print_variant(var))
412 pub fn arg_to_string(arg: &ast::Arg) -> String {
413 to_string(|s| s.print_arg(arg, false))
416 pub fn mac_to_string(arg: &ast::Mac) -> String {
417 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
420 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
421 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
424 fn needs_parentheses(expr: &ast::Expr) -> bool {
426 ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
427 ast::ExprKind::Closure(..) |
428 ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
429 ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
434 pub trait PrintState<'a> {
435 fn writer(&mut self) -> &mut pp::Printer<'a>;
436 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
437 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
438 fn cur_cmnt(&mut self) -> &mut usize;
439 fn cur_lit(&mut self) -> Option<&comments::Literal>;
440 fn bump_lit(&mut self) -> Option<comments::Literal>;
442 fn word_space(&mut self, w: &str) -> io::Result<()> {
443 self.writer().word(w)?;
444 self.writer().space()
447 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
449 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
451 fn is_begin(&mut self) -> bool {
452 match self.writer().last_token() {
453 pp::Token::Begin(_) => true,
458 fn is_end(&mut self) -> bool {
459 match self.writer().last_token() {
460 pp::Token::End => true,
465 // is this the beginning of a line?
466 fn is_bol(&mut self) -> bool {
467 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
470 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
472 self.writer().hardbreak()?
478 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
479 self.boxes().push(b);
480 self.writer().rbox(u, b)
483 fn ibox(&mut self, u: usize) -> io::Result<()> {
484 self.boxes().push(pp::Breaks::Inconsistent);
485 self.writer().ibox(u)
488 fn end(&mut self) -> io::Result<()> {
489 self.boxes().pop().unwrap();
493 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
494 where F: FnMut(&mut Self, &T) -> io::Result<()>,
497 let mut first = true;
499 if first { first = false; } else { self.word_space(",")?; }
505 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
506 while let Some(ltrl) = self.cur_lit().cloned() {
507 if ltrl.pos > pos { break; }
509 // we don't need the value here since we're forced to clone cur_lit
510 // due to lack of NLL.
520 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
521 while let Some(ref cmnt) = self.next_comment() {
523 self.print_comment(cmnt)?;
531 fn print_comment(&mut self,
532 cmnt: &comments::Comment) -> io::Result<()> {
533 let r = match cmnt.style {
535 assert_eq!(cmnt.lines.len(), 1);
536 self.writer().zerobreak()?;
537 self.writer().word(&cmnt.lines[0])?;
538 self.writer().zerobreak()
540 comments::Isolated => {
541 self.hardbreak_if_not_bol()?;
542 for line in &cmnt.lines {
543 // Don't print empty lines because they will end up as trailing
545 if !line.is_empty() {
546 self.writer().word(&line[..])?;
548 self.writer().hardbreak()?;
552 comments::Trailing => {
554 self.writer().word(" ")?;
556 if cmnt.lines.len() == 1 {
557 self.writer().word(&cmnt.lines[0])?;
558 self.writer().hardbreak()
561 for line in &cmnt.lines {
562 if !line.is_empty() {
563 self.writer().word(&line[..])?;
565 self.writer().hardbreak()?;
570 comments::BlankLine => {
571 // We need to do at least one, possibly two hardbreaks.
572 let is_semi = match self.writer().last_token() {
573 pp::Token::String(s, _) => ";" == s,
576 if is_semi || self.is_begin() || self.is_end() {
577 self.writer().hardbreak()?;
579 self.writer().hardbreak()
584 *self.cur_cmnt() = *self.cur_cmnt() + 1;
591 fn next_comment(&mut self) -> Option<comments::Comment> {
592 let cur_cmnt = *self.cur_cmnt();
593 match *self.comments() {
595 if cur_cmnt < cmnts.len() {
596 Some(cmnts[cur_cmnt].clone())
605 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
606 self.maybe_print_comment(lit.span.lo())?;
607 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
608 return self.writer().word(<rl.lit);
611 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
612 ast::LitKind::Byte(byte) => {
613 let mut res = String::from("b'");
614 res.extend(ascii::escape_default(byte).map(|c| c as char));
616 self.writer().word(&res[..])
618 ast::LitKind::Char(ch) => {
619 let mut res = String::from("'");
620 res.extend(ch.escape_default());
622 self.writer().word(&res[..])
624 ast::LitKind::Int(i, t) => {
626 ast::LitIntType::Signed(st) => {
627 self.writer().word(&st.val_to_string(i as i128))
629 ast::LitIntType::Unsigned(ut) => {
630 self.writer().word(&ut.val_to_string(i))
632 ast::LitIntType::Unsuffixed => {
633 self.writer().word(&format!("{}", i))
637 ast::LitKind::Float(ref f, t) => {
638 self.writer().word(&format!("{}{}", &f, t.ty_to_string()))
640 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()),
641 ast::LitKind::Bool(val) => {
642 if val { self.writer().word("true") } else { self.writer().word("false") }
644 ast::LitKind::ByteStr(ref v) => {
645 let mut escaped: String = String::new();
646 for &ch in v.iter() {
647 escaped.extend(ascii::escape_default(ch)
648 .map(|c| c as char));
650 self.writer().word(&format!("b\"{}\"", escaped))
655 fn print_string(&mut self, st: &str,
656 style: ast::StrStyle) -> io::Result<()> {
657 let st = match style {
658 ast::StrStyle::Cooked => {
659 (format!("\"{}\"", parse::escape_default(st)))
661 ast::StrStyle::Raw(n) => {
662 (format!("r{delim}\"{string}\"{delim}",
663 delim=repeat("#", n),
667 self.writer().word(&st[..])
670 fn print_inner_attributes(&mut self,
671 attrs: &[ast::Attribute]) -> io::Result<()> {
672 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
675 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
676 attrs: &[ast::Attribute])
678 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
681 fn print_outer_attributes(&mut self,
682 attrs: &[ast::Attribute]) -> io::Result<()> {
683 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
686 fn print_inner_attributes_inline(&mut self,
687 attrs: &[ast::Attribute]) -> io::Result<()> {
688 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
691 fn print_outer_attributes_inline(&mut self,
692 attrs: &[ast::Attribute]) -> io::Result<()> {
693 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
696 fn print_either_attributes(&mut self,
697 attrs: &[ast::Attribute],
698 kind: ast::AttrStyle,
700 trailing_hardbreak: bool) -> io::Result<()> {
703 if attr.style == kind {
704 self.print_attribute_inline(attr, is_inline)?;
711 if count > 0 && trailing_hardbreak && !is_inline {
712 self.hardbreak_if_not_bol()?;
717 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
718 self.print_attribute_inline(attr, false)
721 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
722 is_inline: bool) -> io::Result<()> {
724 self.hardbreak_if_not_bol()?;
726 self.maybe_print_comment(attr.span.lo())?;
727 if attr.is_sugared_doc {
728 self.writer().word(&attr.value_str().unwrap().as_str())?;
729 self.writer().hardbreak()
732 ast::AttrStyle::Inner => self.writer().word("#![")?,
733 ast::AttrStyle::Outer => self.writer().word("#[")?,
735 if let Some(mi) = attr.meta() {
736 self.print_meta_item(&mi)?
738 for (i, segment) in attr.path.segments.iter().enumerate() {
740 self.writer().word("::")?
742 if segment.identifier.name != keywords::CrateRoot.name() &&
743 segment.identifier.name != keywords::DollarCrate.name() {
744 self.writer().word(&segment.identifier.name.as_str())?;
747 self.writer().space()?;
748 self.print_tts(attr.tokens.clone())?;
750 self.writer().word("]")
754 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
756 ast::NestedMetaItemKind::MetaItem(ref mi) => {
757 self.print_meta_item(mi)
759 ast::NestedMetaItemKind::Literal(ref lit) => {
760 self.print_literal(lit)
765 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
766 self.ibox(INDENT_UNIT)?;
768 ast::MetaItemKind::Word => {
769 self.writer().word(&item.name.as_str())?;
771 ast::MetaItemKind::NameValue(ref value) => {
772 self.word_space(&item.name.as_str())?;
773 self.word_space("=")?;
774 self.print_literal(value)?;
776 ast::MetaItemKind::List(ref items) => {
777 self.writer().word(&item.name.as_str())?;
779 self.commasep(Consistent,
781 |s, i| s.print_meta_list_item(i))?;
788 /// This doesn't deserve to be called "pretty" printing, but it should be
789 /// meaning-preserving. A quick hack that might help would be to look at the
790 /// spans embedded in the TTs to decide where to put spaces and newlines.
791 /// But it'd be better to parse these according to the grammar of the
792 /// appropriate macro, transcribe back into the grammar we just parsed from,
793 /// and then pretty-print the resulting AST nodes (so, e.g., we print
794 /// expression arguments as expressions). It can be done! I think.
795 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
797 TokenTree::Token(_, ref tk) => {
798 self.writer().word(&token_to_string(tk))?;
800 parse::token::DocComment(..) => {
801 self.writer().hardbreak()
806 TokenTree::Delimited(_, ref delimed) => {
807 self.writer().word(&token_to_string(&delimed.open_token()))?;
808 self.writer().space()?;
809 self.print_tts(delimed.stream())?;
810 self.writer().space()?;
811 self.writer().word(&token_to_string(&delimed.close_token()))
816 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
818 for (i, tt) in tts.into_trees().enumerate() {
820 self.writer().space()?;
827 fn space_if_not_bol(&mut self) -> io::Result<()> {
828 if !self.is_bol() { self.writer().space()?; }
832 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
835 impl<'a> PrintState<'a> for State<'a> {
836 fn writer(&mut self) -> &mut pp::Printer<'a> {
840 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
844 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
848 fn cur_cmnt(&mut self) -> &mut usize {
852 fn cur_lit(&mut self) -> Option<&comments::Literal> {
856 fn bump_lit(&mut self) -> Option<comments::Literal> {
862 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
863 self.boxes.push(pp::Breaks::Consistent);
867 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
872 pub fn head(&mut self, w: &str) -> io::Result<()> {
873 // outer-box is consistent
874 self.cbox(INDENT_UNIT)?;
875 // head-box is inconsistent
876 self.ibox(w.len() + 1)?;
877 // keyword that starts the head
884 pub fn bopen(&mut self) -> io::Result<()> {
886 self.end() // close the head-box
889 pub fn bclose_(&mut self, span: syntax_pos::Span,
890 indented: usize) -> io::Result<()> {
891 self.bclose_maybe_open(span, indented, true)
893 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
894 indented: usize, close_box: bool) -> io::Result<()> {
895 self.maybe_print_comment(span.hi())?;
896 self.break_offset_if_not_bol(1, -(indented as isize))?;
899 self.end()?; // close the outer-box
903 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
904 self.bclose_(span, INDENT_UNIT)
907 pub fn in_cbox(&self) -> bool {
908 match self.boxes.last() {
909 Some(&last_box) => last_box == pp::Breaks::Consistent,
914 pub fn break_offset_if_not_bol(&mut self, n: usize,
915 off: isize) -> io::Result<()> {
917 self.s.break_offset(n, off)
919 if off != 0 && self.s.last_token().is_hardbreak_tok() {
920 // We do something pretty sketchy here: tuck the nonzero
921 // offset-adjustment we were going to deposit along with the
922 // break into the previous hardbreak.
923 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
929 // Synthesizes a comment that was not textually present in the original source
931 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
934 self.s.word(&text[..])?;
941 pub fn commasep_cmnt<T, F, G>(&mut self,
945 mut get_span: G) -> io::Result<()> where
946 F: FnMut(&mut State, &T) -> io::Result<()>,
947 G: FnMut(&T) -> syntax_pos::Span,
950 let len = elts.len();
953 self.maybe_print_comment(get_span(elt).hi())?;
958 self.maybe_print_trailing_comment(get_span(elt),
959 Some(get_span(&elts[i]).hi()))?;
960 self.space_if_not_bol()?;
966 pub fn commasep_exprs(&mut self, b: Breaks,
967 exprs: &[P<ast::Expr>]) -> io::Result<()> {
968 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
971 pub fn print_mod(&mut self, _mod: &ast::Mod,
972 attrs: &[ast::Attribute]) -> io::Result<()> {
973 self.print_inner_attributes(attrs)?;
974 for item in &_mod.items {
975 self.print_item(item)?;
980 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
981 attrs: &[ast::Attribute]) -> io::Result<()> {
982 self.print_inner_attributes(attrs)?;
983 for item in &nmod.items {
984 self.print_foreign_item(item)?;
989 pub fn print_opt_lifetime(&mut self,
990 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
991 if let Some(l) = *lifetime {
992 self.print_lifetime(&l)?;
998 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
999 self.maybe_print_comment(ty.span.lo())?;
1002 ast::TyKind::Slice(ref ty) => {
1004 self.print_type(ty)?;
1007 ast::TyKind::Ptr(ref mt) => {
1010 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1011 ast::Mutability::Immutable => self.word_nbsp("const")?,
1013 self.print_type(&mt.ty)?;
1015 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1017 self.print_opt_lifetime(lifetime)?;
1020 ast::TyKind::Never => {
1023 ast::TyKind::Tup(ref elts) => {
1025 self.commasep(Inconsistent, &elts[..],
1026 |s, ty| s.print_type(ty))?;
1027 if elts.len() == 1 {
1032 ast::TyKind::Paren(ref typ) => {
1034 self.print_type(typ)?;
1037 ast::TyKind::BareFn(ref f) => {
1038 let generics = ast::Generics {
1039 lifetimes: f.lifetimes.clone(),
1040 ty_params: Vec::new(),
1041 where_clause: ast::WhereClause {
1042 id: ast::DUMMY_NODE_ID,
1043 predicates: Vec::new(),
1044 span: syntax_pos::DUMMY_SP,
1046 span: syntax_pos::DUMMY_SP,
1048 self.print_ty_fn(f.abi,
1054 ast::TyKind::Path(None, ref path) => {
1055 self.print_path(path, false, 0, false)?;
1057 ast::TyKind::Path(Some(ref qself), ref path) => {
1058 self.print_qpath(path, qself, false)?
1060 ast::TyKind::TraitObject(ref bounds) => {
1061 self.print_bounds("", &bounds[..])?;
1063 ast::TyKind::ImplTrait(ref bounds) => {
1064 self.print_bounds("impl ", &bounds[..])?;
1066 ast::TyKind::Array(ref ty, ref v) => {
1068 self.print_type(ty)?;
1070 self.print_expr(v)?;
1073 ast::TyKind::Typeof(ref e) => {
1074 self.s.word("typeof(")?;
1075 self.print_expr(e)?;
1078 ast::TyKind::Infer => {
1081 ast::TyKind::Err => {
1084 ast::TyKind::ImplicitSelf => {
1085 self.s.word("Self")?;
1087 ast::TyKind::Mac(ref m) => {
1088 self.print_mac(m, token::Paren)?;
1094 pub fn print_foreign_item(&mut self,
1095 item: &ast::ForeignItem) -> io::Result<()> {
1096 self.hardbreak_if_not_bol()?;
1097 self.maybe_print_comment(item.span.lo())?;
1098 self.print_outer_attributes(&item.attrs)?;
1100 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1102 self.print_fn(decl, ast::Unsafety::Normal,
1103 ast::Constness::NotConst,
1104 Abi::Rust, Some(item.ident),
1105 generics, &item.vis)?;
1106 self.end()?; // end head-ibox
1108 self.end() // end the outer fn box
1110 ast::ForeignItemKind::Static(ref t, m) => {
1111 self.head(&visibility_qualified(&item.vis, "static"))?;
1113 self.word_space("mut")?;
1115 self.print_ident(item.ident)?;
1116 self.word_space(":")?;
1117 self.print_type(t)?;
1119 self.end()?; // end the head-ibox
1120 self.end() // end the outer cbox
1125 fn print_associated_const(&mut self,
1128 default: Option<&ast::Expr>,
1129 vis: &ast::Visibility)
1132 self.s.word(&visibility_qualified(vis, ""))?;
1133 self.word_space("const")?;
1134 self.print_ident(ident)?;
1135 self.word_space(":")?;
1136 self.print_type(ty)?;
1137 if let Some(expr) = default {
1139 self.word_space("=")?;
1140 self.print_expr(expr)?;
1145 fn print_associated_type(&mut self,
1147 bounds: Option<&ast::TyParamBounds>,
1148 ty: Option<&ast::Ty>)
1150 self.word_space("type")?;
1151 self.print_ident(ident)?;
1152 if let Some(bounds) = bounds {
1153 self.print_bounds(":", bounds)?;
1155 if let Some(ty) = ty {
1157 self.word_space("=")?;
1158 self.print_type(ty)?;
1163 /// Pretty-print an item
1164 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1165 self.hardbreak_if_not_bol()?;
1166 self.maybe_print_comment(item.span.lo())?;
1167 self.print_outer_attributes(&item.attrs)?;
1168 self.ann.pre(self, NodeItem(item))?;
1170 ast::ItemKind::ExternCrate(ref optional_path) => {
1171 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1172 if let Some(p) = *optional_path {
1173 let val = p.as_str();
1174 if val.contains('-') {
1175 self.print_string(&val, ast::StrStyle::Cooked)?;
1177 self.print_name(p)?;
1183 self.print_ident(item.ident)?;
1185 self.end()?; // end inner head-block
1186 self.end()?; // end outer head-block
1188 ast::ItemKind::Use(ref vp) => {
1189 self.head(&visibility_qualified(&item.vis, "use"))?;
1190 self.print_view_path(vp)?;
1192 self.end()?; // end inner head-block
1193 self.end()?; // end outer head-block
1195 ast::ItemKind::Static(ref ty, m, ref expr) => {
1196 self.head(&visibility_qualified(&item.vis, "static"))?;
1197 if m == ast::Mutability::Mutable {
1198 self.word_space("mut")?;
1200 self.print_ident(item.ident)?;
1201 self.word_space(":")?;
1202 self.print_type(ty)?;
1204 self.end()?; // end the head-ibox
1206 self.word_space("=")?;
1207 self.print_expr(expr)?;
1209 self.end()?; // end the outer cbox
1211 ast::ItemKind::Const(ref ty, ref expr) => {
1212 self.head(&visibility_qualified(&item.vis, "const"))?;
1213 self.print_ident(item.ident)?;
1214 self.word_space(":")?;
1215 self.print_type(ty)?;
1217 self.end()?; // end the head-ibox
1219 self.word_space("=")?;
1220 self.print_expr(expr)?;
1222 self.end()?; // end the outer cbox
1224 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1236 self.print_block_with_attrs(body, &item.attrs)?;
1238 ast::ItemKind::Mod(ref _mod) => {
1239 self.head(&visibility_qualified(&item.vis, "mod"))?;
1240 self.print_ident(item.ident)?;
1243 self.print_mod(_mod, &item.attrs)?;
1244 self.bclose(item.span)?;
1246 ast::ItemKind::ForeignMod(ref nmod) => {
1247 self.head("extern")?;
1248 self.word_nbsp(&nmod.abi.to_string())?;
1250 self.print_foreign_mod(nmod, &item.attrs)?;
1251 self.bclose(item.span)?;
1253 ast::ItemKind::GlobalAsm(ref ga) => {
1254 self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
1255 self.s.word(&ga.asm.as_str())?;
1258 ast::ItemKind::Ty(ref ty, ref params) => {
1259 self.ibox(INDENT_UNIT)?;
1261 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1262 self.print_ident(item.ident)?;
1263 self.print_generics(params)?;
1264 self.end()?; // end the inner ibox
1266 self.print_where_clause(¶ms.where_clause)?;
1268 self.word_space("=")?;
1269 self.print_type(ty)?;
1271 self.end()?; // end the outer ibox
1273 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1274 self.print_enum_def(
1282 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1283 self.head(&visibility_qualified(&item.vis, "struct"))?;
1284 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1286 ast::ItemKind::Union(ref struct_def, ref generics) => {
1287 self.head(&visibility_qualified(&item.vis, "union"))?;
1288 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1290 ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1292 self.print_visibility(&item.vis)?;
1293 self.print_unsafety(unsafety)?;
1294 self.word_nbsp("impl")?;
1295 self.print_trait_ref(trait_ref)?;
1297 self.word_space("for")?;
1298 self.word_space("..")?;
1300 self.bclose(item.span)?;
1302 ast::ItemKind::Impl(unsafety,
1308 ref impl_items) => {
1310 self.print_visibility(&item.vis)?;
1311 self.print_defaultness(defaultness)?;
1312 self.print_unsafety(unsafety)?;
1313 self.word_nbsp("impl")?;
1315 if generics.is_parameterized() {
1316 self.print_generics(generics)?;
1320 if polarity == ast::ImplPolarity::Negative {
1324 if let Some(ref t) = *opt_trait {
1325 self.print_trait_ref(t)?;
1327 self.word_space("for")?;
1330 self.print_type(ty)?;
1331 self.print_where_clause(&generics.where_clause)?;
1335 self.print_inner_attributes(&item.attrs)?;
1336 for impl_item in impl_items {
1337 self.print_impl_item(impl_item)?;
1339 self.bclose(item.span)?;
1341 ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1343 self.print_visibility(&item.vis)?;
1344 self.print_unsafety(unsafety)?;
1345 self.word_nbsp("trait")?;
1346 self.print_ident(item.ident)?;
1347 self.print_generics(generics)?;
1348 let mut real_bounds = Vec::with_capacity(bounds.len());
1349 for b in bounds.iter() {
1350 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1352 self.word_space("for ?")?;
1353 self.print_trait_ref(&ptr.trait_ref)?;
1355 real_bounds.push(b.clone());
1358 self.print_bounds(":", &real_bounds[..])?;
1359 self.print_where_clause(&generics.where_clause)?;
1362 for trait_item in trait_items {
1363 self.print_trait_item(trait_item)?;
1365 self.bclose(item.span)?;
1367 ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1368 self.print_path(&node.path, false, 0, false)?;
1370 self.print_ident(item.ident)?;
1371 self.cbox(INDENT_UNIT)?;
1373 self.print_tts(node.stream())?;
1378 ast::ItemKind::MacroDef(ref tts) => {
1379 self.s.word("macro_rules! ")?;
1380 self.print_ident(item.ident)?;
1381 self.cbox(INDENT_UNIT)?;
1383 self.print_tts(tts.stream())?;
1389 self.ann.post(self, NodeItem(item))
1392 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1393 self.print_path(&t.path, false, 0, false)
1396 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1397 if !lifetimes.is_empty() {
1398 self.s.word("for<")?;
1399 let mut comma = false;
1400 for lifetime_def in lifetimes {
1402 self.word_space(",")?
1404 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1405 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1413 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1414 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1415 self.print_trait_ref(&t.trait_ref)
1418 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1419 generics: &ast::Generics, ident: ast::Ident,
1420 span: syntax_pos::Span,
1421 visibility: &ast::Visibility) -> io::Result<()> {
1422 self.head(&visibility_qualified(visibility, "enum"))?;
1423 self.print_ident(ident)?;
1424 self.print_generics(generics)?;
1425 self.print_where_clause(&generics.where_clause)?;
1427 self.print_variants(&enum_definition.variants, span)
1430 pub fn print_variants(&mut self,
1431 variants: &[ast::Variant],
1432 span: syntax_pos::Span) -> io::Result<()> {
1435 self.space_if_not_bol()?;
1436 self.maybe_print_comment(v.span.lo())?;
1437 self.print_outer_attributes(&v.node.attrs)?;
1438 self.ibox(INDENT_UNIT)?;
1439 self.print_variant(v)?;
1442 self.maybe_print_trailing_comment(v.span, None)?;
1447 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1449 ast::Visibility::Public => self.word_nbsp("pub"),
1450 ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1451 ast::Visibility::Restricted { ref path, .. } => {
1452 let path = to_string(|s| s.print_path(path, false, 0, true));
1453 if path == "self" || path == "super" {
1454 self.word_nbsp(&format!("pub({})", path))
1456 self.word_nbsp(&format!("pub(in {})", path))
1459 ast::Visibility::Inherited => Ok(())
1463 pub fn print_defaultness(&mut self, defatulness: ast::Defaultness) -> io::Result<()> {
1464 if let ast::Defaultness::Default = defatulness {
1465 try!(self.word_nbsp("default"));
1470 pub fn print_struct(&mut self,
1471 struct_def: &ast::VariantData,
1472 generics: &ast::Generics,
1474 span: syntax_pos::Span,
1475 print_finalizer: bool) -> io::Result<()> {
1476 self.print_ident(ident)?;
1477 self.print_generics(generics)?;
1478 if !struct_def.is_struct() {
1479 if struct_def.is_tuple() {
1482 Inconsistent, struct_def.fields(),
1484 s.maybe_print_comment(field.span.lo())?;
1485 s.print_outer_attributes(&field.attrs)?;
1486 s.print_visibility(&field.vis)?;
1487 s.print_type(&field.ty)
1492 self.print_where_clause(&generics.where_clause)?;
1493 if print_finalizer {
1497 self.end() // close the outer-box
1499 self.print_where_clause(&generics.where_clause)?;
1502 self.hardbreak_if_not_bol()?;
1504 for field in struct_def.fields() {
1505 self.hardbreak_if_not_bol()?;
1506 self.maybe_print_comment(field.span.lo())?;
1507 self.print_outer_attributes(&field.attrs)?;
1508 self.print_visibility(&field.vis)?;
1509 self.print_ident(field.ident.unwrap())?;
1510 self.word_nbsp(":")?;
1511 self.print_type(&field.ty)?;
1519 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1521 let generics = ast::Generics::default();
1522 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1523 match v.node.disr_expr {
1526 self.word_space("=")?;
1533 pub fn print_method_sig(&mut self,
1536 vis: &ast::Visibility)
1538 self.print_fn(&m.decl,
1547 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1549 self.ann.pre(self, NodeSubItem(ti.id))?;
1550 self.hardbreak_if_not_bol()?;
1551 self.maybe_print_comment(ti.span.lo())?;
1552 self.print_outer_attributes(&ti.attrs)?;
1554 ast::TraitItemKind::Const(ref ty, ref default) => {
1555 self.print_associated_const(ti.ident, ty,
1556 default.as_ref().map(|expr| &**expr),
1557 &ast::Visibility::Inherited)?;
1559 ast::TraitItemKind::Method(ref sig, ref body) => {
1563 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1564 if let Some(ref body) = *body {
1566 self.print_block_with_attrs(body, &ti.attrs)?;
1571 ast::TraitItemKind::Type(ref bounds, ref default) => {
1572 self.print_associated_type(ti.ident, Some(bounds),
1573 default.as_ref().map(|ty| &**ty))?;
1575 ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1576 // code copied from ItemKind::Mac:
1577 self.print_path(&node.path, false, 0, false)?;
1579 self.cbox(INDENT_UNIT)?;
1581 self.print_tts(node.stream())?;
1587 self.ann.post(self, NodeSubItem(ti.id))
1590 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1591 self.ann.pre(self, NodeSubItem(ii.id))?;
1592 self.hardbreak_if_not_bol()?;
1593 self.maybe_print_comment(ii.span.lo())?;
1594 self.print_outer_attributes(&ii.attrs)?;
1595 self.print_defaultness(ii.defaultness)?;
1597 ast::ImplItemKind::Const(ref ty, ref expr) => {
1598 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1600 ast::ImplItemKind::Method(ref sig, ref body) => {
1602 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1604 self.print_block_with_attrs(body, &ii.attrs)?;
1606 ast::ImplItemKind::Type(ref ty) => {
1607 self.print_associated_type(ii.ident, None, Some(ty))?;
1609 ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1610 // code copied from ItemKind::Mac:
1611 self.print_path(&node.path, false, 0, false)?;
1613 self.cbox(INDENT_UNIT)?;
1615 self.print_tts(node.stream())?;
1621 self.ann.post(self, NodeSubItem(ii.id))
1624 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1625 self.maybe_print_comment(st.span.lo())?;
1627 ast::StmtKind::Local(ref loc) => {
1628 self.print_outer_attributes(&loc.attrs)?;
1629 self.space_if_not_bol()?;
1630 self.ibox(INDENT_UNIT)?;
1631 self.word_nbsp("let")?;
1633 self.ibox(INDENT_UNIT)?;
1634 self.print_local_decl(loc)?;
1636 if let Some(ref init) = loc.init {
1638 self.word_space("=")?;
1639 self.print_expr(init)?;
1644 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1645 ast::StmtKind::Expr(ref expr) => {
1646 self.space_if_not_bol()?;
1647 self.print_expr_outer_attr_style(expr, false)?;
1648 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1652 ast::StmtKind::Semi(ref expr) => {
1653 self.space_if_not_bol()?;
1654 self.print_expr_outer_attr_style(expr, false)?;
1657 ast::StmtKind::Mac(ref mac) => {
1658 let (ref mac, style, ref attrs) = **mac;
1659 self.space_if_not_bol()?;
1660 self.print_outer_attributes(attrs)?;
1661 let delim = match style {
1662 ast::MacStmtStyle::Braces => token::Brace,
1665 self.print_mac(mac, delim)?;
1666 if style == ast::MacStmtStyle::Semicolon {
1671 self.maybe_print_trailing_comment(st.span, None)
1674 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1675 self.print_block_with_attrs(blk, &[])
1678 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1679 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1682 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1683 attrs: &[ast::Attribute])
1685 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1688 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1689 indented: usize) -> io::Result<()> {
1690 self.print_block_maybe_unclosed(blk, indented, &[], false)
1693 pub fn print_block_with_attrs(&mut self,
1695 attrs: &[ast::Attribute]) -> io::Result<()> {
1696 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1699 pub fn print_block_maybe_unclosed(&mut self,
1702 attrs: &[ast::Attribute],
1703 close_box: bool) -> io::Result<()> {
1705 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1706 BlockCheckMode::Default => ()
1708 self.maybe_print_comment(blk.span.lo())?;
1709 self.ann.pre(self, NodeBlock(blk))?;
1712 self.print_inner_attributes(attrs)?;
1714 for (i, st) in blk.stmts.iter().enumerate() {
1716 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1717 self.maybe_print_comment(st.span.lo())?;
1718 self.space_if_not_bol()?;
1719 self.print_expr_outer_attr_style(expr, false)?;
1720 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1722 _ => self.print_stmt(st)?,
1726 self.bclose_maybe_open(blk.span, indented, close_box)?;
1727 self.ann.post(self, NodeBlock(blk))
1730 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1734 // "another else-if"
1735 ast::ExprKind::If(ref i, ref then, ref e) => {
1736 self.cbox(INDENT_UNIT - 1)?;
1738 self.s.word(" else if ")?;
1739 self.print_expr(i)?;
1741 self.print_block(then)?;
1742 self.print_else(e.as_ref().map(|e| &**e))
1744 // "another else-if-let"
1745 ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1746 self.cbox(INDENT_UNIT - 1)?;
1748 self.s.word(" else if let ")?;
1749 self.print_pat(pat)?;
1751 self.word_space("=")?;
1752 self.print_expr(expr)?;
1754 self.print_block(then)?;
1755 self.print_else(e.as_ref().map(|e| &**e))
1758 ast::ExprKind::Block(ref b) => {
1759 self.cbox(INDENT_UNIT - 1)?;
1761 self.s.word(" else ")?;
1764 // BLEAH, constraints would be great here
1766 panic!("print_if saw if with weird alternative");
1774 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1775 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1777 self.print_expr(test)?;
1779 self.print_block(blk)?;
1780 self.print_else(elseopt)
1783 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1784 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1785 self.head("if let")?;
1786 self.print_pat(pat)?;
1788 self.word_space("=")?;
1789 self.print_expr(expr)?;
1791 self.print_block(blk)?;
1792 self.print_else(elseopt)
1795 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1797 self.print_path(&m.node.path, false, 0, false)?;
1800 token::Paren => self.popen()?,
1801 token::Bracket => self.s.word("[")?,
1806 token::NoDelim => {}
1808 self.print_tts(m.node.stream())?;
1810 token::Paren => self.pclose(),
1811 token::Bracket => self.s.word("]"),
1812 token::Brace => self.bclose(m.span),
1813 token::NoDelim => Ok(()),
1818 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1820 self.commasep_exprs(Inconsistent, args)?;
1824 pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1825 binop: ast::BinOp) -> bool {
1826 match sub_expr.node {
1827 ast::ExprKind::Binary(ref sub_op, _, _) => {
1828 AssocOp::from_ast_binop(sub_op.node).precedence() <
1829 AssocOp::from_ast_binop(binop.node).precedence()
1835 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1836 let needs_par = needs_parentheses(expr);
1840 self.print_expr(expr)?;
1847 fn print_expr_in_place(&mut self,
1849 expr: &ast::Expr) -> io::Result<()> {
1850 self.print_expr_maybe_paren(place)?;
1852 self.word_space("<-")?;
1853 self.print_expr_maybe_paren(expr)
1856 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1857 attrs: &[Attribute]) -> io::Result<()> {
1858 self.ibox(INDENT_UNIT)?;
1860 self.print_inner_attributes_inline(attrs)?;
1861 self.commasep_exprs(Inconsistent, &exprs[..])?;
1866 fn print_expr_repeat(&mut self,
1867 element: &ast::Expr,
1869 attrs: &[Attribute]) -> io::Result<()> {
1870 self.ibox(INDENT_UNIT)?;
1872 self.print_inner_attributes_inline(attrs)?;
1873 self.print_expr(element)?;
1874 self.word_space(";")?;
1875 self.print_expr(count)?;
1880 fn print_expr_struct(&mut self,
1882 fields: &[ast::Field],
1883 wth: &Option<P<ast::Expr>>,
1884 attrs: &[Attribute]) -> io::Result<()> {
1885 self.print_path(path, true, 0, false)?;
1887 self.print_inner_attributes_inline(attrs)?;
1892 s.ibox(INDENT_UNIT)?;
1893 if !field.is_shorthand {
1894 s.print_ident(field.ident.node)?;
1897 s.print_expr(&field.expr)?;
1903 self.ibox(INDENT_UNIT)?;
1904 if !fields.is_empty() {
1909 self.print_expr(expr)?;
1912 _ => if !fields.is_empty() {
1920 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1921 attrs: &[Attribute]) -> io::Result<()> {
1923 self.print_inner_attributes_inline(attrs)?;
1924 self.commasep_exprs(Inconsistent, &exprs[..])?;
1925 if exprs.len() == 1 {
1931 fn print_expr_call(&mut self,
1933 args: &[P<ast::Expr>]) -> io::Result<()> {
1934 self.print_expr_maybe_paren(func)?;
1935 self.print_call_post(args)
1938 fn print_expr_method_call(&mut self,
1939 segment: &ast::PathSegment,
1940 args: &[P<ast::Expr>]) -> io::Result<()> {
1941 let base_args = &args[1..];
1942 self.print_expr(&args[0])?;
1944 self.print_ident(segment.identifier)?;
1945 if let Some(ref parameters) = segment.parameters {
1946 self.print_path_parameters(parameters, true)?;
1948 self.print_call_post(base_args)
1951 fn print_expr_binary(&mut self,
1954 rhs: &ast::Expr) -> io::Result<()> {
1955 if self.check_expr_bin_needs_paren(lhs, op) {
1956 self.print_expr_maybe_paren(lhs)?;
1958 self.print_expr(lhs)?;
1961 self.word_space(op.node.to_string())?;
1962 if self.check_expr_bin_needs_paren(rhs, op) {
1963 self.print_expr_maybe_paren(rhs)
1965 self.print_expr(rhs)
1969 fn print_expr_unary(&mut self,
1971 expr: &ast::Expr) -> io::Result<()> {
1972 self.s.word(ast::UnOp::to_string(op))?;
1973 self.print_expr_maybe_paren(expr)
1976 fn print_expr_addr_of(&mut self,
1977 mutability: ast::Mutability,
1978 expr: &ast::Expr) -> io::Result<()> {
1980 self.print_mutability(mutability)?;
1981 self.print_expr_maybe_paren(expr)
1984 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1985 self.print_expr_outer_attr_style(expr, true)
1988 fn print_expr_outer_attr_style(&mut self,
1990 is_inline: bool) -> io::Result<()> {
1991 self.maybe_print_comment(expr.span.lo())?;
1993 let attrs = &expr.attrs;
1995 self.print_outer_attributes_inline(attrs)?;
1997 self.print_outer_attributes(attrs)?;
2000 self.ibox(INDENT_UNIT)?;
2001 self.ann.pre(self, NodeExpr(expr))?;
2003 ast::ExprKind::Box(ref expr) => {
2004 self.word_space("box")?;
2005 self.print_expr(expr)?;
2007 ast::ExprKind::InPlace(ref place, ref expr) => {
2008 self.print_expr_in_place(place, expr)?;
2010 ast::ExprKind::Array(ref exprs) => {
2011 self.print_expr_vec(&exprs[..], attrs)?;
2013 ast::ExprKind::Repeat(ref element, ref count) => {
2014 self.print_expr_repeat(element, count, attrs)?;
2016 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2017 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2019 ast::ExprKind::Tup(ref exprs) => {
2020 self.print_expr_tup(&exprs[..], attrs)?;
2022 ast::ExprKind::Call(ref func, ref args) => {
2023 self.print_expr_call(func, &args[..])?;
2025 ast::ExprKind::MethodCall(ref segment, ref args) => {
2026 self.print_expr_method_call(segment, &args[..])?;
2028 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2029 self.print_expr_binary(op, lhs, rhs)?;
2031 ast::ExprKind::Unary(op, ref expr) => {
2032 self.print_expr_unary(op, expr)?;
2034 ast::ExprKind::AddrOf(m, ref expr) => {
2035 self.print_expr_addr_of(m, expr)?;
2037 ast::ExprKind::Lit(ref lit) => {
2038 self.print_literal(lit)?;
2040 ast::ExprKind::Cast(ref expr, ref ty) => {
2041 if let ast::ExprKind::Cast(..) = expr.node {
2042 self.print_expr(expr)?;
2044 self.print_expr_maybe_paren(expr)?;
2047 self.word_space("as")?;
2048 self.print_type(ty)?;
2050 ast::ExprKind::Type(ref expr, ref ty) => {
2051 self.print_expr(expr)?;
2052 self.word_space(":")?;
2053 self.print_type(ty)?;
2055 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2056 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2058 ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2059 self.print_if_let(pat, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2061 ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2062 if let Some(ident) = opt_ident {
2063 self.print_ident(ident.node)?;
2064 self.word_space(":")?;
2066 self.head("while")?;
2067 self.print_expr(test)?;
2069 self.print_block_with_attrs(blk, attrs)?;
2071 ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2072 if let Some(ident) = opt_ident {
2073 self.print_ident(ident.node)?;
2074 self.word_space(":")?;
2076 self.head("while let")?;
2077 self.print_pat(pat)?;
2079 self.word_space("=")?;
2080 self.print_expr(expr)?;
2082 self.print_block_with_attrs(blk, attrs)?;
2084 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2085 if let Some(ident) = opt_ident {
2086 self.print_ident(ident.node)?;
2087 self.word_space(":")?;
2090 self.print_pat(pat)?;
2092 self.word_space("in")?;
2093 self.print_expr(iter)?;
2095 self.print_block_with_attrs(blk, attrs)?;
2097 ast::ExprKind::Loop(ref blk, opt_ident) => {
2098 if let Some(ident) = opt_ident {
2099 self.print_ident(ident.node)?;
2100 self.word_space(":")?;
2104 self.print_block_with_attrs(blk, attrs)?;
2106 ast::ExprKind::Match(ref expr, ref arms) => {
2107 self.cbox(INDENT_UNIT)?;
2109 self.word_nbsp("match")?;
2110 self.print_expr(expr)?;
2113 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2115 self.print_arm(arm)?;
2117 self.bclose_(expr.span, INDENT_UNIT)?;
2119 ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2120 self.print_capture_clause(capture_clause)?;
2122 self.print_fn_block_args(decl)?;
2124 self.print_expr(body)?;
2125 self.end()?; // need to close a box
2127 // a box will be closed by print_expr, but we didn't want an overall
2128 // wrapper so we closed the corresponding opening. so create an
2129 // empty box to satisfy the close.
2132 ast::ExprKind::Block(ref blk) => {
2133 // containing cbox, will be closed by print-block at }
2134 self.cbox(INDENT_UNIT)?;
2135 // head-box, will be closed by print-block after {
2137 self.print_block_with_attrs(blk, attrs)?;
2139 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2140 self.print_expr(lhs)?;
2142 self.word_space("=")?;
2143 self.print_expr(rhs)?;
2145 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2146 self.print_expr(lhs)?;
2148 self.s.word(op.node.to_string())?;
2149 self.word_space("=")?;
2150 self.print_expr(rhs)?;
2152 ast::ExprKind::Field(ref expr, id) => {
2153 self.print_expr(expr)?;
2155 self.print_ident(id.node)?;
2157 ast::ExprKind::TupField(ref expr, id) => {
2158 self.print_expr(expr)?;
2160 self.print_usize(id.node)?;
2162 ast::ExprKind::Index(ref expr, ref index) => {
2163 self.print_expr(expr)?;
2165 self.print_expr(index)?;
2168 ast::ExprKind::Range(ref start, ref end, limits) => {
2169 if let Some(ref e) = *start {
2170 self.print_expr(e)?;
2172 if limits == ast::RangeLimits::HalfOpen {
2175 self.s.word("...")?;
2177 if let Some(ref e) = *end {
2178 self.print_expr(e)?;
2181 ast::ExprKind::Path(None, ref path) => {
2182 self.print_path(path, true, 0, false)?
2184 ast::ExprKind::Path(Some(ref qself), ref path) => {
2185 self.print_qpath(path, qself, true)?
2187 ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2188 self.s.word("break")?;
2190 if let Some(ident) = opt_ident {
2191 self.print_ident(ident.node)?;
2194 if let Some(ref expr) = *opt_expr {
2195 self.print_expr(expr)?;
2199 ast::ExprKind::Continue(opt_ident) => {
2200 self.s.word("continue")?;
2202 if let Some(ident) = opt_ident {
2203 self.print_ident(ident.node)?;
2207 ast::ExprKind::Ret(ref result) => {
2208 self.s.word("return")?;
2209 if let Some(ref expr) = *result {
2211 self.print_expr(expr)?;
2214 ast::ExprKind::InlineAsm(ref a) => {
2215 self.s.word("asm!")?;
2217 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2218 self.word_space(":")?;
2220 self.commasep(Inconsistent, &a.outputs, |s, out| {
2221 let constraint = out.constraint.as_str();
2222 let mut ch = constraint.chars();
2224 Some('=') if out.is_rw => {
2225 s.print_string(&format!("+{}", ch.as_str()),
2226 ast::StrStyle::Cooked)?
2228 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2231 s.print_expr(&out.expr)?;
2236 self.word_space(":")?;
2238 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2239 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2246 self.word_space(":")?;
2248 self.commasep(Inconsistent, &a.clobbers,
2250 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2254 let mut options = vec![];
2256 options.push("volatile");
2259 options.push("alignstack");
2261 if a.dialect == ast::AsmDialect::Intel {
2262 options.push("intel");
2265 if !options.is_empty() {
2267 self.word_space(":")?;
2268 self.commasep(Inconsistent, &options,
2270 s.print_string(co, ast::StrStyle::Cooked)?;
2277 ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2278 ast::ExprKind::Paren(ref e) => {
2280 self.print_inner_attributes_inline(attrs)?;
2281 self.print_expr(e)?;
2284 ast::ExprKind::Yield(ref e) => {
2285 self.s.word("yield")?;
2289 self.print_expr(&expr)?;
2294 ast::ExprKind::Try(ref e) => {
2295 self.print_expr(e)?;
2298 ast::ExprKind::Catch(ref blk) => {
2299 self.head("do catch")?;
2301 self.print_block_with_attrs(blk, attrs)?
2304 self.ann.post(self, NodeExpr(expr))?;
2308 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2309 self.print_pat(&loc.pat)?;
2310 if let Some(ref ty) = loc.ty {
2311 self.word_space(":")?;
2312 self.print_type(ty)?;
2317 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2318 self.s.word(&ident.name.as_str())?;
2319 self.ann.post(self, NodeIdent(&ident))
2322 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2323 self.s.word(&i.to_string())
2326 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2327 self.s.word(&name.as_str())?;
2328 self.ann.post(self, NodeName(&name))
2331 pub fn print_for_decl(&mut self, loc: &ast::Local,
2332 coll: &ast::Expr) -> io::Result<()> {
2333 self.print_local_decl(loc)?;
2335 self.word_space("in")?;
2336 self.print_expr(coll)
2339 fn print_path(&mut self,
2341 colons_before_params: bool,
2343 defaults_to_global: bool)
2346 self.maybe_print_comment(path.span.lo())?;
2348 let mut segments = path.segments[..path.segments.len()-depth].iter();
2349 if defaults_to_global && path.is_global() {
2352 for (i, segment) in segments.enumerate() {
2356 self.print_path_segment(segment, colons_before_params)?;
2362 fn print_path_segment(&mut self,
2363 segment: &ast::PathSegment,
2364 colons_before_params: bool)
2367 if segment.identifier.name != keywords::CrateRoot.name() &&
2368 segment.identifier.name != keywords::DollarCrate.name() {
2369 self.print_ident(segment.identifier)?;
2370 if let Some(ref parameters) = segment.parameters {
2371 self.print_path_parameters(parameters, colons_before_params)?;
2377 fn print_qpath(&mut self,
2380 colons_before_params: bool)
2384 self.print_type(&qself.ty)?;
2385 if qself.position > 0 {
2387 self.word_space("as")?;
2388 let depth = path.segments.len() - qself.position;
2389 self.print_path(path, false, depth, false)?;
2393 let item_segment = path.segments.last().unwrap();
2394 self.print_ident(item_segment.identifier)?;
2395 match item_segment.parameters {
2396 Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2401 fn print_path_parameters(&mut self,
2402 parameters: &ast::PathParameters,
2403 colons_before_params: bool)
2406 if colons_before_params {
2411 ast::PathParameters::AngleBracketed(ref data) => {
2414 let mut comma = false;
2415 for lifetime in &data.lifetimes {
2417 self.word_space(",")?
2419 self.print_lifetime(lifetime)?;
2423 if !data.types.is_empty() {
2425 self.word_space(",")?
2430 |s, ty| s.print_type(ty))?;
2434 for binding in data.bindings.iter() {
2436 self.word_space(",")?
2438 self.print_ident(binding.ident)?;
2440 self.word_space("=")?;
2441 self.print_type(&binding.ty)?;
2448 ast::PathParameters::Parenthesized(ref data) => {
2453 |s, ty| s.print_type(ty))?;
2456 if let Some(ref ty) = data.output {
2457 self.space_if_not_bol()?;
2458 self.word_space("->")?;
2459 self.print_type(ty)?;
2467 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2468 self.maybe_print_comment(pat.span.lo())?;
2469 self.ann.pre(self, NodePat(pat))?;
2470 /* Pat isn't normalized, but the beauty of it
2471 is that it doesn't matter */
2473 PatKind::Wild => self.s.word("_")?,
2474 PatKind::Ident(binding_mode, ref path1, ref sub) => {
2475 match binding_mode {
2476 ast::BindingMode::ByRef(mutbl) => {
2477 self.word_nbsp("ref")?;
2478 self.print_mutability(mutbl)?;
2480 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2481 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2482 self.word_nbsp("mut")?;
2485 self.print_ident(path1.node)?;
2486 if let Some(ref p) = *sub {
2491 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2492 self.print_path(path, true, 0, false)?;
2494 if let Some(ddpos) = ddpos {
2495 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2497 self.word_space(",")?;
2500 if ddpos != elts.len() {
2502 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2505 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2509 PatKind::Path(None, ref path) => {
2510 self.print_path(path, true, 0, false)?;
2512 PatKind::Path(Some(ref qself), ref path) => {
2513 self.print_qpath(path, qself, false)?;
2515 PatKind::Struct(ref path, ref fields, etc) => {
2516 self.print_path(path, true, 0, false)?;
2518 self.word_space("{")?;
2520 Consistent, &fields[..],
2522 s.cbox(INDENT_UNIT)?;
2523 if !f.node.is_shorthand {
2524 s.print_ident(f.node.ident)?;
2527 s.print_pat(&f.node.pat)?;
2530 |f| f.node.pat.span)?;
2532 if !fields.is_empty() { self.word_space(",")?; }
2538 PatKind::Tuple(ref elts, ddpos) => {
2540 if let Some(ddpos) = ddpos {
2541 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2543 self.word_space(",")?;
2546 if ddpos != elts.len() {
2548 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2551 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2552 if elts.len() == 1 {
2558 PatKind::Box(ref inner) => {
2559 self.s.word("box ")?;
2560 self.print_pat(inner)?;
2562 PatKind::Ref(ref inner, mutbl) => {
2564 if mutbl == ast::Mutability::Mutable {
2565 self.s.word("mut ")?;
2567 self.print_pat(inner)?;
2569 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2570 PatKind::Range(ref begin, ref end, ref end_kind) => {
2571 self.print_expr(begin)?;
2574 RangeEnd::Included => self.s.word("...")?,
2575 RangeEnd::Excluded => self.s.word("..")?,
2577 self.print_expr(end)?;
2579 PatKind::Slice(ref before, ref slice, ref after) => {
2581 self.commasep(Inconsistent,
2583 |s, p| s.print_pat(p))?;
2584 if let Some(ref p) = *slice {
2585 if !before.is_empty() { self.word_space(",")?; }
2586 if p.node != PatKind::Wild {
2590 if !after.is_empty() { self.word_space(",")?; }
2592 self.commasep(Inconsistent,
2594 |s, p| s.print_pat(p))?;
2597 PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2599 self.ann.post(self, NodePat(pat))
2602 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2603 // I have no idea why this check is necessary, but here it
2605 if arm.attrs.is_empty() {
2608 self.cbox(INDENT_UNIT)?;
2610 self.maybe_print_comment(arm.pats[0].span.lo())?;
2611 self.print_outer_attributes(&arm.attrs)?;
2612 let mut first = true;
2613 for p in &arm.pats {
2618 self.word_space("|")?;
2623 if let Some(ref e) = arm.guard {
2624 self.word_space("if")?;
2625 self.print_expr(e)?;
2628 self.word_space("=>")?;
2630 match arm.body.node {
2631 ast::ExprKind::Block(ref blk) => {
2632 // the block will close the pattern's ibox
2633 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2635 // If it is a user-provided unsafe block, print a comma after it
2636 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2641 self.end()?; // close the ibox for the pattern
2642 self.print_expr(&arm.body)?;
2646 self.end() // close enclosing cbox
2649 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2650 match explicit_self.node {
2651 SelfKind::Value(m) => {
2652 self.print_mutability(m)?;
2655 SelfKind::Region(ref lt, m) => {
2657 self.print_opt_lifetime(lt)?;
2658 self.print_mutability(m)?;
2661 SelfKind::Explicit(ref typ, m) => {
2662 self.print_mutability(m)?;
2663 self.s.word("self")?;
2664 self.word_space(":")?;
2665 self.print_type(typ)
2670 pub fn print_fn(&mut self,
2672 unsafety: ast::Unsafety,
2673 constness: ast::Constness,
2675 name: Option<ast::Ident>,
2676 generics: &ast::Generics,
2677 vis: &ast::Visibility) -> io::Result<()> {
2678 self.print_fn_header_info(unsafety, constness, abi, vis)?;
2680 if let Some(name) = name {
2682 self.print_ident(name)?;
2684 self.print_generics(generics)?;
2685 self.print_fn_args_and_ret(decl)?;
2686 self.print_where_clause(&generics.where_clause)
2689 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2692 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2694 self.s.word(", ...")?;
2698 self.print_fn_output(decl)
2701 pub fn print_fn_block_args(
2706 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2709 if let ast::FunctionRetTy::Default(..) = decl.output {
2713 self.space_if_not_bol()?;
2714 self.word_space("->")?;
2716 ast::FunctionRetTy::Ty(ref ty) => {
2717 self.print_type(ty)?;
2718 self.maybe_print_comment(ty.span.lo())
2720 ast::FunctionRetTy::Default(..) => unreachable!(),
2724 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2726 match capture_clause {
2727 ast::CaptureBy::Value => self.word_space("move"),
2728 ast::CaptureBy::Ref => Ok(()),
2732 pub fn print_bounds(&mut self,
2734 bounds: &[ast::TyParamBound])
2736 if !bounds.is_empty() {
2737 self.s.word(prefix)?;
2738 let mut first = true;
2739 for bound in bounds {
2744 self.word_space("+")?;
2748 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2749 self.print_poly_trait_ref(tref)
2751 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2753 self.print_poly_trait_ref(tref)
2755 RegionTyParamBound(ref lt) => {
2756 self.print_lifetime(lt)
2766 pub fn print_lifetime(&mut self,
2767 lifetime: &ast::Lifetime)
2770 self.print_name(lifetime.ident.name)
2773 pub fn print_lifetime_bounds(&mut self,
2774 lifetime: &ast::Lifetime,
2775 bounds: &[ast::Lifetime])
2778 self.print_lifetime(lifetime)?;
2779 if !bounds.is_empty() {
2781 for (i, bound) in bounds.iter().enumerate() {
2783 self.s.word(" + ")?;
2785 self.print_lifetime(bound)?;
2791 pub fn print_generics(&mut self,
2792 generics: &ast::Generics)
2795 let total = generics.lifetimes.len() + generics.ty_params.len();
2802 let mut ints = Vec::new();
2807 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2808 if idx < generics.lifetimes.len() {
2809 let lifetime_def = &generics.lifetimes[idx];
2810 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2811 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2813 let idx = idx - generics.lifetimes.len();
2814 let param = &generics.ty_params[idx];
2815 s.print_ty_param(param)
2823 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2824 self.print_outer_attributes_inline(¶m.attrs)?;
2825 self.print_ident(param.ident)?;
2826 self.print_bounds(":", ¶m.bounds)?;
2827 match param.default {
2828 Some(ref default) => {
2830 self.word_space("=")?;
2831 self.print_type(default)
2837 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2839 if where_clause.predicates.is_empty() {
2844 self.word_space("where")?;
2846 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2848 self.word_space(",")?;
2852 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2856 self.print_formal_lifetime_list(bound_lifetimes)?;
2857 self.print_type(bounded_ty)?;
2858 self.print_bounds(":", bounds)?;
2860 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2863 self.print_lifetime_bounds(lifetime, bounds)?;
2865 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2868 self.print_type(lhs_ty)?;
2870 self.word_space("=")?;
2871 self.print_type(rhs_ty)?;
2879 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2881 ast::ViewPathSimple(ident, ref path) => {
2882 self.print_path(path, false, 0, true)?;
2884 if path.segments.last().unwrap().identifier.name !=
2887 self.word_space("as")?;
2888 self.print_ident(ident)?;
2894 ast::ViewPathGlob(ref path) => {
2895 self.print_path(path, false, 0, true)?;
2899 ast::ViewPathList(ref path, ref idents) => {
2900 if path.segments.is_empty() {
2903 self.print_path(path, false, 0, true)?;
2904 self.s.word("::{")?;
2906 self.commasep(Inconsistent, &idents[..], |s, w| {
2907 s.print_ident(w.node.name)?;
2908 if let Some(ident) = w.node.rename {
2910 s.word_space("as")?;
2911 s.print_ident(ident)?;
2920 pub fn print_mutability(&mut self,
2921 mutbl: ast::Mutability) -> io::Result<()> {
2923 ast::Mutability::Mutable => self.word_nbsp("mut"),
2924 ast::Mutability::Immutable => Ok(()),
2928 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2929 self.print_mutability(mt.mutbl)?;
2930 self.print_type(&mt.ty)
2933 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2934 self.ibox(INDENT_UNIT)?;
2935 match input.ty.node {
2936 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2938 if let Some(eself) = input.to_self() {
2939 self.print_explicit_self(&eself)?;
2941 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2942 ident.node.name == keywords::Invalid.name()
2947 self.print_pat(&input.pat)?;
2951 self.print_type(&input.ty)?;
2958 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2959 if let ast::FunctionRetTy::Default(..) = decl.output {
2963 self.space_if_not_bol()?;
2964 self.ibox(INDENT_UNIT)?;
2965 self.word_space("->")?;
2967 ast::FunctionRetTy::Default(..) => unreachable!(),
2968 ast::FunctionRetTy::Ty(ref ty) =>
2969 self.print_type(ty)?
2974 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2979 pub fn print_ty_fn(&mut self,
2981 unsafety: ast::Unsafety,
2983 name: Option<ast::Ident>,
2984 generics: &ast::Generics)
2986 self.ibox(INDENT_UNIT)?;
2987 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2988 self.s.word("for")?;
2989 self.print_generics(generics)?;
2991 let generics = ast::Generics {
2992 lifetimes: Vec::new(),
2993 ty_params: Vec::new(),
2994 where_clause: ast::WhereClause {
2995 id: ast::DUMMY_NODE_ID,
2996 predicates: Vec::new(),
2997 span: syntax_pos::DUMMY_SP,
2999 span: syntax_pos::DUMMY_SP,
3003 ast::Constness::NotConst,
3007 &ast::Visibility::Inherited)?;
3011 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3012 next_pos: Option<BytePos>)
3014 let cm = match self.cm {
3018 if let Some(ref cmnt) = self.next_comment() {
3019 if cmnt.style != comments::Trailing { return Ok(()) }
3020 let span_line = cm.lookup_char_pos(span.hi());
3021 let comment_line = cm.lookup_char_pos(cmnt.pos);
3022 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3023 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3024 self.print_comment(cmnt)?;
3030 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3031 // If there aren't any remaining comments, then we need to manually
3032 // make sure there is a line break at the end.
3033 if self.next_comment().is_none() {
3034 self.s.hardbreak()?;
3036 while let Some(ref cmnt) = self.next_comment() {
3037 self.print_comment(cmnt)?;
3042 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3043 opt_abi: Option<Abi>)
3046 Some(Abi::Rust) => Ok(()),
3048 self.word_nbsp("extern")?;
3049 self.word_nbsp(&abi.to_string())
3055 pub fn print_extern_opt_abi(&mut self,
3056 opt_abi: Option<Abi>) -> io::Result<()> {
3059 self.word_nbsp("extern")?;
3060 self.word_nbsp(&abi.to_string())
3066 pub fn print_fn_header_info(&mut self,
3067 unsafety: ast::Unsafety,
3068 constness: ast::Constness,
3070 vis: &ast::Visibility) -> io::Result<()> {
3071 self.s.word(&visibility_qualified(vis, ""))?;
3074 ast::Constness::NotConst => {}
3075 ast::Constness::Const => self.word_nbsp("const")?
3078 self.print_unsafety(unsafety)?;
3080 if abi != Abi::Rust {
3081 self.word_nbsp("extern")?;
3082 self.word_nbsp(&abi.to_string())?;
3088 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3090 ast::Unsafety::Normal => Ok(()),
3091 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3096 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3107 fn test_fun_to_string() {
3108 let abba_ident = ast::Ident::from_str("abba");
3110 let decl = ast::FnDecl {
3112 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3115 let generics = ast::Generics::default();
3116 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3117 ast::Constness::NotConst,
3118 abba_ident, &generics),
3123 fn test_variant_to_string() {
3124 let ident = ast::Ident::from_str("principal_skinner");
3126 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3129 // making this up as I go.... ?
3130 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3134 let varstr = variant_to_string(&var);
3135 assert_eq!(varstr, "principal_skinner");