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::*;
13 use rustc_target::spec::abi::{self, Abi};
14 use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
15 use ast::{SelfKind, GenericBound, TraitBoundModifier};
16 use ast::{Attribute, MacDelimiter, GenericArg};
17 use util::parser::{self, AssocOp, Fixity};
19 use codemap::{self, CodeMap, Spanned};
20 use syntax_pos::{self, BytePos};
21 use syntax_pos::hygiene::{Mark, SyntaxContext};
22 use parse::token::{self, BinOpToken, Token};
23 use parse::lexer::comments;
24 use parse::{self, ParseSess};
25 use print::pp::{self, Breaks};
26 use print::pp::Breaks::{Consistent, Inconsistent};
30 use syntax_pos::{DUMMY_SP, FileName};
31 use tokenstream::{self, TokenStream, TokenTree};
34 use std::io::{self, Write, Read};
35 use std::iter::Peekable;
38 pub enum AnnNode<'a> {
39 NodeIdent(&'a ast::Ident),
40 NodeName(&'a ast::Name),
41 NodeBlock(&'a ast::Block),
42 NodeItem(&'a ast::Item),
43 NodeSubItem(ast::NodeId),
44 NodeExpr(&'a ast::Expr),
45 NodePat(&'a ast::Pat),
49 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
50 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
53 #[derive(Copy, Clone)]
56 impl PpAnn for NoAnn {}
58 pub struct State<'a> {
59 pub s: pp::Printer<'a>,
60 cm: Option<&'a CodeMap>,
61 comments: Option<Vec<comments::Comment> >,
62 literals: Peekable<vec::IntoIter<comments::Literal>>,
64 boxes: Vec<pp::Breaks>,
65 ann: &'a (dyn PpAnn+'a),
68 fn rust_printer<'a>(writer: Box<dyn Write+'a>, ann: &'a dyn PpAnn) -> State<'a> {
70 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
73 literals: vec![].into_iter().peekable(),
80 pub const INDENT_UNIT: usize = 4;
82 pub const DEFAULT_COLUMNS: usize = 78;
84 /// Requires you to pass an input filename and reader so that
85 /// it can scan the input text for comments and literals to
87 pub fn print_crate<'a>(cm: &'a CodeMap,
92 out: Box<dyn Write+'a>,
94 is_expanded: bool) -> io::Result<()> {
95 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
97 if is_expanded && std_inject::injected_crate_name().is_some() {
98 // We need to print `#![no_std]` (and its feature gate) so that
99 // compiling pretty-printed source won't inject libstd again.
100 // However we don't want these attributes in the AST because
101 // of the feature gate, so we fake them up here.
103 // #![feature(prelude_import)]
104 let pi_nested = attr::mk_nested_word_item(ast::Ident::from_str("prelude_import"));
105 let list = attr::mk_list_item(DUMMY_SP, ast::Ident::from_str("feature"), vec![pi_nested]);
106 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
107 s.print_attribute(&fake_attr)?;
110 let no_std_meta = attr::mk_word_item(ast::Ident::from_str("no_std"));
111 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
112 s.print_attribute(&fake_attr)?;
115 s.print_mod(&krate.module, &krate.attrs)?;
116 s.print_remaining_comments()?;
121 pub fn new_from_input(cm: &'a CodeMap,
124 input: &mut dyn Read,
125 out: Box<dyn Write+'a>,
127 is_expanded: bool) -> State<'a> {
128 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
135 // If the code is post expansion, don't use the table of
136 // literals, since it doesn't correspond with the literals
137 // in the AST anymore.
138 if is_expanded { None } else { Some(lits) })
141 pub fn new(cm: &'a CodeMap,
142 out: Box<dyn Write+'a>,
144 comments: Option<Vec<comments::Comment>>,
145 literals: Option<Vec<comments::Literal>>) -> State<'a> {
147 s: pp::mk_printer(out, DEFAULT_COLUMNS),
150 literals: literals.unwrap_or_default().into_iter().peekable(),
158 pub fn to_string<F>(f: F) -> String where
159 F: FnOnce(&mut State) -> io::Result<()>,
161 let mut wr = Vec::new();
164 let mut printer = rust_printer(Box::new(&mut wr), &ann);
165 f(&mut printer).unwrap();
166 printer.s.eof().unwrap();
168 String::from_utf8(wr).unwrap()
171 fn binop_to_string(op: BinOpToken) -> &'static str {
177 token::Percent => "%",
186 pub fn token_to_string(tok: &Token) -> String {
188 token::Eq => "=".to_string(),
189 token::Lt => "<".to_string(),
190 token::Le => "<=".to_string(),
191 token::EqEq => "==".to_string(),
192 token::Ne => "!=".to_string(),
193 token::Ge => ">=".to_string(),
194 token::Gt => ">".to_string(),
195 token::Not => "!".to_string(),
196 token::Tilde => "~".to_string(),
197 token::OrOr => "||".to_string(),
198 token::AndAnd => "&&".to_string(),
199 token::BinOp(op) => binop_to_string(op).to_string(),
200 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
202 /* Structural symbols */
203 token::At => "@".to_string(),
204 token::Dot => ".".to_string(),
205 token::DotDot => "..".to_string(),
206 token::DotDotDot => "...".to_string(),
207 token::DotDotEq => "..=".to_string(),
208 token::DotEq => ".=".to_string(),
209 token::Comma => ",".to_string(),
210 token::Semi => ";".to_string(),
211 token::Colon => ":".to_string(),
212 token::ModSep => "::".to_string(),
213 token::RArrow => "->".to_string(),
214 token::LArrow => "<-".to_string(),
215 token::FatArrow => "=>".to_string(),
216 token::OpenDelim(token::Paren) => "(".to_string(),
217 token::CloseDelim(token::Paren) => ")".to_string(),
218 token::OpenDelim(token::Bracket) => "[".to_string(),
219 token::CloseDelim(token::Bracket) => "]".to_string(),
220 token::OpenDelim(token::Brace) => "{".to_string(),
221 token::CloseDelim(token::Brace) => "}".to_string(),
222 token::OpenDelim(token::NoDelim) |
223 token::CloseDelim(token::NoDelim) => " ".to_string(),
224 token::Pound => "#".to_string(),
225 token::Dollar => "$".to_string(),
226 token::Question => "?".to_string(),
227 token::SingleQuote => "'".to_string(),
230 token::Literal(lit, suf) => {
231 let mut out = match lit {
232 token::Byte(b) => format!("b'{}'", b),
233 token::Char(c) => format!("'{}'", c),
235 token::Integer(c) => c.to_string(),
236 token::Str_(s) => format!("\"{}\"", s),
237 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
238 delim="#".repeat(n as usize),
240 token::ByteStr(v) => format!("b\"{}\"", v),
241 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
242 delim="#".repeat(n as usize),
246 if let Some(s) = suf {
247 out.push_str(&s.as_str())
253 /* Name components */
254 token::Ident(s, false) => s.to_string(),
255 token::Ident(s, true) => format!("r#{}", s),
256 token::Lifetime(s) => s.to_string(),
259 token::DocComment(s) => s.to_string(),
260 token::Eof => "<eof>".to_string(),
261 token::Whitespace => " ".to_string(),
262 token::Comment => "/* */".to_string(),
263 token::Shebang(s) => format!("/* shebang: {}*/", s),
265 token::Interpolated(ref nt) => match nt.0 {
266 token::NtExpr(ref e) => expr_to_string(e),
267 token::NtMeta(ref e) => meta_item_to_string(e),
268 token::NtTy(ref e) => ty_to_string(e),
269 token::NtPath(ref e) => path_to_string(e),
270 token::NtItem(ref e) => item_to_string(e),
271 token::NtBlock(ref e) => block_to_string(e),
272 token::NtStmt(ref e) => stmt_to_string(e),
273 token::NtPat(ref e) => pat_to_string(e),
274 token::NtIdent(e, false) => ident_to_string(e),
275 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
276 token::NtLifetime(e) => ident_to_string(e),
277 token::NtLiteral(ref e) => expr_to_string(e),
278 token::NtTT(ref tree) => tt_to_string(tree.clone()),
279 token::NtArm(ref e) => arm_to_string(e),
280 token::NtImplItem(ref e) => impl_item_to_string(e),
281 token::NtTraitItem(ref e) => trait_item_to_string(e),
282 token::NtGenerics(ref e) => generic_params_to_string(&e.params),
283 token::NtWhereClause(ref e) => where_clause_to_string(e),
284 token::NtArg(ref e) => arg_to_string(e),
285 token::NtVis(ref e) => vis_to_string(e),
286 token::NtForeignItem(ref e) => foreign_item_to_string(e),
291 pub fn ty_to_string(ty: &ast::Ty) -> String {
292 to_string(|s| s.print_type(ty))
295 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
296 to_string(|s| s.print_type_bounds("", bounds))
299 pub fn pat_to_string(pat: &ast::Pat) -> String {
300 to_string(|s| s.print_pat(pat))
303 pub fn arm_to_string(arm: &ast::Arm) -> String {
304 to_string(|s| s.print_arm(arm))
307 pub fn expr_to_string(e: &ast::Expr) -> String {
308 to_string(|s| s.print_expr(e))
311 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
312 to_string(|s| s.print_lifetime(*lt))
315 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
316 to_string(|s| s.print_tt(tt))
319 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
320 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
323 pub fn tokens_to_string(tokens: TokenStream) -> String {
324 to_string(|s| s.print_tts(tokens))
327 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
328 to_string(|s| s.print_stmt(stmt))
331 pub fn attr_to_string(attr: &ast::Attribute) -> String {
332 to_string(|s| s.print_attribute(attr))
335 pub fn item_to_string(i: &ast::Item) -> String {
336 to_string(|s| s.print_item(i))
339 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
340 to_string(|s| s.print_impl_item(i))
343 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
344 to_string(|s| s.print_trait_item(i))
347 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
348 to_string(|s| s.print_generic_params(generic_params))
351 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
352 to_string(|s| s.print_where_clause(i))
355 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
356 to_string(|s| s.print_fn_block_args(p))
359 pub fn path_to_string(p: &ast::Path) -> String {
360 to_string(|s| s.print_path(p, false, 0))
363 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
364 to_string(|s| s.print_path_segment(p, false))
367 pub fn ident_to_string(id: ast::Ident) -> String {
368 to_string(|s| s.print_ident(id))
371 pub fn vis_to_string(v: &ast::Visibility) -> String {
372 to_string(|s| s.print_visibility(v))
375 pub fn fun_to_string(decl: &ast::FnDecl,
376 header: ast::FnHeader,
378 generics: &ast::Generics)
382 s.print_fn(decl, header, Some(name),
383 generics, &codemap::dummy_spanned(ast::VisibilityKind::Inherited))?;
384 s.end()?; // Close the head box
385 s.end() // Close the outer box
389 pub fn block_to_string(blk: &ast::Block) -> String {
391 // containing cbox, will be closed by print-block at }
392 s.cbox(INDENT_UNIT)?;
393 // head-ibox, will be closed by print-block after {
399 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
400 to_string(|s| s.print_meta_list_item(li))
403 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
404 to_string(|s| s.print_meta_item(mi))
407 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
408 to_string(|s| s.print_attribute(attr))
411 pub fn lit_to_string(l: &ast::Lit) -> String {
412 to_string(|s| s.print_literal(l))
415 pub fn variant_to_string(var: &ast::Variant) -> String {
416 to_string(|s| s.print_variant(var))
419 pub fn arg_to_string(arg: &ast::Arg) -> String {
420 to_string(|s| s.print_arg(arg, false))
423 pub fn mac_to_string(arg: &ast::Mac) -> String {
424 to_string(|s| s.print_mac(arg))
427 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
428 to_string(|s| s.print_foreign_item(arg))
431 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
432 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
435 pub trait PrintState<'a> {
436 fn writer(&mut self) -> &mut pp::Printer<'a>;
437 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
438 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
439 fn cur_cmnt(&mut self) -> &mut usize;
440 fn cur_lit(&mut self) -> Option<&comments::Literal>;
441 fn bump_lit(&mut self) -> Option<comments::Literal>;
443 fn word_space(&mut self, w: &str) -> io::Result<()> {
444 self.writer().word(w)?;
445 self.writer().space()
448 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
450 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
452 fn is_begin(&mut self) -> bool {
453 match self.writer().last_token() {
454 pp::Token::Begin(_) => true,
459 fn is_end(&mut self) -> bool {
460 match self.writer().last_token() {
461 pp::Token::End => true,
466 // is this the beginning of a line?
467 fn is_bol(&mut self) -> bool {
468 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
471 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
473 self.writer().hardbreak()?
479 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
480 self.boxes().push(b);
481 self.writer().rbox(u, b)
484 fn ibox(&mut self, u: usize) -> io::Result<()> {
485 self.boxes().push(pp::Breaks::Inconsistent);
486 self.writer().ibox(u)
489 fn end(&mut self) -> io::Result<()> {
490 self.boxes().pop().unwrap();
494 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
495 where F: FnMut(&mut Self, &T) -> io::Result<()>,
498 let mut first = true;
500 if first { first = false; } else { self.word_space(",")?; }
506 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
507 while let Some(ltrl) = self.cur_lit().cloned() {
508 if ltrl.pos > pos { break; }
510 // we don't need the value here since we're forced to clone cur_lit
511 // due to lack of NLL.
521 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
522 while let Some(ref cmnt) = self.next_comment() {
524 self.print_comment(cmnt)?;
532 fn print_comment(&mut self,
533 cmnt: &comments::Comment) -> io::Result<()> {
534 let r = match cmnt.style {
536 assert_eq!(cmnt.lines.len(), 1);
537 self.writer().zerobreak()?;
538 self.writer().word(&cmnt.lines[0])?;
539 self.writer().zerobreak()
541 comments::Isolated => {
542 self.hardbreak_if_not_bol()?;
543 for line in &cmnt.lines {
544 // Don't print empty lines because they will end up as trailing
546 if !line.is_empty() {
547 self.writer().word(&line[..])?;
549 self.writer().hardbreak()?;
553 comments::Trailing => {
555 self.writer().word(" ")?;
557 if cmnt.lines.len() == 1 {
558 self.writer().word(&cmnt.lines[0])?;
559 self.writer().hardbreak()
562 for line in &cmnt.lines {
563 if !line.is_empty() {
564 self.writer().word(&line[..])?;
566 self.writer().hardbreak()?;
571 comments::BlankLine => {
572 // We need to do at least one, possibly two hardbreaks.
573 let is_semi = match self.writer().last_token() {
574 pp::Token::String(s, _) => ";" == s,
577 if is_semi || self.is_begin() || self.is_end() {
578 self.writer().hardbreak()?;
580 self.writer().hardbreak()
585 *self.cur_cmnt() = *self.cur_cmnt() + 1;
592 fn next_comment(&mut self) -> Option<comments::Comment> {
593 let cur_cmnt = *self.cur_cmnt();
594 match *self.comments() {
596 if cur_cmnt < cmnts.len() {
597 Some(cmnts[cur_cmnt].clone())
606 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
607 self.maybe_print_comment(lit.span.lo())?;
608 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
609 return self.writer().word(<rl.lit);
612 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
613 ast::LitKind::Byte(byte) => {
614 let mut res = String::from("b'");
615 res.extend(ascii::escape_default(byte).map(|c| c as char));
617 self.writer().word(&res[..])
619 ast::LitKind::Char(ch) => {
620 let mut res = String::from("'");
621 res.extend(ch.escape_default());
623 self.writer().word(&res[..])
625 ast::LitKind::Int(i, t) => {
627 ast::LitIntType::Signed(st) => {
628 self.writer().word(&st.val_to_string(i as i128))
630 ast::LitIntType::Unsigned(ut) => {
631 self.writer().word(&ut.val_to_string(i))
633 ast::LitIntType::Unsuffixed => {
634 self.writer().word(&i.to_string())
638 ast::LitKind::Float(ref f, t) => {
639 self.writer().word(&format!("{}{}", &f, t.ty_to_string()))
641 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()),
642 ast::LitKind::Bool(val) => {
643 if val { self.writer().word("true") } else { self.writer().word("false") }
645 ast::LitKind::ByteStr(ref v) => {
646 let mut escaped: String = String::new();
647 for &ch in v.iter() {
648 escaped.extend(ascii::escape_default(ch)
649 .map(|c| c as char));
651 self.writer().word(&format!("b\"{}\"", escaped))
656 fn print_string(&mut self, st: &str,
657 style: ast::StrStyle) -> io::Result<()> {
658 let st = match style {
659 ast::StrStyle::Cooked => {
660 (format!("\"{}\"", st.escape_debug()))
662 ast::StrStyle::Raw(n) => {
663 (format!("r{delim}\"{string}\"{delim}",
664 delim="#".repeat(n as usize),
668 self.writer().word(&st[..])
671 fn print_inner_attributes(&mut self,
672 attrs: &[ast::Attribute]) -> io::Result<()> {
673 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
676 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
677 attrs: &[ast::Attribute])
679 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
682 fn print_outer_attributes(&mut self,
683 attrs: &[ast::Attribute]) -> io::Result<()> {
684 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
687 fn print_inner_attributes_inline(&mut self,
688 attrs: &[ast::Attribute]) -> io::Result<()> {
689 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
692 fn print_outer_attributes_inline(&mut self,
693 attrs: &[ast::Attribute]) -> io::Result<()> {
694 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
697 fn print_either_attributes(&mut self,
698 attrs: &[ast::Attribute],
699 kind: ast::AttrStyle,
701 trailing_hardbreak: bool) -> io::Result<()> {
704 if attr.style == kind {
705 self.print_attribute_inline(attr, is_inline)?;
712 if count > 0 && trailing_hardbreak && !is_inline {
713 self.hardbreak_if_not_bol()?;
718 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
719 for (i, segment) in path.segments.iter().enumerate() {
721 self.writer().word("::")?
723 if segment.ident.name != keywords::CrateRoot.name() &&
724 segment.ident.name != keywords::DollarCrate.name()
726 self.writer().word(&segment.ident.as_str())?;
727 } else if segment.ident.name == keywords::DollarCrate.name() {
728 self.print_dollar_crate(segment.ident.span.ctxt())?;
734 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
735 self.print_attribute_inline(attr, false)
738 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
739 is_inline: bool) -> io::Result<()> {
741 self.hardbreak_if_not_bol()?;
743 self.maybe_print_comment(attr.span.lo())?;
744 if attr.is_sugared_doc {
745 self.writer().word(&attr.value_str().unwrap().as_str())?;
746 self.writer().hardbreak()
749 ast::AttrStyle::Inner => self.writer().word("#![")?,
750 ast::AttrStyle::Outer => self.writer().word("#[")?,
752 if let Some(mi) = attr.meta() {
753 self.print_meta_item(&mi)?
755 self.print_attribute_path(&attr.path)?;
756 self.writer().space()?;
757 self.print_tts(attr.tokens.clone())?;
759 self.writer().word("]")
763 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
765 ast::NestedMetaItemKind::MetaItem(ref mi) => {
766 self.print_meta_item(mi)
768 ast::NestedMetaItemKind::Literal(ref lit) => {
769 self.print_literal(lit)
774 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
775 self.ibox(INDENT_UNIT)?;
777 ast::MetaItemKind::Word => self.print_attribute_path(&item.ident)?,
778 ast::MetaItemKind::NameValue(ref value) => {
779 self.print_attribute_path(&item.ident)?;
780 self.writer().space()?;
781 self.word_space("=")?;
782 self.print_literal(value)?;
784 ast::MetaItemKind::List(ref items) => {
785 self.print_attribute_path(&item.ident)?;
787 self.commasep(Consistent,
789 |s, i| s.print_meta_list_item(i))?;
796 /// This doesn't deserve to be called "pretty" printing, but it should be
797 /// meaning-preserving. A quick hack that might help would be to look at the
798 /// spans embedded in the TTs to decide where to put spaces and newlines.
799 /// But it'd be better to parse these according to the grammar of the
800 /// appropriate macro, transcribe back into the grammar we just parsed from,
801 /// and then pretty-print the resulting AST nodes (so, e.g., we print
802 /// expression arguments as expressions). It can be done! I think.
803 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
805 TokenTree::Token(_, ref tk) => {
806 self.writer().word(&token_to_string(tk))?;
808 parse::token::DocComment(..) => {
809 self.writer().hardbreak()
814 TokenTree::Delimited(_, ref delimed) => {
815 self.writer().word(&token_to_string(&delimed.open_token()))?;
816 self.writer().space()?;
817 self.print_tts(delimed.stream())?;
818 self.writer().space()?;
819 self.writer().word(&token_to_string(&delimed.close_token()))
824 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
826 for (i, tt) in tts.into_trees().enumerate() {
828 self.writer().space()?;
835 fn space_if_not_bol(&mut self) -> io::Result<()> {
836 if !self.is_bol() { self.writer().space()?; }
840 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
842 fn print_dollar_crate(&mut self, mut ctxt: SyntaxContext) -> io::Result<()> {
843 if let Some(mark) = ctxt.adjust(Mark::root()) {
844 // Make a best effort to print something that complies
845 if mark.is_builtin() {
846 if let Some(name) = std_inject::injected_crate_name() {
847 self.writer().word("::")?;
848 self.writer().word(name)?;
856 impl<'a> PrintState<'a> for State<'a> {
857 fn writer(&mut self) -> &mut pp::Printer<'a> {
861 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
865 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
869 fn cur_cmnt(&mut self) -> &mut usize {
873 fn cur_lit(&mut self) -> Option<&comments::Literal> {
877 fn bump_lit(&mut self) -> Option<comments::Literal> {
883 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
884 self.boxes.push(pp::Breaks::Consistent);
888 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
893 pub fn head(&mut self, w: &str) -> io::Result<()> {
894 // outer-box is consistent
895 self.cbox(INDENT_UNIT)?;
896 // head-box is inconsistent
897 self.ibox(w.len() + 1)?;
898 // keyword that starts the head
905 pub fn bopen(&mut self) -> io::Result<()> {
907 self.end() // close the head-box
910 pub fn bclose_(&mut self, span: syntax_pos::Span,
911 indented: usize) -> io::Result<()> {
912 self.bclose_maybe_open(span, indented, true)
914 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
915 indented: usize, close_box: bool) -> io::Result<()> {
916 self.maybe_print_comment(span.hi())?;
917 self.break_offset_if_not_bol(1, -(indented as isize))?;
920 self.end()?; // close the outer-box
924 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
925 self.bclose_(span, INDENT_UNIT)
928 pub fn in_cbox(&self) -> bool {
929 match self.boxes.last() {
930 Some(&last_box) => last_box == pp::Breaks::Consistent,
935 pub fn break_offset_if_not_bol(&mut self, n: usize,
936 off: isize) -> io::Result<()> {
938 self.s.break_offset(n, off)
940 if off != 0 && self.s.last_token().is_hardbreak_tok() {
941 // We do something pretty sketchy here: tuck the nonzero
942 // offset-adjustment we were going to deposit along with the
943 // break into the previous hardbreak.
944 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
950 // Synthesizes a comment that was not textually present in the original source
952 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
955 self.s.word(&text[..])?;
962 pub fn commasep_cmnt<T, F, G>(&mut self,
966 mut get_span: G) -> io::Result<()> where
967 F: FnMut(&mut State, &T) -> io::Result<()>,
968 G: FnMut(&T) -> syntax_pos::Span,
971 let len = elts.len();
974 self.maybe_print_comment(get_span(elt).hi())?;
979 self.maybe_print_trailing_comment(get_span(elt),
980 Some(get_span(&elts[i]).hi()))?;
981 self.space_if_not_bol()?;
987 pub fn commasep_exprs(&mut self, b: Breaks,
988 exprs: &[P<ast::Expr>]) -> io::Result<()> {
989 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
992 pub fn print_mod(&mut self, _mod: &ast::Mod,
993 attrs: &[ast::Attribute]) -> io::Result<()> {
994 self.print_inner_attributes(attrs)?;
995 for item in &_mod.items {
996 self.print_item(item)?;
1001 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
1002 attrs: &[ast::Attribute]) -> io::Result<()> {
1003 self.print_inner_attributes(attrs)?;
1004 for item in &nmod.items {
1005 self.print_foreign_item(item)?;
1010 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1011 if let Some(lt) = *lifetime {
1012 self.print_lifetime(lt)?;
1018 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
1020 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1021 GenericArg::Type(ty) => self.print_type(ty),
1025 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1026 self.maybe_print_comment(ty.span.lo())?;
1029 ast::TyKind::Slice(ref ty) => {
1031 self.print_type(ty)?;
1034 ast::TyKind::Ptr(ref mt) => {
1037 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1038 ast::Mutability::Immutable => self.word_nbsp("const")?,
1040 self.print_type(&mt.ty)?;
1042 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1044 self.print_opt_lifetime(lifetime)?;
1047 ast::TyKind::Never => {
1050 ast::TyKind::Tup(ref elts) => {
1052 self.commasep(Inconsistent, &elts[..],
1053 |s, ty| s.print_type(ty))?;
1054 if elts.len() == 1 {
1059 ast::TyKind::Paren(ref typ) => {
1061 self.print_type(typ)?;
1064 ast::TyKind::BareFn(ref f) => {
1065 self.print_ty_fn(f.abi,
1069 &f.generic_params)?;
1071 ast::TyKind::Path(None, ref path) => {
1072 self.print_path(path, false, 0)?;
1074 ast::TyKind::Path(Some(ref qself), ref path) => {
1075 self.print_qpath(path, qself, false)?
1077 ast::TyKind::TraitObject(ref bounds, syntax) => {
1078 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1079 self.print_type_bounds(prefix, &bounds[..])?;
1081 ast::TyKind::ImplTrait(_, ref bounds) => {
1082 self.print_type_bounds("impl", &bounds[..])?;
1084 ast::TyKind::Array(ref ty, ref length) => {
1086 self.print_type(ty)?;
1088 self.print_expr(&length.value)?;
1091 ast::TyKind::Typeof(ref e) => {
1092 self.s.word("typeof(")?;
1093 self.print_expr(&e.value)?;
1096 ast::TyKind::Infer => {
1099 ast::TyKind::Err => {
1102 ast::TyKind::ImplicitSelf => {
1103 self.s.word("Self")?;
1105 ast::TyKind::Mac(ref m) => {
1112 pub fn print_foreign_item(&mut self,
1113 item: &ast::ForeignItem) -> io::Result<()> {
1114 self.hardbreak_if_not_bol()?;
1115 self.maybe_print_comment(item.span.lo())?;
1116 self.print_outer_attributes(&item.attrs)?;
1118 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1120 self.print_fn(decl, ast::FnHeader::default(),
1122 generics, &item.vis)?;
1123 self.end()?; // end head-ibox
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)?;
1136 self.end()?; // end the head-ibox
1137 self.end() // end the outer cbox
1139 ast::ForeignItemKind::Ty => {
1140 self.head(&visibility_qualified(&item.vis, "type"))?;
1141 self.print_ident(item.ident)?;
1143 self.end()?; // end the head-ibox
1144 self.end() // end the outer cbox
1146 ast::ForeignItemKind::Macro(ref m) => {
1148 match m.node.delim {
1149 MacDelimiter::Brace => Ok(()),
1150 _ => self.s.word(";")
1156 fn print_associated_const(&mut self,
1159 default: Option<&ast::Expr>,
1160 vis: &ast::Visibility)
1163 self.s.word(&visibility_qualified(vis, ""))?;
1164 self.word_space("const")?;
1165 self.print_ident(ident)?;
1166 self.word_space(":")?;
1167 self.print_type(ty)?;
1168 if let Some(expr) = default {
1170 self.word_space("=")?;
1171 self.print_expr(expr)?;
1176 fn print_associated_type(&mut self,
1178 bounds: Option<&ast::GenericBounds>,
1179 ty: Option<&ast::Ty>)
1181 self.word_space("type")?;
1182 self.print_ident(ident)?;
1183 if let Some(bounds) = bounds {
1184 self.print_type_bounds(":", bounds)?;
1186 if let Some(ty) = ty {
1188 self.word_space("=")?;
1189 self.print_type(ty)?;
1194 /// Pretty-print an item
1195 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1196 self.hardbreak_if_not_bol()?;
1197 self.maybe_print_comment(item.span.lo())?;
1198 self.print_outer_attributes(&item.attrs)?;
1199 self.ann.pre(self, NodeItem(item))?;
1201 ast::ItemKind::ExternCrate(orig_name) => {
1202 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1203 if let Some(orig_name) = orig_name {
1204 self.print_name(orig_name)?;
1209 self.print_ident(item.ident)?;
1211 self.end()?; // end inner head-block
1212 self.end()?; // end outer head-block
1214 ast::ItemKind::Use(ref tree) => {
1215 self.head(&visibility_qualified(&item.vis, "use"))?;
1216 self.print_use_tree(tree)?;
1218 self.end()?; // end inner head-block
1219 self.end()?; // end outer head-block
1221 ast::ItemKind::Static(ref ty, m, ref expr) => {
1222 self.head(&visibility_qualified(&item.vis, "static"))?;
1223 if m == ast::Mutability::Mutable {
1224 self.word_space("mut")?;
1226 self.print_ident(item.ident)?;
1227 self.word_space(":")?;
1228 self.print_type(ty)?;
1230 self.end()?; // end the head-ibox
1232 self.word_space("=")?;
1233 self.print_expr(expr)?;
1235 self.end()?; // end the outer cbox
1237 ast::ItemKind::Const(ref ty, ref expr) => {
1238 self.head(&visibility_qualified(&item.vis, "const"))?;
1239 self.print_ident(item.ident)?;
1240 self.word_space(":")?;
1241 self.print_type(ty)?;
1243 self.end()?; // end the head-ibox
1245 self.word_space("=")?;
1246 self.print_expr(expr)?;
1248 self.end()?; // end the outer cbox
1250 ast::ItemKind::Fn(ref decl, header, ref typarams, ref body) => {
1260 self.print_block_with_attrs(body, &item.attrs)?;
1262 ast::ItemKind::Mod(ref _mod) => {
1263 self.head(&visibility_qualified(&item.vis, "mod"))?;
1264 self.print_ident(item.ident)?;
1267 self.print_mod(_mod, &item.attrs)?;
1268 self.bclose(item.span)?;
1270 ast::ItemKind::ForeignMod(ref nmod) => {
1271 self.head("extern")?;
1272 self.word_nbsp(&nmod.abi.to_string())?;
1274 self.print_foreign_mod(nmod, &item.attrs)?;
1275 self.bclose(item.span)?;
1277 ast::ItemKind::GlobalAsm(ref ga) => {
1278 self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
1279 self.s.word(&ga.asm.as_str())?;
1282 ast::ItemKind::Ty(ref ty, ref generics) => {
1283 self.head(&visibility_qualified(&item.vis, "type"))?;
1284 self.print_ident(item.ident)?;
1285 self.print_generic_params(&generics.params)?;
1286 self.end()?; // end the inner ibox
1288 self.print_where_clause(&generics.where_clause)?;
1290 self.word_space("=")?;
1291 self.print_type(ty)?;
1293 self.end()?; // end the outer ibox
1295 ast::ItemKind::Existential(ref bounds, ref generics) => {
1296 self.head(&visibility_qualified(&item.vis, "existential type"))?;
1297 self.print_ident(item.ident)?;
1298 self.print_generic_params(&generics.params)?;
1299 self.end()?; // end the inner ibox
1301 self.print_where_clause(&generics.where_clause)?;
1303 self.print_type_bounds(":", bounds)?;
1305 self.end()?; // end the outer ibox
1307 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1308 self.print_enum_def(
1316 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1317 self.head(&visibility_qualified(&item.vis, "struct"))?;
1318 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1320 ast::ItemKind::Union(ref struct_def, ref generics) => {
1321 self.head(&visibility_qualified(&item.vis, "union"))?;
1322 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1324 ast::ItemKind::Impl(unsafety,
1330 ref impl_items) => {
1332 self.print_visibility(&item.vis)?;
1333 self.print_defaultness(defaultness)?;
1334 self.print_unsafety(unsafety)?;
1335 self.word_nbsp("impl")?;
1337 if !generics.params.is_empty() {
1338 self.print_generic_params(&generics.params)?;
1342 if polarity == ast::ImplPolarity::Negative {
1346 if let Some(ref t) = *opt_trait {
1347 self.print_trait_ref(t)?;
1349 self.word_space("for")?;
1352 self.print_type(ty)?;
1353 self.print_where_clause(&generics.where_clause)?;
1357 self.print_inner_attributes(&item.attrs)?;
1358 for impl_item in impl_items {
1359 self.print_impl_item(impl_item)?;
1361 self.bclose(item.span)?;
1363 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1365 self.print_visibility(&item.vis)?;
1366 self.print_unsafety(unsafety)?;
1367 self.print_is_auto(is_auto)?;
1368 self.word_nbsp("trait")?;
1369 self.print_ident(item.ident)?;
1370 self.print_generic_params(&generics.params)?;
1371 let mut real_bounds = Vec::with_capacity(bounds.len());
1372 for b in bounds.iter() {
1373 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1375 self.word_space("for ?")?;
1376 self.print_trait_ref(&ptr.trait_ref)?;
1378 real_bounds.push(b.clone());
1381 self.print_type_bounds(":", &real_bounds[..])?;
1382 self.print_where_clause(&generics.where_clause)?;
1385 for trait_item in trait_items {
1386 self.print_trait_item(trait_item)?;
1388 self.bclose(item.span)?;
1390 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1392 self.print_visibility(&item.vis)?;
1393 self.word_nbsp("trait")?;
1394 self.print_ident(item.ident)?;
1395 self.print_generic_params(&generics.params)?;
1396 let mut real_bounds = Vec::with_capacity(bounds.len());
1397 // FIXME(durka) this seems to be some quite outdated syntax
1398 for b in bounds.iter() {
1399 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1401 self.word_space("for ?")?;
1402 self.print_trait_ref(&ptr.trait_ref)?;
1404 real_bounds.push(b.clone());
1408 self.print_type_bounds("=", &real_bounds[..])?;
1409 self.print_where_clause(&generics.where_clause)?;
1412 ast::ItemKind::Mac(ref mac) => {
1413 if item.ident.name == keywords::Invalid.name() {
1414 self.print_mac(mac)?;
1415 match mac.node.delim {
1416 MacDelimiter::Brace => {}
1417 _ => self.s.word(";")?,
1420 self.print_path(&mac.node.path, false, 0)?;
1422 self.print_ident(item.ident)?;
1423 self.cbox(INDENT_UNIT)?;
1425 self.print_tts(mac.node.stream())?;
1431 ast::ItemKind::MacroDef(ref tts) => {
1432 self.s.word("macro_rules! ")?;
1433 self.print_ident(item.ident)?;
1434 self.cbox(INDENT_UNIT)?;
1436 self.print_tts(tts.stream())?;
1442 self.ann.post(self, NodeItem(item))
1445 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1446 self.print_path(&t.path, false, 0)
1449 fn print_formal_generic_params(
1451 generic_params: &[ast::GenericParam]
1452 ) -> io::Result<()> {
1453 if !generic_params.is_empty() {
1454 self.s.word("for")?;
1455 self.print_generic_params(generic_params)?;
1461 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1462 self.print_formal_generic_params(&t.bound_generic_params)?;
1463 self.print_trait_ref(&t.trait_ref)
1466 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1467 generics: &ast::Generics, ident: ast::Ident,
1468 span: syntax_pos::Span,
1469 visibility: &ast::Visibility) -> io::Result<()> {
1470 self.head(&visibility_qualified(visibility, "enum"))?;
1471 self.print_ident(ident)?;
1472 self.print_generic_params(&generics.params)?;
1473 self.print_where_clause(&generics.where_clause)?;
1475 self.print_variants(&enum_definition.variants, span)
1478 pub fn print_variants(&mut self,
1479 variants: &[ast::Variant],
1480 span: syntax_pos::Span) -> io::Result<()> {
1483 self.space_if_not_bol()?;
1484 self.maybe_print_comment(v.span.lo())?;
1485 self.print_outer_attributes(&v.node.attrs)?;
1486 self.ibox(INDENT_UNIT)?;
1487 self.print_variant(v)?;
1490 self.maybe_print_trailing_comment(v.span, None)?;
1495 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1497 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1498 ast::VisibilityKind::Crate(sugar) => match sugar {
1499 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1500 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1502 ast::VisibilityKind::Restricted { ref path, .. } => {
1503 let path = to_string(|s| s.print_path(path, false, 0));
1504 if path == "self" || path == "super" {
1505 self.word_nbsp(&format!("pub({})", path))
1507 self.word_nbsp(&format!("pub(in {})", path))
1510 ast::VisibilityKind::Inherited => Ok(())
1514 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1515 if let ast::Defaultness::Default = defaultness {
1516 try!(self.word_nbsp("default"));
1521 pub fn print_struct(&mut self,
1522 struct_def: &ast::VariantData,
1523 generics: &ast::Generics,
1525 span: syntax_pos::Span,
1526 print_finalizer: bool) -> io::Result<()> {
1527 self.print_ident(ident)?;
1528 self.print_generic_params(&generics.params)?;
1529 if !struct_def.is_struct() {
1530 if struct_def.is_tuple() {
1533 Inconsistent, struct_def.fields(),
1535 s.maybe_print_comment(field.span.lo())?;
1536 s.print_outer_attributes(&field.attrs)?;
1537 s.print_visibility(&field.vis)?;
1538 s.print_type(&field.ty)
1543 self.print_where_clause(&generics.where_clause)?;
1544 if print_finalizer {
1548 self.end() // close the outer-box
1550 self.print_where_clause(&generics.where_clause)?;
1553 self.hardbreak_if_not_bol()?;
1555 for field in struct_def.fields() {
1556 self.hardbreak_if_not_bol()?;
1557 self.maybe_print_comment(field.span.lo())?;
1558 self.print_outer_attributes(&field.attrs)?;
1559 self.print_visibility(&field.vis)?;
1560 self.print_ident(field.ident.unwrap())?;
1561 self.word_nbsp(":")?;
1562 self.print_type(&field.ty)?;
1570 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1572 let generics = ast::Generics::default();
1573 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1574 match v.node.disr_expr {
1577 self.word_space("=")?;
1578 self.print_expr(&d.value)
1584 pub fn print_method_sig(&mut self,
1586 generics: &ast::Generics,
1588 vis: &ast::Visibility)
1590 self.print_fn(&m.decl,
1597 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1599 self.ann.pre(self, NodeSubItem(ti.id))?;
1600 self.hardbreak_if_not_bol()?;
1601 self.maybe_print_comment(ti.span.lo())?;
1602 self.print_outer_attributes(&ti.attrs)?;
1604 ast::TraitItemKind::Const(ref ty, ref default) => {
1605 self.print_associated_const(
1608 default.as_ref().map(|expr| &**expr),
1609 &codemap::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1612 ast::TraitItemKind::Method(ref sig, ref body) => {
1616 self.print_method_sig(
1620 &codemap::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1622 if let Some(ref body) = *body {
1624 self.print_block_with_attrs(body, &ti.attrs)?;
1629 ast::TraitItemKind::Type(ref bounds, ref default) => {
1630 self.print_associated_type(ti.ident, Some(bounds),
1631 default.as_ref().map(|ty| &**ty))?;
1633 ast::TraitItemKind::Macro(ref mac) => {
1634 self.print_mac(mac)?;
1635 match mac.node.delim {
1636 MacDelimiter::Brace => {}
1637 _ => self.s.word(";")?,
1641 self.ann.post(self, NodeSubItem(ti.id))
1644 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1645 self.ann.pre(self, NodeSubItem(ii.id))?;
1646 self.hardbreak_if_not_bol()?;
1647 self.maybe_print_comment(ii.span.lo())?;
1648 self.print_outer_attributes(&ii.attrs)?;
1649 self.print_defaultness(ii.defaultness)?;
1651 ast::ImplItemKind::Const(ref ty, ref expr) => {
1652 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1654 ast::ImplItemKind::Method(ref sig, ref body) => {
1656 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1658 self.print_block_with_attrs(body, &ii.attrs)?;
1660 ast::ImplItemKind::Type(ref ty) => {
1661 self.print_associated_type(ii.ident, None, Some(ty))?;
1663 ast::ImplItemKind::Existential(ref bounds) => {
1664 self.word_space("existential")?;
1665 self.print_associated_type(ii.ident, Some(bounds), None)?;
1667 ast::ImplItemKind::Macro(ref mac) => {
1668 self.print_mac(mac)?;
1669 match mac.node.delim {
1670 MacDelimiter::Brace => {}
1671 _ => self.s.word(";")?,
1675 self.ann.post(self, NodeSubItem(ii.id))
1678 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1679 self.maybe_print_comment(st.span.lo())?;
1681 ast::StmtKind::Local(ref loc) => {
1682 self.print_outer_attributes(&loc.attrs)?;
1683 self.space_if_not_bol()?;
1684 self.ibox(INDENT_UNIT)?;
1685 self.word_nbsp("let")?;
1687 self.ibox(INDENT_UNIT)?;
1688 self.print_local_decl(loc)?;
1690 if let Some(ref init) = loc.init {
1692 self.word_space("=")?;
1693 self.print_expr(init)?;
1698 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1699 ast::StmtKind::Expr(ref expr) => {
1700 self.space_if_not_bol()?;
1701 self.print_expr_outer_attr_style(expr, false)?;
1702 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1706 ast::StmtKind::Semi(ref expr) => {
1707 self.space_if_not_bol()?;
1708 self.print_expr_outer_attr_style(expr, false)?;
1711 ast::StmtKind::Mac(ref mac) => {
1712 let (ref mac, style, ref attrs) = **mac;
1713 self.space_if_not_bol()?;
1714 self.print_outer_attributes(attrs)?;
1715 self.print_mac(mac)?;
1716 if style == ast::MacStmtStyle::Semicolon {
1721 self.maybe_print_trailing_comment(st.span, None)
1724 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1725 self.print_block_with_attrs(blk, &[])
1728 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1729 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1732 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1733 attrs: &[ast::Attribute])
1735 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1738 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1739 indented: usize) -> io::Result<()> {
1740 self.print_block_maybe_unclosed(blk, indented, &[], false)
1743 pub fn print_block_with_attrs(&mut self,
1745 attrs: &[ast::Attribute]) -> io::Result<()> {
1746 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1749 pub fn print_block_maybe_unclosed(&mut self,
1752 attrs: &[ast::Attribute],
1753 close_box: bool) -> io::Result<()> {
1755 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1756 BlockCheckMode::Default => ()
1758 self.maybe_print_comment(blk.span.lo())?;
1759 self.ann.pre(self, NodeBlock(blk))?;
1762 self.print_inner_attributes(attrs)?;
1764 for (i, st) in blk.stmts.iter().enumerate() {
1766 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1767 self.maybe_print_comment(st.span.lo())?;
1768 self.space_if_not_bol()?;
1769 self.print_expr_outer_attr_style(expr, false)?;
1770 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1772 _ => self.print_stmt(st)?,
1776 self.bclose_maybe_open(blk.span, indented, close_box)?;
1777 self.ann.post(self, NodeBlock(blk))
1780 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1784 // "another else-if"
1785 ast::ExprKind::If(ref i, ref then, ref e) => {
1786 self.cbox(INDENT_UNIT - 1)?;
1788 self.s.word(" else if ")?;
1789 self.print_expr_as_cond(i)?;
1791 self.print_block(then)?;
1792 self.print_else(e.as_ref().map(|e| &**e))
1794 // "another else-if-let"
1795 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1796 self.cbox(INDENT_UNIT - 1)?;
1798 self.s.word(" else if let ")?;
1799 self.print_pats(pats)?;
1801 self.word_space("=")?;
1802 self.print_expr_as_cond(expr)?;
1804 self.print_block(then)?;
1805 self.print_else(e.as_ref().map(|e| &**e))
1808 ast::ExprKind::Block(ref b, _) => {
1809 self.cbox(INDENT_UNIT - 1)?;
1811 self.s.word(" else ")?;
1814 // BLEAH, constraints would be great here
1816 panic!("print_if saw if with weird alternative");
1824 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1825 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1827 self.print_expr_as_cond(test)?;
1829 self.print_block(blk)?;
1830 self.print_else(elseopt)
1833 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1834 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1835 self.head("if let")?;
1836 self.print_pats(pats)?;
1838 self.word_space("=")?;
1839 self.print_expr_as_cond(expr)?;
1841 self.print_block(blk)?;
1842 self.print_else(elseopt)
1845 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1846 self.print_path(&m.node.path, false, 0)?;
1848 match m.node.delim {
1849 MacDelimiter::Parenthesis => self.popen()?,
1850 MacDelimiter::Bracket => self.s.word("[")?,
1851 MacDelimiter::Brace => {
1856 self.print_tts(m.node.stream())?;
1857 match m.node.delim {
1858 MacDelimiter::Parenthesis => self.pclose(),
1859 MacDelimiter::Bracket => self.s.word("]"),
1860 MacDelimiter::Brace => self.bclose(m.span),
1865 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1867 self.commasep_exprs(Inconsistent, args)?;
1871 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1872 let needs_par = expr.precedence().order() < prec;
1876 self.print_expr(expr)?;
1883 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1884 /// `if cond { ... }`.
1885 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1886 let needs_par = match expr.node {
1887 // These cases need parens due to the parse error observed in #26461: `if return {}`
1888 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1889 ast::ExprKind::Closure(..) |
1890 ast::ExprKind::Ret(..) |
1891 ast::ExprKind::Break(..) => true,
1893 _ => parser::contains_exterior_struct_lit(expr),
1899 self.print_expr(expr)?;
1906 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1907 attrs: &[Attribute]) -> io::Result<()> {
1908 self.ibox(INDENT_UNIT)?;
1910 self.print_inner_attributes_inline(attrs)?;
1911 self.commasep_exprs(Inconsistent, &exprs[..])?;
1916 fn print_expr_repeat(&mut self,
1917 element: &ast::Expr,
1918 count: &ast::AnonConst,
1919 attrs: &[Attribute]) -> io::Result<()> {
1920 self.ibox(INDENT_UNIT)?;
1922 self.print_inner_attributes_inline(attrs)?;
1923 self.print_expr(element)?;
1924 self.word_space(";")?;
1925 self.print_expr(&count.value)?;
1930 fn print_expr_struct(&mut self,
1932 fields: &[ast::Field],
1933 wth: &Option<P<ast::Expr>>,
1934 attrs: &[Attribute]) -> io::Result<()> {
1935 self.print_path(path, true, 0)?;
1937 self.print_inner_attributes_inline(attrs)?;
1942 s.ibox(INDENT_UNIT)?;
1943 if !field.is_shorthand {
1944 s.print_ident(field.ident)?;
1947 s.print_expr(&field.expr)?;
1953 self.ibox(INDENT_UNIT)?;
1954 if !fields.is_empty() {
1959 self.print_expr(expr)?;
1962 _ => if !fields.is_empty() {
1970 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1971 attrs: &[Attribute]) -> io::Result<()> {
1973 self.print_inner_attributes_inline(attrs)?;
1974 self.commasep_exprs(Inconsistent, &exprs[..])?;
1975 if exprs.len() == 1 {
1981 fn print_expr_call(&mut self,
1983 args: &[P<ast::Expr>]) -> io::Result<()> {
1986 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1987 _ => parser::PREC_POSTFIX,
1990 self.print_expr_maybe_paren(func, prec)?;
1991 self.print_call_post(args)
1994 fn print_expr_method_call(&mut self,
1995 segment: &ast::PathSegment,
1996 args: &[P<ast::Expr>]) -> io::Result<()> {
1997 let base_args = &args[1..];
1998 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
2000 self.print_ident(segment.ident)?;
2001 if let Some(ref args) = segment.args {
2002 self.print_generic_args(args, true)?;
2004 self.print_call_post(base_args)
2007 fn print_expr_binary(&mut self,
2010 rhs: &ast::Expr) -> io::Result<()> {
2011 let assoc_op = AssocOp::from_ast_binop(op.node);
2012 let prec = assoc_op.precedence() as i8;
2013 let fixity = assoc_op.fixity();
2015 let (left_prec, right_prec) = match fixity {
2016 Fixity::Left => (prec, prec + 1),
2017 Fixity::Right => (prec + 1, prec),
2018 Fixity::None => (prec + 1, prec + 1),
2021 let left_prec = match (&lhs.node, op.node) {
2022 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
2023 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
2024 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
2025 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
2026 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
2030 self.print_expr_maybe_paren(lhs, left_prec)?;
2032 self.word_space(op.node.to_string())?;
2033 self.print_expr_maybe_paren(rhs, right_prec)
2036 fn print_expr_unary(&mut self,
2038 expr: &ast::Expr) -> io::Result<()> {
2039 self.s.word(ast::UnOp::to_string(op))?;
2040 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2043 fn print_expr_addr_of(&mut self,
2044 mutability: ast::Mutability,
2045 expr: &ast::Expr) -> io::Result<()> {
2047 self.print_mutability(mutability)?;
2048 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2051 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2052 self.print_expr_outer_attr_style(expr, true)
2055 fn print_expr_outer_attr_style(&mut self,
2057 is_inline: bool) -> io::Result<()> {
2058 self.maybe_print_comment(expr.span.lo())?;
2060 let attrs = &expr.attrs;
2062 self.print_outer_attributes_inline(attrs)?;
2064 self.print_outer_attributes(attrs)?;
2067 self.ibox(INDENT_UNIT)?;
2068 self.ann.pre(self, NodeExpr(expr))?;
2070 ast::ExprKind::Box(ref expr) => {
2071 self.word_space("box")?;
2072 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2074 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2075 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2076 self.print_expr_maybe_paren(place, prec + 1)?;
2078 self.word_space("<-")?;
2079 self.print_expr_maybe_paren(expr, prec)?;
2081 ast::ExprKind::Array(ref exprs) => {
2082 self.print_expr_vec(&exprs[..], attrs)?;
2084 ast::ExprKind::Repeat(ref element, ref count) => {
2085 self.print_expr_repeat(element, count, attrs)?;
2087 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2088 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2090 ast::ExprKind::Tup(ref exprs) => {
2091 self.print_expr_tup(&exprs[..], attrs)?;
2093 ast::ExprKind::Call(ref func, ref args) => {
2094 self.print_expr_call(func, &args[..])?;
2096 ast::ExprKind::MethodCall(ref segment, ref args) => {
2097 self.print_expr_method_call(segment, &args[..])?;
2099 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2100 self.print_expr_binary(op, lhs, rhs)?;
2102 ast::ExprKind::Unary(op, ref expr) => {
2103 self.print_expr_unary(op, expr)?;
2105 ast::ExprKind::AddrOf(m, ref expr) => {
2106 self.print_expr_addr_of(m, expr)?;
2108 ast::ExprKind::Lit(ref lit) => {
2109 self.print_literal(lit)?;
2111 ast::ExprKind::Cast(ref expr, ref ty) => {
2112 let prec = AssocOp::As.precedence() as i8;
2113 self.print_expr_maybe_paren(expr, prec)?;
2115 self.word_space("as")?;
2116 self.print_type(ty)?;
2118 ast::ExprKind::Type(ref expr, ref ty) => {
2119 let prec = AssocOp::Colon.precedence() as i8;
2120 self.print_expr_maybe_paren(expr, prec)?;
2121 self.word_space(":")?;
2122 self.print_type(ty)?;
2124 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2125 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2127 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2128 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2130 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2131 if let Some(label) = opt_label {
2132 self.print_ident(label.ident)?;
2133 self.word_space(":")?;
2135 self.head("while")?;
2136 self.print_expr_as_cond(test)?;
2138 self.print_block_with_attrs(blk, attrs)?;
2140 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2141 if let Some(label) = opt_label {
2142 self.print_ident(label.ident)?;
2143 self.word_space(":")?;
2145 self.head("while let")?;
2146 self.print_pats(pats)?;
2148 self.word_space("=")?;
2149 self.print_expr_as_cond(expr)?;
2151 self.print_block_with_attrs(blk, attrs)?;
2153 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2154 if let Some(label) = opt_label {
2155 self.print_ident(label.ident)?;
2156 self.word_space(":")?;
2159 self.print_pat(pat)?;
2161 self.word_space("in")?;
2162 self.print_expr_as_cond(iter)?;
2164 self.print_block_with_attrs(blk, attrs)?;
2166 ast::ExprKind::Loop(ref blk, opt_label) => {
2167 if let Some(label) = opt_label {
2168 self.print_ident(label.ident)?;
2169 self.word_space(":")?;
2173 self.print_block_with_attrs(blk, attrs)?;
2175 ast::ExprKind::Match(ref expr, ref arms) => {
2176 self.cbox(INDENT_UNIT)?;
2178 self.word_nbsp("match")?;
2179 self.print_expr_as_cond(expr)?;
2182 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2184 self.print_arm(arm)?;
2186 self.bclose_(expr.span, INDENT_UNIT)?;
2188 ast::ExprKind::Closure(
2189 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2190 self.print_movability(movability)?;
2191 self.print_asyncness(asyncness)?;
2192 self.print_capture_clause(capture_clause)?;
2194 self.print_fn_block_args(decl)?;
2196 self.print_expr(body)?;
2197 self.end()?; // need to close a box
2199 // a box will be closed by print_expr, but we didn't want an overall
2200 // wrapper so we closed the corresponding opening. so create an
2201 // empty box to satisfy the close.
2204 ast::ExprKind::Block(ref blk, opt_label) => {
2205 if let Some(label) = opt_label {
2206 self.print_ident(label.ident)?;
2207 self.word_space(":")?;
2209 // containing cbox, will be closed by print-block at }
2210 self.cbox(INDENT_UNIT)?;
2211 // head-box, will be closed by print-block after {
2213 self.print_block_with_attrs(blk, attrs)?;
2215 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2216 self.word_nbsp("async")?;
2217 self.print_capture_clause(capture_clause)?;
2219 self.print_block_with_attrs(blk, attrs)?;
2221 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2222 let prec = AssocOp::Assign.precedence() as i8;
2223 self.print_expr_maybe_paren(lhs, prec + 1)?;
2225 self.word_space("=")?;
2226 self.print_expr_maybe_paren(rhs, prec)?;
2228 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2229 let prec = AssocOp::Assign.precedence() as i8;
2230 self.print_expr_maybe_paren(lhs, prec + 1)?;
2232 self.s.word(op.node.to_string())?;
2233 self.word_space("=")?;
2234 self.print_expr_maybe_paren(rhs, prec)?;
2236 ast::ExprKind::Field(ref expr, ident) => {
2237 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2239 self.print_ident(ident)?;
2241 ast::ExprKind::Index(ref expr, ref index) => {
2242 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2244 self.print_expr(index)?;
2247 ast::ExprKind::Range(ref start, ref end, limits) => {
2248 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2249 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2250 // Here we use a fake precedence value so that any child with lower precedence than
2251 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2252 let fake_prec = AssocOp::LOr.precedence() as i8;
2253 if let Some(ref e) = *start {
2254 self.print_expr_maybe_paren(e, fake_prec)?;
2256 if limits == ast::RangeLimits::HalfOpen {
2259 self.s.word("..=")?;
2261 if let Some(ref e) = *end {
2262 self.print_expr_maybe_paren(e, fake_prec)?;
2265 ast::ExprKind::Path(None, ref path) => {
2266 self.print_path(path, true, 0)?
2268 ast::ExprKind::Path(Some(ref qself), ref path) => {
2269 self.print_qpath(path, qself, true)?
2271 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2272 self.s.word("break")?;
2274 if let Some(label) = opt_label {
2275 self.print_ident(label.ident)?;
2278 if let Some(ref expr) = *opt_expr {
2279 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2283 ast::ExprKind::Continue(opt_label) => {
2284 self.s.word("continue")?;
2286 if let Some(label) = opt_label {
2287 self.print_ident(label.ident)?;
2291 ast::ExprKind::Ret(ref result) => {
2292 self.s.word("return")?;
2293 if let Some(ref expr) = *result {
2295 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2298 ast::ExprKind::InlineAsm(ref a) => {
2299 self.s.word("asm!")?;
2301 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2302 self.word_space(":")?;
2304 self.commasep(Inconsistent, &a.outputs, |s, out| {
2305 let constraint = out.constraint.as_str();
2306 let mut ch = constraint.chars();
2308 Some('=') if out.is_rw => {
2309 s.print_string(&format!("+{}", ch.as_str()),
2310 ast::StrStyle::Cooked)?
2312 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2315 s.print_expr(&out.expr)?;
2320 self.word_space(":")?;
2322 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2323 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2330 self.word_space(":")?;
2332 self.commasep(Inconsistent, &a.clobbers,
2334 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2338 let mut options = vec![];
2340 options.push("volatile");
2343 options.push("alignstack");
2345 if a.dialect == ast::AsmDialect::Intel {
2346 options.push("intel");
2349 if !options.is_empty() {
2351 self.word_space(":")?;
2352 self.commasep(Inconsistent, &options,
2354 s.print_string(co, ast::StrStyle::Cooked)?;
2361 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2362 ast::ExprKind::Paren(ref e) => {
2364 self.print_inner_attributes_inline(attrs)?;
2365 self.print_expr(e)?;
2368 ast::ExprKind::Yield(ref e) => {
2369 self.s.word("yield")?;
2373 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2378 ast::ExprKind::Try(ref e) => {
2379 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2382 ast::ExprKind::TryBlock(ref blk) => {
2385 self.print_block_with_attrs(blk, attrs)?
2388 self.ann.post(self, NodeExpr(expr))?;
2392 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2393 self.print_pat(&loc.pat)?;
2394 if let Some(ref ty) = loc.ty {
2395 self.word_space(":")?;
2396 self.print_type(ty)?;
2401 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2402 if ident.is_raw_guess() {
2403 self.s.word(&format!("r#{}", ident))?;
2405 self.s.word(&ident.as_str())?;
2407 self.ann.post(self, NodeIdent(&ident))
2410 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2411 self.s.word(&i.to_string())
2414 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2415 self.s.word(&name.as_str())?;
2416 self.ann.post(self, NodeName(&name))
2419 pub fn print_for_decl(&mut self, loc: &ast::Local,
2420 coll: &ast::Expr) -> io::Result<()> {
2421 self.print_local_decl(loc)?;
2423 self.word_space("in")?;
2424 self.print_expr(coll)
2427 fn print_path(&mut self,
2429 colons_before_params: bool,
2433 self.maybe_print_comment(path.span.lo())?;
2435 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2439 self.print_path_segment(segment, colons_before_params)?;
2445 fn print_path_segment(&mut self,
2446 segment: &ast::PathSegment,
2447 colons_before_params: bool)
2450 if segment.ident.name != keywords::CrateRoot.name() &&
2451 segment.ident.name != keywords::DollarCrate.name() {
2452 self.print_ident(segment.ident)?;
2453 if let Some(ref args) = segment.args {
2454 self.print_generic_args(args, colons_before_params)?;
2456 } else if segment.ident.name == keywords::DollarCrate.name() {
2457 self.print_dollar_crate(segment.ident.span.ctxt())?;
2462 fn print_qpath(&mut self,
2465 colons_before_params: bool)
2469 self.print_type(&qself.ty)?;
2470 if qself.position > 0 {
2472 self.word_space("as")?;
2473 let depth = path.segments.len() - qself.position;
2474 self.print_path(path, false, depth)?;
2478 let item_segment = path.segments.last().unwrap();
2479 self.print_ident(item_segment.ident)?;
2480 match item_segment.args {
2481 Some(ref args) => self.print_generic_args(args, colons_before_params),
2486 fn print_generic_args(&mut self,
2487 args: &ast::GenericArgs,
2488 colons_before_params: bool)
2491 if colons_before_params {
2496 ast::GenericArgs::AngleBracketed(ref data) => {
2499 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2500 s.print_generic_arg(generic_arg)
2503 let mut comma = data.args.len() != 0;
2505 for binding in data.bindings.iter() {
2507 self.word_space(",")?
2509 self.print_ident(binding.ident)?;
2511 self.word_space("=")?;
2512 self.print_type(&binding.ty)?;
2519 ast::GenericArgs::Parenthesized(ref data) => {
2524 |s, ty| s.print_type(ty))?;
2527 if let Some(ref ty) = data.output {
2528 self.space_if_not_bol()?;
2529 self.word_space("->")?;
2530 self.print_type(ty)?;
2538 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2539 self.maybe_print_comment(pat.span.lo())?;
2540 self.ann.pre(self, NodePat(pat))?;
2541 /* Pat isn't normalized, but the beauty of it
2542 is that it doesn't matter */
2544 PatKind::Wild => self.s.word("_")?,
2545 PatKind::Ident(binding_mode, ident, ref sub) => {
2546 match binding_mode {
2547 ast::BindingMode::ByRef(mutbl) => {
2548 self.word_nbsp("ref")?;
2549 self.print_mutability(mutbl)?;
2551 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2552 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2553 self.word_nbsp("mut")?;
2556 self.print_ident(ident)?;
2557 if let Some(ref p) = *sub {
2562 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2563 self.print_path(path, true, 0)?;
2565 if let Some(ddpos) = ddpos {
2566 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2568 self.word_space(",")?;
2571 if ddpos != elts.len() {
2573 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2576 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2580 PatKind::Path(None, ref path) => {
2581 self.print_path(path, true, 0)?;
2583 PatKind::Path(Some(ref qself), ref path) => {
2584 self.print_qpath(path, qself, false)?;
2586 PatKind::Struct(ref path, ref fields, etc) => {
2587 self.print_path(path, true, 0)?;
2589 self.word_space("{")?;
2591 Consistent, &fields[..],
2593 s.cbox(INDENT_UNIT)?;
2594 if !f.node.is_shorthand {
2595 s.print_ident(f.node.ident)?;
2598 s.print_pat(&f.node.pat)?;
2601 |f| f.node.pat.span)?;
2603 if !fields.is_empty() { self.word_space(",")?; }
2609 PatKind::Tuple(ref elts, ddpos) => {
2611 if let Some(ddpos) = ddpos {
2612 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2614 self.word_space(",")?;
2617 if ddpos != elts.len() {
2619 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2622 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2623 if elts.len() == 1 {
2629 PatKind::Box(ref inner) => {
2630 self.s.word("box ")?;
2631 self.print_pat(inner)?;
2633 PatKind::Ref(ref inner, mutbl) => {
2635 if mutbl == ast::Mutability::Mutable {
2636 self.s.word("mut ")?;
2638 self.print_pat(inner)?;
2640 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2641 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2642 self.print_expr(begin)?;
2645 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2646 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2647 RangeEnd::Excluded => self.s.word("..")?,
2649 self.print_expr(end)?;
2651 PatKind::Slice(ref before, ref slice, ref after) => {
2653 self.commasep(Inconsistent,
2655 |s, p| s.print_pat(p))?;
2656 if let Some(ref p) = *slice {
2657 if !before.is_empty() { self.word_space(",")?; }
2658 if let PatKind::Wild = p.node {
2664 if !after.is_empty() { self.word_space(",")?; }
2666 self.commasep(Inconsistent,
2668 |s, p| s.print_pat(p))?;
2671 PatKind::Paren(ref inner) => {
2673 self.print_pat(inner)?;
2676 PatKind::Mac(ref m) => self.print_mac(m)?,
2678 self.ann.post(self, NodePat(pat))
2681 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2682 let mut first = true;
2688 self.word_space("|")?;
2695 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2696 // I have no idea why this check is necessary, but here it
2698 if arm.attrs.is_empty() {
2701 self.cbox(INDENT_UNIT)?;
2703 self.maybe_print_comment(arm.pats[0].span.lo())?;
2704 self.print_outer_attributes(&arm.attrs)?;
2705 self.print_pats(&arm.pats)?;
2707 if let Some(ref e) = arm.guard {
2708 self.word_space("if")?;
2709 self.print_expr(e)?;
2712 self.word_space("=>")?;
2714 match arm.body.node {
2715 ast::ExprKind::Block(ref blk, opt_label) => {
2716 if let Some(label) = opt_label {
2717 self.print_ident(label.ident)?;
2718 self.word_space(":")?;
2721 // the block will close the pattern's ibox
2722 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2724 // If it is a user-provided unsafe block, print a comma after it
2725 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2730 self.end()?; // close the ibox for the pattern
2731 self.print_expr(&arm.body)?;
2735 self.end() // close enclosing cbox
2738 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2739 match explicit_self.node {
2740 SelfKind::Value(m) => {
2741 self.print_mutability(m)?;
2744 SelfKind::Region(ref lt, m) => {
2746 self.print_opt_lifetime(lt)?;
2747 self.print_mutability(m)?;
2750 SelfKind::Explicit(ref typ, m) => {
2751 self.print_mutability(m)?;
2752 self.s.word("self")?;
2753 self.word_space(":")?;
2754 self.print_type(typ)
2759 pub fn print_fn(&mut self,
2761 header: ast::FnHeader,
2762 name: Option<ast::Ident>,
2763 generics: &ast::Generics,
2764 vis: &ast::Visibility) -> io::Result<()> {
2765 self.print_fn_header_info(header, vis)?;
2767 if let Some(name) = name {
2769 self.print_ident(name)?;
2771 self.print_generic_params(&generics.params)?;
2772 self.print_fn_args_and_ret(decl)?;
2773 self.print_where_clause(&generics.where_clause)
2776 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2779 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2781 self.s.word(", ...")?;
2785 self.print_fn_output(decl)
2788 pub fn print_fn_block_args(
2793 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2796 if let ast::FunctionRetTy::Default(..) = decl.output {
2800 self.space_if_not_bol()?;
2801 self.word_space("->")?;
2803 ast::FunctionRetTy::Ty(ref ty) => {
2804 self.print_type(ty)?;
2805 self.maybe_print_comment(ty.span.lo())
2807 ast::FunctionRetTy::Default(..) => unreachable!(),
2811 pub fn print_movability(&mut self, movability: ast::Movability)
2814 ast::Movability::Static => self.word_space("static"),
2815 ast::Movability::Movable => Ok(()),
2819 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2821 if asyncness.is_async() {
2822 self.word_nbsp("async")?;
2827 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2829 match capture_clause {
2830 ast::CaptureBy::Value => self.word_space("move"),
2831 ast::CaptureBy::Ref => Ok(()),
2835 pub fn print_type_bounds(&mut self,
2837 bounds: &[ast::GenericBound])
2839 if !bounds.is_empty() {
2840 self.s.word(prefix)?;
2841 let mut first = true;
2842 for bound in bounds {
2843 if !(first && prefix.is_empty()) {
2849 self.word_space("+")?;
2853 GenericBound::Trait(tref, modifier) => {
2854 if modifier == &TraitBoundModifier::Maybe {
2857 self.print_poly_trait_ref(tref)?;
2859 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2866 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2867 self.print_name(lifetime.ident.name)
2870 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2873 self.print_lifetime(lifetime)?;
2874 if !bounds.is_empty() {
2876 for (i, bound) in bounds.iter().enumerate() {
2878 self.s.word(" + ")?;
2881 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2889 pub fn print_generic_params(
2891 generic_params: &[ast::GenericParam]
2892 ) -> io::Result<()> {
2893 if generic_params.is_empty() {
2899 self.commasep(Inconsistent, &generic_params, |s, param| {
2901 ast::GenericParamKind::Lifetime => {
2902 s.print_outer_attributes_inline(¶m.attrs)?;
2903 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2904 s.print_lifetime_bounds(lt, ¶m.bounds)
2906 ast::GenericParamKind::Type { ref default } => {
2907 s.print_outer_attributes_inline(¶m.attrs)?;
2908 s.print_ident(param.ident)?;
2909 s.print_type_bounds(":", ¶m.bounds)?;
2911 Some(ref default) => {
2914 s.print_type(default)
2926 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2928 if where_clause.predicates.is_empty() {
2933 self.word_space("where")?;
2935 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2937 self.word_space(",")?;
2941 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2942 ref bound_generic_params,
2947 self.print_formal_generic_params(bound_generic_params)?;
2948 self.print_type(bounded_ty)?;
2949 self.print_type_bounds(":", bounds)?;
2951 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2954 self.print_lifetime_bounds(*lifetime, bounds)?;
2956 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2959 self.print_type(lhs_ty)?;
2961 self.word_space("=")?;
2962 self.print_type(rhs_ty)?;
2970 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2972 ast::UseTreeKind::Simple(rename, ..) => {
2973 self.print_path(&tree.prefix, false, 0)?;
2974 if let Some(rename) = rename {
2976 self.word_space("as")?;
2977 self.print_ident(rename)?;
2980 ast::UseTreeKind::Glob => {
2981 if !tree.prefix.segments.is_empty() {
2982 self.print_path(&tree.prefix, false, 0)?;
2987 ast::UseTreeKind::Nested(ref items) => {
2988 if tree.prefix.segments.is_empty() {
2991 self.print_path(&tree.prefix, false, 0)?;
2992 self.s.word("::{")?;
2994 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2995 this.print_use_tree(tree)
3004 pub fn print_mutability(&mut self,
3005 mutbl: ast::Mutability) -> io::Result<()> {
3007 ast::Mutability::Mutable => self.word_nbsp("mut"),
3008 ast::Mutability::Immutable => Ok(()),
3012 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
3013 self.print_mutability(mt.mutbl)?;
3014 self.print_type(&mt.ty)
3017 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
3018 self.ibox(INDENT_UNIT)?;
3019 match input.ty.node {
3020 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
3022 if let Some(eself) = input.to_self() {
3023 self.print_explicit_self(&eself)?;
3025 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
3026 ident.name == keywords::Invalid.name()
3031 self.print_pat(&input.pat)?;
3035 self.print_type(&input.ty)?;
3042 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3043 if let ast::FunctionRetTy::Default(..) = decl.output {
3047 self.space_if_not_bol()?;
3048 self.ibox(INDENT_UNIT)?;
3049 self.word_space("->")?;
3051 ast::FunctionRetTy::Default(..) => unreachable!(),
3052 ast::FunctionRetTy::Ty(ref ty) =>
3053 self.print_type(ty)?
3058 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3063 pub fn print_ty_fn(&mut self,
3065 unsafety: ast::Unsafety,
3067 name: Option<ast::Ident>,
3068 generic_params: &[ast::GenericParam])
3070 self.ibox(INDENT_UNIT)?;
3071 if !generic_params.is_empty() {
3072 self.s.word("for")?;
3073 self.print_generic_params(generic_params)?;
3075 let generics = ast::Generics {
3077 where_clause: ast::WhereClause {
3078 id: ast::DUMMY_NODE_ID,
3079 predicates: Vec::new(),
3080 span: syntax_pos::DUMMY_SP,
3082 span: syntax_pos::DUMMY_SP,
3085 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3088 &codemap::dummy_spanned(ast::VisibilityKind::Inherited))?;
3092 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3093 next_pos: Option<BytePos>)
3095 let cm = match self.cm {
3099 if let Some(ref cmnt) = self.next_comment() {
3100 if cmnt.style != comments::Trailing { return Ok(()) }
3101 let span_line = cm.lookup_char_pos(span.hi());
3102 let comment_line = cm.lookup_char_pos(cmnt.pos);
3103 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3104 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3105 self.print_comment(cmnt)?;
3111 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3112 // If there aren't any remaining comments, then we need to manually
3113 // make sure there is a line break at the end.
3114 if self.next_comment().is_none() {
3115 self.s.hardbreak()?;
3117 while let Some(ref cmnt) = self.next_comment() {
3118 self.print_comment(cmnt)?;
3123 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3124 opt_abi: Option<Abi>)
3127 Some(Abi::Rust) => Ok(()),
3129 self.word_nbsp("extern")?;
3130 self.word_nbsp(&abi.to_string())
3136 pub fn print_extern_opt_abi(&mut self,
3137 opt_abi: Option<Abi>) -> io::Result<()> {
3140 self.word_nbsp("extern")?;
3141 self.word_nbsp(&abi.to_string())
3147 pub fn print_fn_header_info(&mut self,
3148 header: ast::FnHeader,
3149 vis: &ast::Visibility) -> io::Result<()> {
3150 self.s.word(&visibility_qualified(vis, ""))?;
3152 match header.constness.node {
3153 ast::Constness::NotConst => {}
3154 ast::Constness::Const => self.word_nbsp("const")?
3157 self.print_asyncness(header.asyncness)?;
3158 self.print_unsafety(header.unsafety)?;
3160 if header.abi != Abi::Rust {
3161 self.word_nbsp("extern")?;
3162 self.word_nbsp(&header.abi.to_string())?;
3168 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3170 ast::Unsafety::Normal => Ok(()),
3171 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3175 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3177 ast::IsAuto::Yes => self.word_nbsp("auto"),
3178 ast::IsAuto::No => Ok(()),
3193 fn test_fun_to_string() {
3195 let abba_ident = ast::Ident::from_str("abba");
3197 let decl = ast::FnDecl {
3199 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3202 let generics = ast::Generics::default();
3207 unsafety: ast::Unsafety::Normal,
3208 constness: codemap::dummy_spanned(ast::Constness::NotConst),
3209 asyncness: ast::IsAsync::NotAsync,
3221 fn test_variant_to_string() {
3223 let ident = ast::Ident::from_str("principal_skinner");
3225 let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3228 // making this up as I go.... ?
3229 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3233 let varstr = variant_to_string(&var);
3234 assert_eq!(varstr, "principal_skinner");