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 use rustc_target::spec::abi::{self, Abi};
12 use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
13 use ast::{SelfKind, GenericBound, TraitBoundModifier};
14 use ast::{Attribute, MacDelimiter, GenericArg};
15 use util::parser::{self, AssocOp, Fixity};
17 use source_map::{self, SourceMap, Spanned};
18 use syntax_pos::{self, BytePos};
19 use syntax_pos::hygiene::{Mark, SyntaxContext};
20 use parse::token::{self, BinOpToken, Token};
21 use parse::lexer::comments;
22 use parse::{self, ParseSess};
23 use print::pp::{self, Breaks};
24 use print::pp::Breaks::{Consistent, Inconsistent};
28 use syntax_pos::{DUMMY_SP, FileName};
29 use tokenstream::{self, TokenStream, TokenTree};
32 use std::io::{self, Write, Read};
33 use std::iter::Peekable;
36 pub enum AnnNode<'a> {
37 Ident(&'a ast::Ident),
39 Block(&'a ast::Block),
47 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
48 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
51 #[derive(Copy, Clone)]
54 impl PpAnn for NoAnn {}
56 pub struct State<'a> {
57 pub s: pp::Printer<'a>,
58 cm: Option<&'a SourceMap>,
59 comments: Option<Vec<comments::Comment> >,
60 literals: Peekable<vec::IntoIter<comments::Literal>>,
62 boxes: Vec<pp::Breaks>,
63 ann: &'a (dyn PpAnn+'a),
66 fn rust_printer<'a>(writer: Box<dyn Write+'a>, ann: &'a dyn PpAnn) -> State<'a> {
68 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
71 literals: vec![].into_iter().peekable(),
78 pub const INDENT_UNIT: usize = 4;
80 pub const DEFAULT_COLUMNS: usize = 78;
82 /// Requires you to pass an input filename and reader so that
83 /// it can scan the input text for comments and literals to
85 pub fn print_crate<'a>(cm: &'a SourceMap,
90 out: Box<dyn Write+'a>,
92 is_expanded: bool) -> io::Result<()> {
93 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
95 if is_expanded && std_inject::injected_crate_name().is_some() {
96 // We need to print `#![no_std]` (and its feature gate) so that
97 // compiling pretty-printed source won't inject libstd again.
98 // However we don't want these attributes in the AST because
99 // of the feature gate, so we fake them up here.
101 // #![feature(prelude_import)]
102 let pi_nested = attr::mk_nested_word_item(ast::Ident::from_str("prelude_import"));
103 let list = attr::mk_list_item(DUMMY_SP, ast::Ident::from_str("feature"), vec![pi_nested]);
104 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
105 s.print_attribute(&fake_attr)?;
108 let no_std_meta = attr::mk_word_item(ast::Ident::from_str("no_std"));
109 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
110 s.print_attribute(&fake_attr)?;
113 s.print_mod(&krate.module, &krate.attrs)?;
114 s.print_remaining_comments()?;
119 pub fn new_from_input(cm: &'a SourceMap,
122 input: &mut dyn Read,
123 out: Box<dyn Write+'a>,
125 is_expanded: bool) -> State<'a> {
126 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
133 // If the code is post expansion, don't use the table of
134 // literals, since it doesn't correspond with the literals
135 // in the AST anymore.
136 if is_expanded { None } else { Some(lits) })
139 pub fn new(cm: &'a SourceMap,
140 out: Box<dyn Write+'a>,
142 comments: Option<Vec<comments::Comment>>,
143 literals: Option<Vec<comments::Literal>>) -> State<'a> {
145 s: pp::mk_printer(out, DEFAULT_COLUMNS),
148 literals: literals.unwrap_or_default().into_iter().peekable(),
156 pub fn to_string<F>(f: F) -> String where
157 F: FnOnce(&mut State) -> io::Result<()>,
159 let mut wr = Vec::new();
162 let mut printer = rust_printer(Box::new(&mut wr), &ann);
163 f(&mut printer).unwrap();
164 printer.s.eof().unwrap();
166 String::from_utf8(wr).unwrap()
169 fn binop_to_string(op: BinOpToken) -> &'static str {
175 token::Percent => "%",
184 pub fn token_to_string(tok: &Token) -> String {
186 token::Eq => "=".to_string(),
187 token::Lt => "<".to_string(),
188 token::Le => "<=".to_string(),
189 token::EqEq => "==".to_string(),
190 token::Ne => "!=".to_string(),
191 token::Ge => ">=".to_string(),
192 token::Gt => ">".to_string(),
193 token::Not => "!".to_string(),
194 token::Tilde => "~".to_string(),
195 token::OrOr => "||".to_string(),
196 token::AndAnd => "&&".to_string(),
197 token::BinOp(op) => binop_to_string(op).to_string(),
198 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
200 /* Structural symbols */
201 token::At => "@".to_string(),
202 token::Dot => ".".to_string(),
203 token::DotDot => "..".to_string(),
204 token::DotDotDot => "...".to_string(),
205 token::DotDotEq => "..=".to_string(),
206 token::DotEq => ".=".to_string(),
207 token::Comma => ",".to_string(),
208 token::Semi => ";".to_string(),
209 token::Colon => ":".to_string(),
210 token::ModSep => "::".to_string(),
211 token::RArrow => "->".to_string(),
212 token::LArrow => "<-".to_string(),
213 token::FatArrow => "=>".to_string(),
214 token::OpenDelim(token::Paren) => "(".to_string(),
215 token::CloseDelim(token::Paren) => ")".to_string(),
216 token::OpenDelim(token::Bracket) => "[".to_string(),
217 token::CloseDelim(token::Bracket) => "]".to_string(),
218 token::OpenDelim(token::Brace) => "{".to_string(),
219 token::CloseDelim(token::Brace) => "}".to_string(),
220 token::OpenDelim(token::NoDelim) |
221 token::CloseDelim(token::NoDelim) => " ".to_string(),
222 token::Pound => "#".to_string(),
223 token::Dollar => "$".to_string(),
224 token::Question => "?".to_string(),
225 token::SingleQuote => "'".to_string(),
228 token::Literal(lit, suf) => {
229 let mut out = match lit {
230 token::Byte(b) => format!("b'{}'", b),
231 token::Char(c) => format!("'{}'", c),
233 token::Integer(c) => c.to_string(),
234 token::Str_(s) => format!("\"{}\"", s),
235 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
236 delim="#".repeat(n as usize),
238 token::ByteStr(v) => format!("b\"{}\"", v),
239 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
240 delim="#".repeat(n as usize),
244 if let Some(s) = suf {
245 out.push_str(&s.as_str())
251 /* Name components */
252 token::Ident(s, false) => s.to_string(),
253 token::Ident(s, true) => format!("r#{}", s),
254 token::Lifetime(s) => s.to_string(),
257 token::DocComment(s) => s.to_string(),
258 token::Eof => "<eof>".to_string(),
259 token::Whitespace => " ".to_string(),
260 token::Comment => "/* */".to_string(),
261 token::Shebang(s) => format!("/* shebang: {}*/", s),
263 token::Interpolated(ref nt) => match nt.0 {
264 token::NtExpr(ref e) => expr_to_string(e),
265 token::NtMeta(ref e) => meta_item_to_string(e),
266 token::NtTy(ref e) => ty_to_string(e),
267 token::NtPath(ref e) => path_to_string(e),
268 token::NtItem(ref e) => item_to_string(e),
269 token::NtBlock(ref e) => block_to_string(e),
270 token::NtStmt(ref e) => stmt_to_string(e),
271 token::NtPat(ref e) => pat_to_string(e),
272 token::NtIdent(e, false) => ident_to_string(e),
273 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
274 token::NtLifetime(e) => ident_to_string(e),
275 token::NtLiteral(ref e) => expr_to_string(e),
276 token::NtTT(ref tree) => tt_to_string(tree.clone()),
277 token::NtArm(ref e) => arm_to_string(e),
278 token::NtImplItem(ref e) => impl_item_to_string(e),
279 token::NtTraitItem(ref e) => trait_item_to_string(e),
280 token::NtGenerics(ref e) => generic_params_to_string(&e.params),
281 token::NtWhereClause(ref e) => where_clause_to_string(e),
282 token::NtArg(ref e) => arg_to_string(e),
283 token::NtVis(ref e) => vis_to_string(e),
284 token::NtForeignItem(ref e) => foreign_item_to_string(e),
289 pub fn ty_to_string(ty: &ast::Ty) -> String {
290 to_string(|s| s.print_type(ty))
293 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
294 to_string(|s| s.print_type_bounds("", bounds))
297 pub fn pat_to_string(pat: &ast::Pat) -> String {
298 to_string(|s| s.print_pat(pat))
301 pub fn arm_to_string(arm: &ast::Arm) -> String {
302 to_string(|s| s.print_arm(arm))
305 pub fn expr_to_string(e: &ast::Expr) -> String {
306 to_string(|s| s.print_expr(e))
309 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
310 to_string(|s| s.print_lifetime(*lt))
313 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
314 to_string(|s| s.print_tt(tt))
317 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
318 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
321 pub fn tokens_to_string(tokens: TokenStream) -> String {
322 to_string(|s| s.print_tts(tokens))
325 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
326 to_string(|s| s.print_stmt(stmt))
329 pub fn attr_to_string(attr: &ast::Attribute) -> String {
330 to_string(|s| s.print_attribute(attr))
333 pub fn item_to_string(i: &ast::Item) -> String {
334 to_string(|s| s.print_item(i))
337 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
338 to_string(|s| s.print_impl_item(i))
341 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
342 to_string(|s| s.print_trait_item(i))
345 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
346 to_string(|s| s.print_generic_params(generic_params))
349 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
350 to_string(|s| s.print_where_clause(i))
353 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
354 to_string(|s| s.print_fn_block_args(p))
357 pub fn path_to_string(p: &ast::Path) -> String {
358 to_string(|s| s.print_path(p, false, 0))
361 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
362 to_string(|s| s.print_path_segment(p, false))
365 pub fn ident_to_string(id: ast::Ident) -> String {
366 to_string(|s| s.print_ident(id))
369 pub fn vis_to_string(v: &ast::Visibility) -> String {
370 to_string(|s| s.print_visibility(v))
373 pub fn fun_to_string(decl: &ast::FnDecl,
374 header: ast::FnHeader,
376 generics: &ast::Generics)
380 s.print_fn(decl, header, Some(name),
381 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
382 s.end()?; // Close the head box
383 s.end() // Close the outer box
387 pub fn block_to_string(blk: &ast::Block) -> String {
389 // containing cbox, will be closed by print-block at }
390 s.cbox(INDENT_UNIT)?;
391 // head-ibox, will be closed by print-block after {
397 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
398 to_string(|s| s.print_meta_list_item(li))
401 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
402 to_string(|s| s.print_meta_item(mi))
405 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
406 to_string(|s| s.print_attribute(attr))
409 pub fn lit_to_string(l: &ast::Lit) -> String {
410 to_string(|s| s.print_literal(l))
413 pub fn variant_to_string(var: &ast::Variant) -> String {
414 to_string(|s| s.print_variant(var))
417 pub fn arg_to_string(arg: &ast::Arg) -> String {
418 to_string(|s| s.print_arg(arg, false))
421 pub fn mac_to_string(arg: &ast::Mac) -> String {
422 to_string(|s| s.print_mac(arg))
425 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
426 to_string(|s| s.print_foreign_item(arg))
429 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
430 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
433 pub trait PrintState<'a> {
434 fn writer(&mut self) -> &mut pp::Printer<'a>;
435 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
436 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
437 fn cur_cmnt(&mut self) -> &mut usize;
438 fn cur_lit(&mut self) -> Option<&comments::Literal>;
439 fn bump_lit(&mut self) -> Option<comments::Literal>;
441 fn word_space(&mut self, w: &str) -> io::Result<()> {
442 self.writer().word(w)?;
443 self.writer().space()
446 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
448 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
450 fn is_begin(&mut self) -> bool {
451 match self.writer().last_token() {
452 pp::Token::Begin(_) => true,
457 fn is_end(&mut self) -> bool {
458 match self.writer().last_token() {
459 pp::Token::End => true,
464 // is this the beginning of a line?
465 fn is_bol(&mut self) -> bool {
466 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
469 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
471 self.writer().hardbreak()?
477 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
478 self.boxes().push(b);
479 self.writer().rbox(u, b)
482 fn ibox(&mut self, u: usize) -> io::Result<()> {
483 self.boxes().push(pp::Breaks::Inconsistent);
484 self.writer().ibox(u)
487 fn end(&mut self) -> io::Result<()> {
488 self.boxes().pop().unwrap();
492 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
493 where F: FnMut(&mut Self, &T) -> io::Result<()>,
496 let mut first = true;
498 if first { first = false; } else { self.word_space(",")?; }
504 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
505 while let Some(ltrl) = self.cur_lit().cloned() {
506 if ltrl.pos > pos { break; }
508 // we don't need the value here since we're forced to clone cur_lit
509 // due to lack of NLL.
519 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
520 while let Some(ref cmnt) = self.next_comment() {
522 self.print_comment(cmnt)?;
530 fn print_comment(&mut self,
531 cmnt: &comments::Comment) -> io::Result<()> {
532 let r = match cmnt.style {
534 assert_eq!(cmnt.lines.len(), 1);
535 self.writer().zerobreak()?;
536 self.writer().word(&cmnt.lines[0])?;
537 self.writer().zerobreak()
539 comments::Isolated => {
540 self.hardbreak_if_not_bol()?;
541 for line in &cmnt.lines {
542 // Don't print empty lines because they will end up as trailing
544 if !line.is_empty() {
545 self.writer().word(&line[..])?;
547 self.writer().hardbreak()?;
551 comments::Trailing => {
553 self.writer().word(" ")?;
555 if cmnt.lines.len() == 1 {
556 self.writer().word(&cmnt.lines[0])?;
557 self.writer().hardbreak()
560 for line in &cmnt.lines {
561 if !line.is_empty() {
562 self.writer().word(&line[..])?;
564 self.writer().hardbreak()?;
569 comments::BlankLine => {
570 // We need to do at least one, possibly two hardbreaks.
571 let is_semi = match self.writer().last_token() {
572 pp::Token::String(s, _) => ";" == s,
575 if is_semi || self.is_begin() || self.is_end() {
576 self.writer().hardbreak()?;
578 self.writer().hardbreak()
583 *self.cur_cmnt() = *self.cur_cmnt() + 1;
590 fn next_comment(&mut self) -> Option<comments::Comment> {
591 let cur_cmnt = *self.cur_cmnt();
592 match *self.comments() {
594 if cur_cmnt < cmnts.len() {
595 Some(cmnts[cur_cmnt].clone())
604 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
605 self.maybe_print_comment(lit.span.lo())?;
606 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
607 return self.writer().word(<rl.lit);
610 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
611 ast::LitKind::Byte(byte) => {
612 let mut res = String::from("b'");
613 res.extend(ascii::escape_default(byte).map(|c| c as char));
615 self.writer().word(&res[..])
617 ast::LitKind::Char(ch) => {
618 let mut res = String::from("'");
619 res.extend(ch.escape_default());
621 self.writer().word(&res[..])
623 ast::LitKind::Int(i, t) => {
625 ast::LitIntType::Signed(st) => {
626 self.writer().word(&st.val_to_string(i as i128))
628 ast::LitIntType::Unsigned(ut) => {
629 self.writer().word(&ut.val_to_string(i))
631 ast::LitIntType::Unsuffixed => {
632 self.writer().word(&i.to_string())
636 ast::LitKind::Float(ref f, t) => {
637 self.writer().word(&format!("{}{}", &f, t.ty_to_string()))
639 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()),
640 ast::LitKind::Bool(val) => {
641 if val { self.writer().word("true") } else { self.writer().word("false") }
643 ast::LitKind::ByteStr(ref v) => {
644 let mut escaped: String = String::new();
645 for &ch in v.iter() {
646 escaped.extend(ascii::escape_default(ch)
647 .map(|c| c as char));
649 self.writer().word(&format!("b\"{}\"", escaped))
654 fn print_string(&mut self, st: &str,
655 style: ast::StrStyle) -> io::Result<()> {
656 let st = match style {
657 ast::StrStyle::Cooked => {
658 (format!("\"{}\"", st.escape_debug()))
660 ast::StrStyle::Raw(n) => {
661 (format!("r{delim}\"{string}\"{delim}",
662 delim="#".repeat(n as usize),
666 self.writer().word(&st[..])
669 fn print_inner_attributes(&mut self,
670 attrs: &[ast::Attribute]) -> io::Result<()> {
671 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
674 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
675 attrs: &[ast::Attribute])
677 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
680 fn print_outer_attributes(&mut self,
681 attrs: &[ast::Attribute]) -> io::Result<()> {
682 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
685 fn print_inner_attributes_inline(&mut self,
686 attrs: &[ast::Attribute]) -> io::Result<()> {
687 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
690 fn print_outer_attributes_inline(&mut self,
691 attrs: &[ast::Attribute]) -> io::Result<()> {
692 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
695 fn print_either_attributes(&mut self,
696 attrs: &[ast::Attribute],
697 kind: ast::AttrStyle,
699 trailing_hardbreak: bool) -> io::Result<()> {
702 if attr.style == kind {
703 self.print_attribute_inline(attr, is_inline)?;
710 if count > 0 && trailing_hardbreak && !is_inline {
711 self.hardbreak_if_not_bol()?;
716 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
717 for (i, segment) in path.segments.iter().enumerate() {
719 self.writer().word("::")?
721 if segment.ident.name != keywords::CrateRoot.name() &&
722 segment.ident.name != keywords::DollarCrate.name()
724 self.writer().word(&segment.ident.as_str())?;
725 } else if segment.ident.name == keywords::DollarCrate.name() {
726 self.print_dollar_crate(segment.ident.span.ctxt())?;
732 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
733 self.print_attribute_inline(attr, false)
736 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
737 is_inline: bool) -> io::Result<()> {
739 self.hardbreak_if_not_bol()?;
741 self.maybe_print_comment(attr.span.lo())?;
742 if attr.is_sugared_doc {
743 self.writer().word(&attr.value_str().unwrap().as_str())?;
744 self.writer().hardbreak()
747 ast::AttrStyle::Inner => self.writer().word("#![")?,
748 ast::AttrStyle::Outer => self.writer().word("#[")?,
750 if let Some(mi) = attr.meta() {
751 self.print_meta_item(&mi)?
753 self.print_attribute_path(&attr.path)?;
754 self.writer().space()?;
755 self.print_tts(attr.tokens.clone())?;
757 self.writer().word("]")
761 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
763 ast::NestedMetaItemKind::MetaItem(ref mi) => {
764 self.print_meta_item(mi)
766 ast::NestedMetaItemKind::Literal(ref lit) => {
767 self.print_literal(lit)
772 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
773 self.ibox(INDENT_UNIT)?;
775 ast::MetaItemKind::Word => self.print_attribute_path(&item.ident)?,
776 ast::MetaItemKind::NameValue(ref value) => {
777 self.print_attribute_path(&item.ident)?;
778 self.writer().space()?;
779 self.word_space("=")?;
780 self.print_literal(value)?;
782 ast::MetaItemKind::List(ref items) => {
783 self.print_attribute_path(&item.ident)?;
785 self.commasep(Consistent,
787 |s, i| s.print_meta_list_item(i))?;
794 /// This doesn't deserve to be called "pretty" printing, but it should be
795 /// meaning-preserving. A quick hack that might help would be to look at the
796 /// spans embedded in the TTs to decide where to put spaces and newlines.
797 /// But it'd be better to parse these according to the grammar of the
798 /// appropriate macro, transcribe back into the grammar we just parsed from,
799 /// and then pretty-print the resulting AST nodes (so, e.g., we print
800 /// expression arguments as expressions). It can be done! I think.
801 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
803 TokenTree::Token(_, ref tk) => {
804 self.writer().word(&token_to_string(tk))?;
806 parse::token::DocComment(..) => {
807 self.writer().hardbreak()
812 TokenTree::Delimited(_, ref delimed) => {
813 self.writer().word(&token_to_string(&delimed.open_token()))?;
814 self.writer().space()?;
815 self.print_tts(delimed.stream())?;
816 self.writer().space()?;
817 self.writer().word(&token_to_string(&delimed.close_token()))
822 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
824 for (i, tt) in tts.into_trees().enumerate() {
826 self.writer().space()?;
833 fn space_if_not_bol(&mut self) -> io::Result<()> {
834 if !self.is_bol() { self.writer().space()?; }
838 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
840 fn print_dollar_crate(&mut self, mut ctxt: SyntaxContext) -> io::Result<()> {
841 if let Some(mark) = ctxt.adjust(Mark::root()) {
842 // Make a best effort to print something that complies
843 if mark.is_builtin() {
844 if let Some(name) = std_inject::injected_crate_name() {
845 self.writer().word("::")?;
846 self.writer().word(name)?;
854 impl<'a> PrintState<'a> for State<'a> {
855 fn writer(&mut self) -> &mut pp::Printer<'a> {
859 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
863 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
867 fn cur_cmnt(&mut self) -> &mut usize {
871 fn cur_lit(&mut self) -> Option<&comments::Literal> {
875 fn bump_lit(&mut self) -> Option<comments::Literal> {
881 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
882 self.boxes.push(pp::Breaks::Consistent);
886 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
891 pub fn head(&mut self, w: &str) -> io::Result<()> {
892 // outer-box is consistent
893 self.cbox(INDENT_UNIT)?;
894 // head-box is inconsistent
895 self.ibox(w.len() + 1)?;
896 // keyword that starts the head
903 pub fn bopen(&mut self) -> io::Result<()> {
905 self.end() // close the head-box
908 pub fn bclose_(&mut self, span: syntax_pos::Span,
909 indented: usize) -> io::Result<()> {
910 self.bclose_maybe_open(span, indented, true)
912 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
913 indented: usize, close_box: bool) -> io::Result<()> {
914 self.maybe_print_comment(span.hi())?;
915 self.break_offset_if_not_bol(1, -(indented as isize))?;
918 self.end()?; // close the outer-box
922 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
923 self.bclose_(span, INDENT_UNIT)
926 pub fn in_cbox(&self) -> bool {
927 match self.boxes.last() {
928 Some(&last_box) => last_box == pp::Breaks::Consistent,
933 pub fn break_offset_if_not_bol(&mut self, n: usize,
934 off: isize) -> io::Result<()> {
936 self.s.break_offset(n, off)
938 if off != 0 && self.s.last_token().is_hardbreak_tok() {
939 // We do something pretty sketchy here: tuck the nonzero
940 // offset-adjustment we were going to deposit along with the
941 // break into the previous hardbreak.
942 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
948 // Synthesizes a comment that was not textually present in the original source
950 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
953 self.s.word(&text[..])?;
960 pub fn commasep_cmnt<T, F, G>(&mut self,
964 mut get_span: G) -> io::Result<()> where
965 F: FnMut(&mut State, &T) -> io::Result<()>,
966 G: FnMut(&T) -> syntax_pos::Span,
969 let len = elts.len();
972 self.maybe_print_comment(get_span(elt).hi())?;
977 self.maybe_print_trailing_comment(get_span(elt),
978 Some(get_span(&elts[i]).hi()))?;
979 self.space_if_not_bol()?;
985 pub fn commasep_exprs(&mut self, b: Breaks,
986 exprs: &[P<ast::Expr>]) -> io::Result<()> {
987 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
990 pub fn print_mod(&mut self, _mod: &ast::Mod,
991 attrs: &[ast::Attribute]) -> io::Result<()> {
992 self.print_inner_attributes(attrs)?;
993 for item in &_mod.items {
994 self.print_item(item)?;
999 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
1000 attrs: &[ast::Attribute]) -> io::Result<()> {
1001 self.print_inner_attributes(attrs)?;
1002 for item in &nmod.items {
1003 self.print_foreign_item(item)?;
1008 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1009 if let Some(lt) = *lifetime {
1010 self.print_lifetime(lt)?;
1016 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
1018 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1019 GenericArg::Type(ty) => self.print_type(ty),
1023 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1024 self.maybe_print_comment(ty.span.lo())?;
1027 ast::TyKind::Slice(ref ty) => {
1029 self.print_type(ty)?;
1032 ast::TyKind::Ptr(ref mt) => {
1035 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1036 ast::Mutability::Immutable => self.word_nbsp("const")?,
1038 self.print_type(&mt.ty)?;
1040 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1042 self.print_opt_lifetime(lifetime)?;
1045 ast::TyKind::Never => {
1048 ast::TyKind::Tup(ref elts) => {
1050 self.commasep(Inconsistent, &elts[..],
1051 |s, ty| s.print_type(ty))?;
1052 if elts.len() == 1 {
1057 ast::TyKind::Paren(ref typ) => {
1059 self.print_type(typ)?;
1062 ast::TyKind::BareFn(ref f) => {
1063 self.print_ty_fn(f.abi,
1067 &f.generic_params)?;
1069 ast::TyKind::Path(None, ref path) => {
1070 self.print_path(path, false, 0)?;
1072 ast::TyKind::Path(Some(ref qself), ref path) => {
1073 self.print_qpath(path, qself, false)?
1075 ast::TyKind::TraitObject(ref bounds, syntax) => {
1076 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1077 self.print_type_bounds(prefix, &bounds[..])?;
1079 ast::TyKind::ImplTrait(_, ref bounds) => {
1080 self.print_type_bounds("impl", &bounds[..])?;
1082 ast::TyKind::Array(ref ty, ref length) => {
1084 self.print_type(ty)?;
1086 self.print_expr(&length.value)?;
1089 ast::TyKind::Typeof(ref e) => {
1090 self.s.word("typeof(")?;
1091 self.print_expr(&e.value)?;
1094 ast::TyKind::Infer => {
1097 ast::TyKind::Err => {
1100 ast::TyKind::ImplicitSelf => {
1101 self.s.word("Self")?;
1103 ast::TyKind::Mac(ref m) => {
1110 pub fn print_foreign_item(&mut self,
1111 item: &ast::ForeignItem) -> io::Result<()> {
1112 self.hardbreak_if_not_bol()?;
1113 self.maybe_print_comment(item.span.lo())?;
1114 self.print_outer_attributes(&item.attrs)?;
1116 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1118 self.print_fn(decl, ast::FnHeader::default(),
1120 generics, &item.vis)?;
1121 self.end()?; // end head-ibox
1123 self.end() // end the outer fn box
1125 ast::ForeignItemKind::Static(ref t, m) => {
1126 self.head(&visibility_qualified(&item.vis, "static"))?;
1128 self.word_space("mut")?;
1130 self.print_ident(item.ident)?;
1131 self.word_space(":")?;
1132 self.print_type(t)?;
1134 self.end()?; // end the head-ibox
1135 self.end() // end the outer cbox
1137 ast::ForeignItemKind::Ty => {
1138 self.head(&visibility_qualified(&item.vis, "type"))?;
1139 self.print_ident(item.ident)?;
1141 self.end()?; // end the head-ibox
1142 self.end() // end the outer cbox
1144 ast::ForeignItemKind::Macro(ref m) => {
1146 match m.node.delim {
1147 MacDelimiter::Brace => Ok(()),
1148 _ => self.s.word(";")
1154 fn print_associated_const(&mut self,
1157 default: Option<&ast::Expr>,
1158 vis: &ast::Visibility)
1161 self.s.word(&visibility_qualified(vis, ""))?;
1162 self.word_space("const")?;
1163 self.print_ident(ident)?;
1164 self.word_space(":")?;
1165 self.print_type(ty)?;
1166 if let Some(expr) = default {
1168 self.word_space("=")?;
1169 self.print_expr(expr)?;
1174 fn print_associated_type(&mut self,
1176 bounds: Option<&ast::GenericBounds>,
1177 ty: Option<&ast::Ty>)
1179 self.word_space("type")?;
1180 self.print_ident(ident)?;
1181 if let Some(bounds) = bounds {
1182 self.print_type_bounds(":", bounds)?;
1184 if let Some(ty) = ty {
1186 self.word_space("=")?;
1187 self.print_type(ty)?;
1192 /// Pretty-print an item
1193 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1194 self.hardbreak_if_not_bol()?;
1195 self.maybe_print_comment(item.span.lo())?;
1196 self.print_outer_attributes(&item.attrs)?;
1197 self.ann.pre(self, AnnNode::Item(item))?;
1199 ast::ItemKind::ExternCrate(orig_name) => {
1200 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1201 if let Some(orig_name) = orig_name {
1202 self.print_name(orig_name)?;
1207 self.print_ident(item.ident)?;
1209 self.end()?; // end inner head-block
1210 self.end()?; // end outer head-block
1212 ast::ItemKind::Use(ref tree) => {
1213 self.head(&visibility_qualified(&item.vis, "use"))?;
1214 self.print_use_tree(tree)?;
1216 self.end()?; // end inner head-block
1217 self.end()?; // end outer head-block
1219 ast::ItemKind::Static(ref ty, m, ref expr) => {
1220 self.head(&visibility_qualified(&item.vis, "static"))?;
1221 if m == ast::Mutability::Mutable {
1222 self.word_space("mut")?;
1224 self.print_ident(item.ident)?;
1225 self.word_space(":")?;
1226 self.print_type(ty)?;
1228 self.end()?; // end the head-ibox
1230 self.word_space("=")?;
1231 self.print_expr(expr)?;
1233 self.end()?; // end the outer cbox
1235 ast::ItemKind::Const(ref ty, ref expr) => {
1236 self.head(&visibility_qualified(&item.vis, "const"))?;
1237 self.print_ident(item.ident)?;
1238 self.word_space(":")?;
1239 self.print_type(ty)?;
1241 self.end()?; // end the head-ibox
1243 self.word_space("=")?;
1244 self.print_expr(expr)?;
1246 self.end()?; // end the outer cbox
1248 ast::ItemKind::Fn(ref decl, header, ref typarams, ref body) => {
1258 self.print_block_with_attrs(body, &item.attrs)?;
1260 ast::ItemKind::Mod(ref _mod) => {
1261 self.head(&visibility_qualified(&item.vis, "mod"))?;
1262 self.print_ident(item.ident)?;
1265 self.print_mod(_mod, &item.attrs)?;
1266 self.bclose(item.span)?;
1268 ast::ItemKind::ForeignMod(ref nmod) => {
1269 self.head("extern")?;
1270 self.word_nbsp(&nmod.abi.to_string())?;
1272 self.print_foreign_mod(nmod, &item.attrs)?;
1273 self.bclose(item.span)?;
1275 ast::ItemKind::GlobalAsm(ref ga) => {
1276 self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
1277 self.s.word(&ga.asm.as_str())?;
1280 ast::ItemKind::Ty(ref ty, ref generics) => {
1281 self.head(&visibility_qualified(&item.vis, "type"))?;
1282 self.print_ident(item.ident)?;
1283 self.print_generic_params(&generics.params)?;
1284 self.end()?; // end the inner ibox
1286 self.print_where_clause(&generics.where_clause)?;
1288 self.word_space("=")?;
1289 self.print_type(ty)?;
1291 self.end()?; // end the outer ibox
1293 ast::ItemKind::Existential(ref bounds, ref generics) => {
1294 self.head(&visibility_qualified(&item.vis, "existential type"))?;
1295 self.print_ident(item.ident)?;
1296 self.print_generic_params(&generics.params)?;
1297 self.end()?; // end the inner ibox
1299 self.print_where_clause(&generics.where_clause)?;
1301 self.print_type_bounds(":", bounds)?;
1303 self.end()?; // end the outer ibox
1305 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1306 self.print_enum_def(
1314 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1315 self.head(&visibility_qualified(&item.vis, "struct"))?;
1316 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1318 ast::ItemKind::Union(ref struct_def, ref generics) => {
1319 self.head(&visibility_qualified(&item.vis, "union"))?;
1320 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1322 ast::ItemKind::Impl(unsafety,
1328 ref impl_items) => {
1330 self.print_visibility(&item.vis)?;
1331 self.print_defaultness(defaultness)?;
1332 self.print_unsafety(unsafety)?;
1333 self.word_nbsp("impl")?;
1335 if !generics.params.is_empty() {
1336 self.print_generic_params(&generics.params)?;
1340 if polarity == ast::ImplPolarity::Negative {
1344 if let Some(ref t) = *opt_trait {
1345 self.print_trait_ref(t)?;
1347 self.word_space("for")?;
1350 self.print_type(ty)?;
1351 self.print_where_clause(&generics.where_clause)?;
1355 self.print_inner_attributes(&item.attrs)?;
1356 for impl_item in impl_items {
1357 self.print_impl_item(impl_item)?;
1359 self.bclose(item.span)?;
1361 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1363 self.print_visibility(&item.vis)?;
1364 self.print_unsafety(unsafety)?;
1365 self.print_is_auto(is_auto)?;
1366 self.word_nbsp("trait")?;
1367 self.print_ident(item.ident)?;
1368 self.print_generic_params(&generics.params)?;
1369 let mut real_bounds = Vec::with_capacity(bounds.len());
1370 for b in bounds.iter() {
1371 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1373 self.word_space("for ?")?;
1374 self.print_trait_ref(&ptr.trait_ref)?;
1376 real_bounds.push(b.clone());
1379 self.print_type_bounds(":", &real_bounds[..])?;
1380 self.print_where_clause(&generics.where_clause)?;
1383 for trait_item in trait_items {
1384 self.print_trait_item(trait_item)?;
1386 self.bclose(item.span)?;
1388 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1390 self.print_visibility(&item.vis)?;
1391 self.word_nbsp("trait")?;
1392 self.print_ident(item.ident)?;
1393 self.print_generic_params(&generics.params)?;
1394 let mut real_bounds = Vec::with_capacity(bounds.len());
1395 // FIXME(durka) this seems to be some quite outdated syntax
1396 for b in bounds.iter() {
1397 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1399 self.word_space("for ?")?;
1400 self.print_trait_ref(&ptr.trait_ref)?;
1402 real_bounds.push(b.clone());
1406 self.print_type_bounds("=", &real_bounds[..])?;
1407 self.print_where_clause(&generics.where_clause)?;
1410 ast::ItemKind::Mac(ref mac) => {
1411 if item.ident.name == keywords::Invalid.name() {
1412 self.print_mac(mac)?;
1413 match mac.node.delim {
1414 MacDelimiter::Brace => {}
1415 _ => self.s.word(";")?,
1418 self.print_path(&mac.node.path, false, 0)?;
1420 self.print_ident(item.ident)?;
1421 self.cbox(INDENT_UNIT)?;
1423 self.print_tts(mac.node.stream())?;
1429 ast::ItemKind::MacroDef(ref tts) => {
1430 self.s.word("macro_rules! ")?;
1431 self.print_ident(item.ident)?;
1432 self.cbox(INDENT_UNIT)?;
1434 self.print_tts(tts.stream())?;
1440 self.ann.post(self, AnnNode::Item(item))
1443 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1444 self.print_path(&t.path, false, 0)
1447 fn print_formal_generic_params(
1449 generic_params: &[ast::GenericParam]
1450 ) -> io::Result<()> {
1451 if !generic_params.is_empty() {
1452 self.s.word("for")?;
1453 self.print_generic_params(generic_params)?;
1459 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1460 self.print_formal_generic_params(&t.bound_generic_params)?;
1461 self.print_trait_ref(&t.trait_ref)
1464 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1465 generics: &ast::Generics, ident: ast::Ident,
1466 span: syntax_pos::Span,
1467 visibility: &ast::Visibility) -> io::Result<()> {
1468 self.head(&visibility_qualified(visibility, "enum"))?;
1469 self.print_ident(ident)?;
1470 self.print_generic_params(&generics.params)?;
1471 self.print_where_clause(&generics.where_clause)?;
1473 self.print_variants(&enum_definition.variants, span)
1476 pub fn print_variants(&mut self,
1477 variants: &[ast::Variant],
1478 span: syntax_pos::Span) -> io::Result<()> {
1481 self.space_if_not_bol()?;
1482 self.maybe_print_comment(v.span.lo())?;
1483 self.print_outer_attributes(&v.node.attrs)?;
1484 self.ibox(INDENT_UNIT)?;
1485 self.print_variant(v)?;
1488 self.maybe_print_trailing_comment(v.span, None)?;
1493 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1495 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1496 ast::VisibilityKind::Crate(sugar) => match sugar {
1497 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1498 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1500 ast::VisibilityKind::Restricted { ref path, .. } => {
1501 let path = to_string(|s| s.print_path(path, false, 0));
1502 if path == "self" || path == "super" {
1503 self.word_nbsp(&format!("pub({})", path))
1505 self.word_nbsp(&format!("pub(in {})", path))
1508 ast::VisibilityKind::Inherited => Ok(())
1512 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1513 if let ast::Defaultness::Default = defaultness {
1514 try!(self.word_nbsp("default"));
1519 pub fn print_struct(&mut self,
1520 struct_def: &ast::VariantData,
1521 generics: &ast::Generics,
1523 span: syntax_pos::Span,
1524 print_finalizer: bool) -> io::Result<()> {
1525 self.print_ident(ident)?;
1526 self.print_generic_params(&generics.params)?;
1527 if !struct_def.is_struct() {
1528 if struct_def.is_tuple() {
1531 Inconsistent, struct_def.fields(),
1533 s.maybe_print_comment(field.span.lo())?;
1534 s.print_outer_attributes(&field.attrs)?;
1535 s.print_visibility(&field.vis)?;
1536 s.print_type(&field.ty)
1541 self.print_where_clause(&generics.where_clause)?;
1542 if print_finalizer {
1546 self.end() // close the outer-box
1548 self.print_where_clause(&generics.where_clause)?;
1551 self.hardbreak_if_not_bol()?;
1553 for field in struct_def.fields() {
1554 self.hardbreak_if_not_bol()?;
1555 self.maybe_print_comment(field.span.lo())?;
1556 self.print_outer_attributes(&field.attrs)?;
1557 self.print_visibility(&field.vis)?;
1558 self.print_ident(field.ident.unwrap())?;
1559 self.word_nbsp(":")?;
1560 self.print_type(&field.ty)?;
1568 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1570 let generics = ast::Generics::default();
1571 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1572 match v.node.disr_expr {
1575 self.word_space("=")?;
1576 self.print_expr(&d.value)
1582 pub fn print_method_sig(&mut self,
1584 generics: &ast::Generics,
1586 vis: &ast::Visibility)
1588 self.print_fn(&m.decl,
1595 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1597 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1598 self.hardbreak_if_not_bol()?;
1599 self.maybe_print_comment(ti.span.lo())?;
1600 self.print_outer_attributes(&ti.attrs)?;
1602 ast::TraitItemKind::Const(ref ty, ref default) => {
1603 self.print_associated_const(
1606 default.as_ref().map(|expr| &**expr),
1607 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1610 ast::TraitItemKind::Method(ref sig, ref body) => {
1614 self.print_method_sig(
1618 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1620 if let Some(ref body) = *body {
1622 self.print_block_with_attrs(body, &ti.attrs)?;
1627 ast::TraitItemKind::Type(ref bounds, ref default) => {
1628 self.print_associated_type(ti.ident, Some(bounds),
1629 default.as_ref().map(|ty| &**ty))?;
1631 ast::TraitItemKind::Macro(ref mac) => {
1632 self.print_mac(mac)?;
1633 match mac.node.delim {
1634 MacDelimiter::Brace => {}
1635 _ => self.s.word(";")?,
1639 self.ann.post(self, AnnNode::SubItem(ti.id))
1642 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1643 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1644 self.hardbreak_if_not_bol()?;
1645 self.maybe_print_comment(ii.span.lo())?;
1646 self.print_outer_attributes(&ii.attrs)?;
1647 self.print_defaultness(ii.defaultness)?;
1649 ast::ImplItemKind::Const(ref ty, ref expr) => {
1650 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1652 ast::ImplItemKind::Method(ref sig, ref body) => {
1654 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1656 self.print_block_with_attrs(body, &ii.attrs)?;
1658 ast::ImplItemKind::Type(ref ty) => {
1659 self.print_associated_type(ii.ident, None, Some(ty))?;
1661 ast::ImplItemKind::Existential(ref bounds) => {
1662 self.word_space("existential")?;
1663 self.print_associated_type(ii.ident, Some(bounds), None)?;
1665 ast::ImplItemKind::Macro(ref mac) => {
1666 self.print_mac(mac)?;
1667 match mac.node.delim {
1668 MacDelimiter::Brace => {}
1669 _ => self.s.word(";")?,
1673 self.ann.post(self, AnnNode::SubItem(ii.id))
1676 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1677 self.maybe_print_comment(st.span.lo())?;
1679 ast::StmtKind::Local(ref loc) => {
1680 self.print_outer_attributes(&loc.attrs)?;
1681 self.space_if_not_bol()?;
1682 self.ibox(INDENT_UNIT)?;
1683 self.word_nbsp("let")?;
1685 self.ibox(INDENT_UNIT)?;
1686 self.print_local_decl(loc)?;
1688 if let Some(ref init) = loc.init {
1690 self.word_space("=")?;
1691 self.print_expr(init)?;
1696 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1697 ast::StmtKind::Expr(ref expr) => {
1698 self.space_if_not_bol()?;
1699 self.print_expr_outer_attr_style(expr, false)?;
1700 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1704 ast::StmtKind::Semi(ref expr) => {
1705 self.space_if_not_bol()?;
1706 self.print_expr_outer_attr_style(expr, false)?;
1709 ast::StmtKind::Mac(ref mac) => {
1710 let (ref mac, style, ref attrs) = **mac;
1711 self.space_if_not_bol()?;
1712 self.print_outer_attributes(attrs)?;
1713 self.print_mac(mac)?;
1714 if style == ast::MacStmtStyle::Semicolon {
1719 self.maybe_print_trailing_comment(st.span, None)
1722 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1723 self.print_block_with_attrs(blk, &[])
1726 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1727 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1730 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1731 attrs: &[ast::Attribute])
1733 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1736 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1737 indented: usize) -> io::Result<()> {
1738 self.print_block_maybe_unclosed(blk, indented, &[], false)
1741 pub fn print_block_with_attrs(&mut self,
1743 attrs: &[ast::Attribute]) -> io::Result<()> {
1744 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1747 pub fn print_block_maybe_unclosed(&mut self,
1750 attrs: &[ast::Attribute],
1751 close_box: bool) -> io::Result<()> {
1753 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1754 BlockCheckMode::Default => ()
1756 self.maybe_print_comment(blk.span.lo())?;
1757 self.ann.pre(self, AnnNode::Block(blk))?;
1760 self.print_inner_attributes(attrs)?;
1762 for (i, st) in blk.stmts.iter().enumerate() {
1764 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1765 self.maybe_print_comment(st.span.lo())?;
1766 self.space_if_not_bol()?;
1767 self.print_expr_outer_attr_style(expr, false)?;
1768 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1770 _ => self.print_stmt(st)?,
1774 self.bclose_maybe_open(blk.span, indented, close_box)?;
1775 self.ann.post(self, AnnNode::Block(blk))
1778 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1782 // "another else-if"
1783 ast::ExprKind::If(ref i, ref then, ref e) => {
1784 self.cbox(INDENT_UNIT - 1)?;
1786 self.s.word(" else if ")?;
1787 self.print_expr_as_cond(i)?;
1789 self.print_block(then)?;
1790 self.print_else(e.as_ref().map(|e| &**e))
1792 // "another else-if-let"
1793 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1794 self.cbox(INDENT_UNIT - 1)?;
1796 self.s.word(" else if let ")?;
1797 self.print_pats(pats)?;
1799 self.word_space("=")?;
1800 self.print_expr_as_cond(expr)?;
1802 self.print_block(then)?;
1803 self.print_else(e.as_ref().map(|e| &**e))
1806 ast::ExprKind::Block(ref b, _) => {
1807 self.cbox(INDENT_UNIT - 1)?;
1809 self.s.word(" else ")?;
1812 // BLEAH, constraints would be great here
1814 panic!("print_if saw if with weird alternative");
1822 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1823 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1825 self.print_expr_as_cond(test)?;
1827 self.print_block(blk)?;
1828 self.print_else(elseopt)
1831 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1832 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1833 self.head("if let")?;
1834 self.print_pats(pats)?;
1836 self.word_space("=")?;
1837 self.print_expr_as_cond(expr)?;
1839 self.print_block(blk)?;
1840 self.print_else(elseopt)
1843 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1844 self.print_path(&m.node.path, false, 0)?;
1846 match m.node.delim {
1847 MacDelimiter::Parenthesis => self.popen()?,
1848 MacDelimiter::Bracket => self.s.word("[")?,
1849 MacDelimiter::Brace => {
1854 self.print_tts(m.node.stream())?;
1855 match m.node.delim {
1856 MacDelimiter::Parenthesis => self.pclose(),
1857 MacDelimiter::Bracket => self.s.word("]"),
1858 MacDelimiter::Brace => self.bclose(m.span),
1863 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1865 self.commasep_exprs(Inconsistent, args)?;
1869 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1870 let needs_par = expr.precedence().order() < prec;
1874 self.print_expr(expr)?;
1881 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1882 /// `if cond { ... }`.
1883 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1884 let needs_par = match expr.node {
1885 // These cases need parens due to the parse error observed in #26461: `if return {}`
1886 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1887 ast::ExprKind::Closure(..) |
1888 ast::ExprKind::Ret(..) |
1889 ast::ExprKind::Break(..) => true,
1891 _ => parser::contains_exterior_struct_lit(expr),
1897 self.print_expr(expr)?;
1904 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1905 attrs: &[Attribute]) -> io::Result<()> {
1906 self.ibox(INDENT_UNIT)?;
1908 self.print_inner_attributes_inline(attrs)?;
1909 self.commasep_exprs(Inconsistent, &exprs[..])?;
1914 fn print_expr_repeat(&mut self,
1915 element: &ast::Expr,
1916 count: &ast::AnonConst,
1917 attrs: &[Attribute]) -> io::Result<()> {
1918 self.ibox(INDENT_UNIT)?;
1920 self.print_inner_attributes_inline(attrs)?;
1921 self.print_expr(element)?;
1922 self.word_space(";")?;
1923 self.print_expr(&count.value)?;
1928 fn print_expr_struct(&mut self,
1930 fields: &[ast::Field],
1931 wth: &Option<P<ast::Expr>>,
1932 attrs: &[Attribute]) -> io::Result<()> {
1933 self.print_path(path, true, 0)?;
1935 self.print_inner_attributes_inline(attrs)?;
1940 s.ibox(INDENT_UNIT)?;
1941 if !field.is_shorthand {
1942 s.print_ident(field.ident)?;
1945 s.print_expr(&field.expr)?;
1951 self.ibox(INDENT_UNIT)?;
1952 if !fields.is_empty() {
1957 self.print_expr(expr)?;
1960 _ => if !fields.is_empty() {
1968 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1969 attrs: &[Attribute]) -> io::Result<()> {
1971 self.print_inner_attributes_inline(attrs)?;
1972 self.commasep_exprs(Inconsistent, &exprs[..])?;
1973 if exprs.len() == 1 {
1979 fn print_expr_call(&mut self,
1981 args: &[P<ast::Expr>]) -> io::Result<()> {
1984 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1985 _ => parser::PREC_POSTFIX,
1988 self.print_expr_maybe_paren(func, prec)?;
1989 self.print_call_post(args)
1992 fn print_expr_method_call(&mut self,
1993 segment: &ast::PathSegment,
1994 args: &[P<ast::Expr>]) -> io::Result<()> {
1995 let base_args = &args[1..];
1996 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1998 self.print_ident(segment.ident)?;
1999 if let Some(ref args) = segment.args {
2000 self.print_generic_args(args, true)?;
2002 self.print_call_post(base_args)
2005 fn print_expr_binary(&mut self,
2008 rhs: &ast::Expr) -> io::Result<()> {
2009 let assoc_op = AssocOp::from_ast_binop(op.node);
2010 let prec = assoc_op.precedence() as i8;
2011 let fixity = assoc_op.fixity();
2013 let (left_prec, right_prec) = match fixity {
2014 Fixity::Left => (prec, prec + 1),
2015 Fixity::Right => (prec + 1, prec),
2016 Fixity::None => (prec + 1, prec + 1),
2019 let left_prec = match (&lhs.node, op.node) {
2020 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
2021 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
2022 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
2023 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
2024 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
2028 self.print_expr_maybe_paren(lhs, left_prec)?;
2030 self.word_space(op.node.to_string())?;
2031 self.print_expr_maybe_paren(rhs, right_prec)
2034 fn print_expr_unary(&mut self,
2036 expr: &ast::Expr) -> io::Result<()> {
2037 self.s.word(ast::UnOp::to_string(op))?;
2038 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2041 fn print_expr_addr_of(&mut self,
2042 mutability: ast::Mutability,
2043 expr: &ast::Expr) -> io::Result<()> {
2045 self.print_mutability(mutability)?;
2046 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2049 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2050 self.print_expr_outer_attr_style(expr, true)
2053 fn print_expr_outer_attr_style(&mut self,
2055 is_inline: bool) -> io::Result<()> {
2056 self.maybe_print_comment(expr.span.lo())?;
2058 let attrs = &expr.attrs;
2060 self.print_outer_attributes_inline(attrs)?;
2062 self.print_outer_attributes(attrs)?;
2065 self.ibox(INDENT_UNIT)?;
2066 self.ann.pre(self, AnnNode::Expr(expr))?;
2068 ast::ExprKind::Box(ref expr) => {
2069 self.word_space("box")?;
2070 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2072 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2073 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2074 self.print_expr_maybe_paren(place, prec + 1)?;
2076 self.word_space("<-")?;
2077 self.print_expr_maybe_paren(expr, prec)?;
2079 ast::ExprKind::Array(ref exprs) => {
2080 self.print_expr_vec(&exprs[..], attrs)?;
2082 ast::ExprKind::Repeat(ref element, ref count) => {
2083 self.print_expr_repeat(element, count, attrs)?;
2085 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2086 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2088 ast::ExprKind::Tup(ref exprs) => {
2089 self.print_expr_tup(&exprs[..], attrs)?;
2091 ast::ExprKind::Call(ref func, ref args) => {
2092 self.print_expr_call(func, &args[..])?;
2094 ast::ExprKind::MethodCall(ref segment, ref args) => {
2095 self.print_expr_method_call(segment, &args[..])?;
2097 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2098 self.print_expr_binary(op, lhs, rhs)?;
2100 ast::ExprKind::Unary(op, ref expr) => {
2101 self.print_expr_unary(op, expr)?;
2103 ast::ExprKind::AddrOf(m, ref expr) => {
2104 self.print_expr_addr_of(m, expr)?;
2106 ast::ExprKind::Lit(ref lit) => {
2107 self.print_literal(lit)?;
2109 ast::ExprKind::Cast(ref expr, ref ty) => {
2110 let prec = AssocOp::As.precedence() as i8;
2111 self.print_expr_maybe_paren(expr, prec)?;
2113 self.word_space("as")?;
2114 self.print_type(ty)?;
2116 ast::ExprKind::Type(ref expr, ref ty) => {
2117 let prec = AssocOp::Colon.precedence() as i8;
2118 self.print_expr_maybe_paren(expr, prec)?;
2119 self.word_space(":")?;
2120 self.print_type(ty)?;
2122 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2123 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2125 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2126 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2128 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2129 if let Some(label) = opt_label {
2130 self.print_ident(label.ident)?;
2131 self.word_space(":")?;
2133 self.head("while")?;
2134 self.print_expr_as_cond(test)?;
2136 self.print_block_with_attrs(blk, attrs)?;
2138 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2139 if let Some(label) = opt_label {
2140 self.print_ident(label.ident)?;
2141 self.word_space(":")?;
2143 self.head("while let")?;
2144 self.print_pats(pats)?;
2146 self.word_space("=")?;
2147 self.print_expr_as_cond(expr)?;
2149 self.print_block_with_attrs(blk, attrs)?;
2151 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2152 if let Some(label) = opt_label {
2153 self.print_ident(label.ident)?;
2154 self.word_space(":")?;
2157 self.print_pat(pat)?;
2159 self.word_space("in")?;
2160 self.print_expr_as_cond(iter)?;
2162 self.print_block_with_attrs(blk, attrs)?;
2164 ast::ExprKind::Loop(ref blk, opt_label) => {
2165 if let Some(label) = opt_label {
2166 self.print_ident(label.ident)?;
2167 self.word_space(":")?;
2171 self.print_block_with_attrs(blk, attrs)?;
2173 ast::ExprKind::Match(ref expr, ref arms) => {
2174 self.cbox(INDENT_UNIT)?;
2176 self.word_nbsp("match")?;
2177 self.print_expr_as_cond(expr)?;
2180 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2182 self.print_arm(arm)?;
2184 self.bclose_(expr.span, INDENT_UNIT)?;
2186 ast::ExprKind::Closure(
2187 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2188 self.print_movability(movability)?;
2189 self.print_asyncness(asyncness)?;
2190 self.print_capture_clause(capture_clause)?;
2192 self.print_fn_block_args(decl)?;
2194 self.print_expr(body)?;
2195 self.end()?; // need to close a box
2197 // a box will be closed by print_expr, but we didn't want an overall
2198 // wrapper so we closed the corresponding opening. so create an
2199 // empty box to satisfy the close.
2202 ast::ExprKind::Block(ref blk, opt_label) => {
2203 if let Some(label) = opt_label {
2204 self.print_ident(label.ident)?;
2205 self.word_space(":")?;
2207 // containing cbox, will be closed by print-block at }
2208 self.cbox(INDENT_UNIT)?;
2209 // head-box, will be closed by print-block after {
2211 self.print_block_with_attrs(blk, attrs)?;
2213 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2214 self.word_nbsp("async")?;
2215 self.print_capture_clause(capture_clause)?;
2217 self.print_block_with_attrs(blk, attrs)?;
2219 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2220 let prec = AssocOp::Assign.precedence() as i8;
2221 self.print_expr_maybe_paren(lhs, prec + 1)?;
2223 self.word_space("=")?;
2224 self.print_expr_maybe_paren(rhs, prec)?;
2226 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2227 let prec = AssocOp::Assign.precedence() as i8;
2228 self.print_expr_maybe_paren(lhs, prec + 1)?;
2230 self.s.word(op.node.to_string())?;
2231 self.word_space("=")?;
2232 self.print_expr_maybe_paren(rhs, prec)?;
2234 ast::ExprKind::Field(ref expr, ident) => {
2235 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2237 self.print_ident(ident)?;
2239 ast::ExprKind::Index(ref expr, ref index) => {
2240 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2242 self.print_expr(index)?;
2245 ast::ExprKind::Range(ref start, ref end, limits) => {
2246 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2247 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2248 // Here we use a fake precedence value so that any child with lower precedence than
2249 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2250 let fake_prec = AssocOp::LOr.precedence() as i8;
2251 if let Some(ref e) = *start {
2252 self.print_expr_maybe_paren(e, fake_prec)?;
2254 if limits == ast::RangeLimits::HalfOpen {
2257 self.s.word("..=")?;
2259 if let Some(ref e) = *end {
2260 self.print_expr_maybe_paren(e, fake_prec)?;
2263 ast::ExprKind::Path(None, ref path) => {
2264 self.print_path(path, true, 0)?
2266 ast::ExprKind::Path(Some(ref qself), ref path) => {
2267 self.print_qpath(path, qself, true)?
2269 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2270 self.s.word("break")?;
2272 if let Some(label) = opt_label {
2273 self.print_ident(label.ident)?;
2276 if let Some(ref expr) = *opt_expr {
2277 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2281 ast::ExprKind::Continue(opt_label) => {
2282 self.s.word("continue")?;
2284 if let Some(label) = opt_label {
2285 self.print_ident(label.ident)?;
2289 ast::ExprKind::Ret(ref result) => {
2290 self.s.word("return")?;
2291 if let Some(ref expr) = *result {
2293 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2296 ast::ExprKind::InlineAsm(ref a) => {
2297 self.s.word("asm!")?;
2299 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2300 self.word_space(":")?;
2302 self.commasep(Inconsistent, &a.outputs, |s, out| {
2303 let constraint = out.constraint.as_str();
2304 let mut ch = constraint.chars();
2306 Some('=') if out.is_rw => {
2307 s.print_string(&format!("+{}", ch.as_str()),
2308 ast::StrStyle::Cooked)?
2310 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2313 s.print_expr(&out.expr)?;
2318 self.word_space(":")?;
2320 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2321 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2328 self.word_space(":")?;
2330 self.commasep(Inconsistent, &a.clobbers,
2332 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2336 let mut options = vec![];
2338 options.push("volatile");
2341 options.push("alignstack");
2343 if a.dialect == ast::AsmDialect::Intel {
2344 options.push("intel");
2347 if !options.is_empty() {
2349 self.word_space(":")?;
2350 self.commasep(Inconsistent, &options,
2352 s.print_string(co, ast::StrStyle::Cooked)?;
2359 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2360 ast::ExprKind::Paren(ref e) => {
2362 self.print_inner_attributes_inline(attrs)?;
2363 self.print_expr(e)?;
2366 ast::ExprKind::Yield(ref e) => {
2367 self.s.word("yield")?;
2371 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2376 ast::ExprKind::Try(ref e) => {
2377 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2380 ast::ExprKind::TryBlock(ref blk) => {
2383 self.print_block_with_attrs(blk, attrs)?
2386 self.ann.post(self, AnnNode::Expr(expr))?;
2390 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2391 self.print_pat(&loc.pat)?;
2392 if let Some(ref ty) = loc.ty {
2393 self.word_space(":")?;
2394 self.print_type(ty)?;
2399 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2400 if ident.is_raw_guess() {
2401 self.s.word(&format!("r#{}", ident))?;
2403 self.s.word(&ident.as_str())?;
2405 self.ann.post(self, AnnNode::Ident(&ident))
2408 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2409 self.s.word(&i.to_string())
2412 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2413 self.s.word(&name.as_str())?;
2414 self.ann.post(self, AnnNode::Name(&name))
2417 pub fn print_for_decl(&mut self, loc: &ast::Local,
2418 coll: &ast::Expr) -> io::Result<()> {
2419 self.print_local_decl(loc)?;
2421 self.word_space("in")?;
2422 self.print_expr(coll)
2425 fn print_path(&mut self,
2427 colons_before_params: bool,
2431 self.maybe_print_comment(path.span.lo())?;
2433 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2437 self.print_path_segment(segment, colons_before_params)?;
2443 fn print_path_segment(&mut self,
2444 segment: &ast::PathSegment,
2445 colons_before_params: bool)
2448 if segment.ident.name != keywords::CrateRoot.name() &&
2449 segment.ident.name != keywords::DollarCrate.name() {
2450 self.print_ident(segment.ident)?;
2451 if let Some(ref args) = segment.args {
2452 self.print_generic_args(args, colons_before_params)?;
2454 } else if segment.ident.name == keywords::DollarCrate.name() {
2455 self.print_dollar_crate(segment.ident.span.ctxt())?;
2460 fn print_qpath(&mut self,
2463 colons_before_params: bool)
2467 self.print_type(&qself.ty)?;
2468 if qself.position > 0 {
2470 self.word_space("as")?;
2471 let depth = path.segments.len() - qself.position;
2472 self.print_path(path, false, depth)?;
2476 let item_segment = path.segments.last().unwrap();
2477 self.print_ident(item_segment.ident)?;
2478 match item_segment.args {
2479 Some(ref args) => self.print_generic_args(args, colons_before_params),
2484 fn print_generic_args(&mut self,
2485 args: &ast::GenericArgs,
2486 colons_before_params: bool)
2489 if colons_before_params {
2494 ast::GenericArgs::AngleBracketed(ref data) => {
2497 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2498 s.print_generic_arg(generic_arg)
2501 let mut comma = data.args.len() != 0;
2503 for binding in data.bindings.iter() {
2505 self.word_space(",")?
2507 self.print_ident(binding.ident)?;
2509 self.word_space("=")?;
2510 self.print_type(&binding.ty)?;
2517 ast::GenericArgs::Parenthesized(ref data) => {
2522 |s, ty| s.print_type(ty))?;
2525 if let Some(ref ty) = data.output {
2526 self.space_if_not_bol()?;
2527 self.word_space("->")?;
2528 self.print_type(ty)?;
2536 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2537 self.maybe_print_comment(pat.span.lo())?;
2538 self.ann.pre(self, AnnNode::Pat(pat))?;
2539 /* Pat isn't normalized, but the beauty of it
2540 is that it doesn't matter */
2542 PatKind::Wild => self.s.word("_")?,
2543 PatKind::Ident(binding_mode, ident, ref sub) => {
2544 match binding_mode {
2545 ast::BindingMode::ByRef(mutbl) => {
2546 self.word_nbsp("ref")?;
2547 self.print_mutability(mutbl)?;
2549 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2550 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2551 self.word_nbsp("mut")?;
2554 self.print_ident(ident)?;
2555 if let Some(ref p) = *sub {
2560 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2561 self.print_path(path, true, 0)?;
2563 if let Some(ddpos) = ddpos {
2564 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2566 self.word_space(",")?;
2569 if ddpos != elts.len() {
2571 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2574 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2578 PatKind::Path(None, ref path) => {
2579 self.print_path(path, true, 0)?;
2581 PatKind::Path(Some(ref qself), ref path) => {
2582 self.print_qpath(path, qself, false)?;
2584 PatKind::Struct(ref path, ref fields, etc) => {
2585 self.print_path(path, true, 0)?;
2587 self.word_space("{")?;
2589 Consistent, &fields[..],
2591 s.cbox(INDENT_UNIT)?;
2592 if !f.node.is_shorthand {
2593 s.print_ident(f.node.ident)?;
2596 s.print_pat(&f.node.pat)?;
2599 |f| f.node.pat.span)?;
2601 if !fields.is_empty() { self.word_space(",")?; }
2607 PatKind::Tuple(ref elts, ddpos) => {
2609 if let Some(ddpos) = ddpos {
2610 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2612 self.word_space(",")?;
2615 if ddpos != elts.len() {
2617 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2620 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2621 if elts.len() == 1 {
2627 PatKind::Box(ref inner) => {
2628 self.s.word("box ")?;
2629 self.print_pat(inner)?;
2631 PatKind::Ref(ref inner, mutbl) => {
2633 if mutbl == ast::Mutability::Mutable {
2634 self.s.word("mut ")?;
2636 self.print_pat(inner)?;
2638 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2639 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2640 self.print_expr(begin)?;
2643 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2644 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2645 RangeEnd::Excluded => self.s.word("..")?,
2647 self.print_expr(end)?;
2649 PatKind::Slice(ref before, ref slice, ref after) => {
2651 self.commasep(Inconsistent,
2653 |s, p| s.print_pat(p))?;
2654 if let Some(ref p) = *slice {
2655 if !before.is_empty() { self.word_space(",")?; }
2656 if let PatKind::Wild = p.node {
2662 if !after.is_empty() { self.word_space(",")?; }
2664 self.commasep(Inconsistent,
2666 |s, p| s.print_pat(p))?;
2669 PatKind::Paren(ref inner) => {
2671 self.print_pat(inner)?;
2674 PatKind::Mac(ref m) => self.print_mac(m)?,
2676 self.ann.post(self, AnnNode::Pat(pat))
2679 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2680 let mut first = true;
2686 self.word_space("|")?;
2693 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2694 // I have no idea why this check is necessary, but here it
2696 if arm.attrs.is_empty() {
2699 self.cbox(INDENT_UNIT)?;
2701 self.maybe_print_comment(arm.pats[0].span.lo())?;
2702 self.print_outer_attributes(&arm.attrs)?;
2703 self.print_pats(&arm.pats)?;
2705 if let Some(ref e) = arm.guard {
2706 self.word_space("if")?;
2707 self.print_expr(e)?;
2710 self.word_space("=>")?;
2712 match arm.body.node {
2713 ast::ExprKind::Block(ref blk, opt_label) => {
2714 if let Some(label) = opt_label {
2715 self.print_ident(label.ident)?;
2716 self.word_space(":")?;
2719 // the block will close the pattern's ibox
2720 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2722 // If it is a user-provided unsafe block, print a comma after it
2723 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2728 self.end()?; // close the ibox for the pattern
2729 self.print_expr(&arm.body)?;
2733 self.end() // close enclosing cbox
2736 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2737 match explicit_self.node {
2738 SelfKind::Value(m) => {
2739 self.print_mutability(m)?;
2742 SelfKind::Region(ref lt, m) => {
2744 self.print_opt_lifetime(lt)?;
2745 self.print_mutability(m)?;
2748 SelfKind::Explicit(ref typ, m) => {
2749 self.print_mutability(m)?;
2750 self.s.word("self")?;
2751 self.word_space(":")?;
2752 self.print_type(typ)
2757 pub fn print_fn(&mut self,
2759 header: ast::FnHeader,
2760 name: Option<ast::Ident>,
2761 generics: &ast::Generics,
2762 vis: &ast::Visibility) -> io::Result<()> {
2763 self.print_fn_header_info(header, vis)?;
2765 if let Some(name) = name {
2767 self.print_ident(name)?;
2769 self.print_generic_params(&generics.params)?;
2770 self.print_fn_args_and_ret(decl)?;
2771 self.print_where_clause(&generics.where_clause)
2774 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2777 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2779 self.s.word(", ...")?;
2783 self.print_fn_output(decl)
2786 pub fn print_fn_block_args(
2791 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2794 if let ast::FunctionRetTy::Default(..) = decl.output {
2798 self.space_if_not_bol()?;
2799 self.word_space("->")?;
2801 ast::FunctionRetTy::Ty(ref ty) => {
2802 self.print_type(ty)?;
2803 self.maybe_print_comment(ty.span.lo())
2805 ast::FunctionRetTy::Default(..) => unreachable!(),
2809 pub fn print_movability(&mut self, movability: ast::Movability)
2812 ast::Movability::Static => self.word_space("static"),
2813 ast::Movability::Movable => Ok(()),
2817 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2819 if asyncness.is_async() {
2820 self.word_nbsp("async")?;
2825 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2827 match capture_clause {
2828 ast::CaptureBy::Value => self.word_space("move"),
2829 ast::CaptureBy::Ref => Ok(()),
2833 pub fn print_type_bounds(&mut self,
2835 bounds: &[ast::GenericBound])
2837 if !bounds.is_empty() {
2838 self.s.word(prefix)?;
2839 let mut first = true;
2840 for bound in bounds {
2841 if !(first && prefix.is_empty()) {
2847 self.word_space("+")?;
2851 GenericBound::Trait(tref, modifier) => {
2852 if modifier == &TraitBoundModifier::Maybe {
2855 self.print_poly_trait_ref(tref)?;
2857 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2864 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2865 self.print_name(lifetime.ident.name)
2868 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2871 self.print_lifetime(lifetime)?;
2872 if !bounds.is_empty() {
2874 for (i, bound) in bounds.iter().enumerate() {
2876 self.s.word(" + ")?;
2879 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2887 pub fn print_generic_params(
2889 generic_params: &[ast::GenericParam]
2890 ) -> io::Result<()> {
2891 if generic_params.is_empty() {
2897 self.commasep(Inconsistent, &generic_params, |s, param| {
2899 ast::GenericParamKind::Lifetime => {
2900 s.print_outer_attributes_inline(¶m.attrs)?;
2901 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2902 s.print_lifetime_bounds(lt, ¶m.bounds)
2904 ast::GenericParamKind::Type { ref default } => {
2905 s.print_outer_attributes_inline(¶m.attrs)?;
2906 s.print_ident(param.ident)?;
2907 s.print_type_bounds(":", ¶m.bounds)?;
2909 Some(ref default) => {
2912 s.print_type(default)
2924 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2926 if where_clause.predicates.is_empty() {
2931 self.word_space("where")?;
2933 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2935 self.word_space(",")?;
2939 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2940 ref bound_generic_params,
2945 self.print_formal_generic_params(bound_generic_params)?;
2946 self.print_type(bounded_ty)?;
2947 self.print_type_bounds(":", bounds)?;
2949 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2952 self.print_lifetime_bounds(*lifetime, bounds)?;
2954 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2957 self.print_type(lhs_ty)?;
2959 self.word_space("=")?;
2960 self.print_type(rhs_ty)?;
2968 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2970 ast::UseTreeKind::Simple(rename, ..) => {
2971 self.print_path(&tree.prefix, false, 0)?;
2972 if let Some(rename) = rename {
2974 self.word_space("as")?;
2975 self.print_ident(rename)?;
2978 ast::UseTreeKind::Glob => {
2979 if !tree.prefix.segments.is_empty() {
2980 self.print_path(&tree.prefix, false, 0)?;
2985 ast::UseTreeKind::Nested(ref items) => {
2986 if tree.prefix.segments.is_empty() {
2989 self.print_path(&tree.prefix, false, 0)?;
2990 self.s.word("::{")?;
2992 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2993 this.print_use_tree(tree)
3002 pub fn print_mutability(&mut self,
3003 mutbl: ast::Mutability) -> io::Result<()> {
3005 ast::Mutability::Mutable => self.word_nbsp("mut"),
3006 ast::Mutability::Immutable => Ok(()),
3010 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
3011 self.print_mutability(mt.mutbl)?;
3012 self.print_type(&mt.ty)
3015 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
3016 self.ibox(INDENT_UNIT)?;
3017 match input.ty.node {
3018 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
3020 if let Some(eself) = input.to_self() {
3021 self.print_explicit_self(&eself)?;
3023 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
3024 ident.name == keywords::Invalid.name()
3029 self.print_pat(&input.pat)?;
3033 self.print_type(&input.ty)?;
3040 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3041 if let ast::FunctionRetTy::Default(..) = decl.output {
3045 self.space_if_not_bol()?;
3046 self.ibox(INDENT_UNIT)?;
3047 self.word_space("->")?;
3049 ast::FunctionRetTy::Default(..) => unreachable!(),
3050 ast::FunctionRetTy::Ty(ref ty) =>
3051 self.print_type(ty)?
3056 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3061 pub fn print_ty_fn(&mut self,
3063 unsafety: ast::Unsafety,
3065 name: Option<ast::Ident>,
3066 generic_params: &[ast::GenericParam])
3068 self.ibox(INDENT_UNIT)?;
3069 if !generic_params.is_empty() {
3070 self.s.word("for")?;
3071 self.print_generic_params(generic_params)?;
3073 let generics = ast::Generics {
3075 where_clause: ast::WhereClause {
3076 id: ast::DUMMY_NODE_ID,
3077 predicates: Vec::new(),
3078 span: syntax_pos::DUMMY_SP,
3080 span: syntax_pos::DUMMY_SP,
3083 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3086 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3090 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3091 next_pos: Option<BytePos>)
3093 let cm = match self.cm {
3097 if let Some(ref cmnt) = self.next_comment() {
3098 if cmnt.style != comments::Trailing { return Ok(()) }
3099 let span_line = cm.lookup_char_pos(span.hi());
3100 let comment_line = cm.lookup_char_pos(cmnt.pos);
3101 let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3102 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3103 self.print_comment(cmnt)?;
3109 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3110 // If there aren't any remaining comments, then we need to manually
3111 // make sure there is a line break at the end.
3112 if self.next_comment().is_none() {
3113 self.s.hardbreak()?;
3115 while let Some(ref cmnt) = self.next_comment() {
3116 self.print_comment(cmnt)?;
3121 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3122 opt_abi: Option<Abi>)
3125 Some(Abi::Rust) => Ok(()),
3127 self.word_nbsp("extern")?;
3128 self.word_nbsp(&abi.to_string())
3134 pub fn print_extern_opt_abi(&mut self,
3135 opt_abi: Option<Abi>) -> io::Result<()> {
3138 self.word_nbsp("extern")?;
3139 self.word_nbsp(&abi.to_string())
3145 pub fn print_fn_header_info(&mut self,
3146 header: ast::FnHeader,
3147 vis: &ast::Visibility) -> io::Result<()> {
3148 self.s.word(&visibility_qualified(vis, ""))?;
3150 match header.constness.node {
3151 ast::Constness::NotConst => {}
3152 ast::Constness::Const => self.word_nbsp("const")?
3155 self.print_asyncness(header.asyncness)?;
3156 self.print_unsafety(header.unsafety)?;
3158 if header.abi != Abi::Rust {
3159 self.word_nbsp("extern")?;
3160 self.word_nbsp(&header.abi.to_string())?;
3166 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3168 ast::Unsafety::Normal => Ok(()),
3169 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3173 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3175 ast::IsAuto::Yes => self.word_nbsp("auto"),
3176 ast::IsAuto::No => Ok(()),
3191 fn test_fun_to_string() {
3193 let abba_ident = ast::Ident::from_str("abba");
3195 let decl = ast::FnDecl {
3197 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3200 let generics = ast::Generics::default();
3205 unsafety: ast::Unsafety::Normal,
3206 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3207 asyncness: ast::IsAsync::NotAsync,
3219 fn test_variant_to_string() {
3221 let ident = ast::Ident::from_str("principal_skinner");
3223 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3226 // making this up as I go.... ?
3227 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3231 let varstr = variant_to_string(&var);
3232 assert_eq!(varstr, "principal_skinner");