1 // ignore-tidy-filelength
3 use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
4 use crate::ast::{SelfKind, GenericBound, TraitBoundModifier};
5 use crate::ast::{Attribute, MacDelimiter, GenericArg};
6 use crate::util::parser::{self, AssocOp, Fixity};
8 use crate::source_map::{self, SourceMap, Spanned};
9 use crate::parse::token::{self, BinOpToken, Nonterminal, Token};
10 use crate::parse::lexer::comments;
11 use crate::parse::{self, ParseSess};
12 use crate::print::pp::{self, Breaks};
13 use crate::print::pp::Breaks::{Consistent, Inconsistent};
15 use crate::std_inject;
16 use crate::symbol::{keywords, sym};
17 use crate::tokenstream::{self, TokenStream, TokenTree};
19 use rustc_target::spec::abi::{self, Abi};
20 use syntax_pos::{self, BytePos};
21 use syntax_pos::{DUMMY_SP, FileName};
24 use std::io::{self, Write, Read};
27 pub enum AnnNode<'a> {
28 Ident(&'a ast::Ident),
30 Block(&'a ast::Block),
38 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> { Ok(()) }
39 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> { Ok(()) }
42 #[derive(Copy, Clone)]
45 impl PpAnn for NoAnn {}
47 pub struct State<'a> {
48 pub s: pp::Printer<'a>,
49 cm: Option<&'a SourceMap>,
50 comments: Option<Vec<comments::Comment>>,
52 boxes: Vec<pp::Breaks>,
53 ann: &'a (dyn PpAnn+'a),
57 fn rust_printer<'a>(writer: Box<dyn Write+'a>, ann: &'a dyn PpAnn) -> State<'a> {
59 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
69 pub const INDENT_UNIT: usize = 4;
71 pub const DEFAULT_COLUMNS: usize = 78;
73 /// Requires you to pass an input filename and reader so that
74 /// it can scan the input text for comments to copy forward.
75 pub fn print_crate<'a>(cm: &'a SourceMap,
80 out: Box<dyn Write+'a>,
82 is_expanded: bool) -> io::Result<()> {
83 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
85 if is_expanded && std_inject::injected_crate_name().is_some() {
86 // We need to print `#![no_std]` (and its feature gate) so that
87 // compiling pretty-printed source won't inject libstd again.
88 // However we don't want these attributes in the AST because
89 // of the feature gate, so we fake them up here.
91 // #![feature(prelude_import)]
92 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_empty_ctxt(sym::prelude_import));
93 let list = attr::mk_list_item(
94 DUMMY_SP, ast::Ident::with_empty_ctxt(sym::feature), vec![pi_nested]);
95 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
96 s.print_attribute(&fake_attr)?;
99 let no_std_meta = attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::no_std));
100 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
101 s.print_attribute(&fake_attr)?;
104 s.print_mod(&krate.module, &krate.attrs)?;
105 s.print_remaining_comments()?;
110 pub fn new_from_input(cm: &'a SourceMap,
113 input: &mut dyn Read,
114 out: Box<dyn Write+'a>,
116 is_expanded: bool) -> State<'a> {
117 let comments = comments::gather_comments(sess, filename, input);
118 State::new(cm, out, ann, Some(comments), is_expanded)
121 pub fn new(cm: &'a SourceMap,
122 out: Box<dyn Write+'a>,
124 comments: Option<Vec<comments::Comment>>,
125 is_expanded: bool) -> State<'a> {
127 s: pp::mk_printer(out, DEFAULT_COLUMNS),
138 pub fn to_string<F>(f: F) -> String where
139 F: FnOnce(&mut State<'_>) -> io::Result<()>,
141 let mut wr = Vec::new();
144 let mut printer = rust_printer(Box::new(&mut wr), &ann);
145 f(&mut printer).unwrap();
146 printer.s.eof().unwrap();
148 String::from_utf8(wr).unwrap()
151 fn binop_to_string(op: BinOpToken) -> &'static str {
157 token::Percent => "%",
166 pub fn literal_to_string(lit: token::Lit, suffix: Option<ast::Name>) -> String {
167 let mut out = match lit {
168 token::Byte(b) => format!("b'{}'", b),
169 token::Char(c) => format!("'{}'", c),
170 token::Err(c) => format!("'{}'", c),
173 token::Integer(c) => c.to_string(),
174 token::Str_(s) => format!("\"{}\"", s),
175 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
176 delim="#".repeat(n as usize),
178 token::ByteStr(v) => format!("b\"{}\"", v),
179 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
180 delim="#".repeat(n as usize),
184 if let Some(suffix) = suffix {
185 out.push_str(&suffix.as_str())
191 pub fn token_to_string(tok: &Token) -> String {
193 token::Eq => "=".to_string(),
194 token::Lt => "<".to_string(),
195 token::Le => "<=".to_string(),
196 token::EqEq => "==".to_string(),
197 token::Ne => "!=".to_string(),
198 token::Ge => ">=".to_string(),
199 token::Gt => ">".to_string(),
200 token::Not => "!".to_string(),
201 token::Tilde => "~".to_string(),
202 token::OrOr => "||".to_string(),
203 token::AndAnd => "&&".to_string(),
204 token::BinOp(op) => binop_to_string(op).to_string(),
205 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
207 /* Structural symbols */
208 token::At => "@".to_string(),
209 token::Dot => ".".to_string(),
210 token::DotDot => "..".to_string(),
211 token::DotDotDot => "...".to_string(),
212 token::DotDotEq => "..=".to_string(),
213 token::Comma => ",".to_string(),
214 token::Semi => ";".to_string(),
215 token::Colon => ":".to_string(),
216 token::ModSep => "::".to_string(),
217 token::RArrow => "->".to_string(),
218 token::LArrow => "<-".to_string(),
219 token::FatArrow => "=>".to_string(),
220 token::OpenDelim(token::Paren) => "(".to_string(),
221 token::CloseDelim(token::Paren) => ")".to_string(),
222 token::OpenDelim(token::Bracket) => "[".to_string(),
223 token::CloseDelim(token::Bracket) => "]".to_string(),
224 token::OpenDelim(token::Brace) => "{".to_string(),
225 token::CloseDelim(token::Brace) => "}".to_string(),
226 token::OpenDelim(token::NoDelim) |
227 token::CloseDelim(token::NoDelim) => " ".to_string(),
228 token::Pound => "#".to_string(),
229 token::Dollar => "$".to_string(),
230 token::Question => "?".to_string(),
231 token::SingleQuote => "'".to_string(),
234 token::Literal(lit, suf) => literal_to_string(lit, suf),
236 /* Name components */
237 token::Ident(s, false) => s.to_string(),
238 token::Ident(s, true) => format!("r#{}", s),
239 token::Lifetime(s) => s.to_string(),
242 token::DocComment(s) => s.to_string(),
243 token::Eof => "<eof>".to_string(),
244 token::Whitespace => " ".to_string(),
245 token::Comment => "/* */".to_string(),
246 token::Shebang(s) => format!("/* shebang: {}*/", s),
248 token::Interpolated(ref nt) => nonterminal_to_string(nt),
252 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
254 token::NtExpr(ref e) => expr_to_string(e),
255 token::NtMeta(ref e) => meta_item_to_string(e),
256 token::NtTy(ref e) => ty_to_string(e),
257 token::NtPath(ref e) => path_to_string(e),
258 token::NtItem(ref e) => item_to_string(e),
259 token::NtBlock(ref e) => block_to_string(e),
260 token::NtStmt(ref e) => stmt_to_string(e),
261 token::NtPat(ref e) => pat_to_string(e),
262 token::NtIdent(e, false) => ident_to_string(e),
263 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
264 token::NtLifetime(e) => ident_to_string(e),
265 token::NtLiteral(ref e) => expr_to_string(e),
266 token::NtTT(ref tree) => tt_to_string(tree.clone()),
267 token::NtImplItem(ref e) => impl_item_to_string(e),
268 token::NtTraitItem(ref e) => trait_item_to_string(e),
269 token::NtVis(ref e) => vis_to_string(e),
270 token::NtForeignItem(ref e) => foreign_item_to_string(e),
274 pub fn ty_to_string(ty: &ast::Ty) -> String {
275 to_string(|s| s.print_type(ty))
278 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
279 to_string(|s| s.print_type_bounds("", bounds))
282 pub fn pat_to_string(pat: &ast::Pat) -> String {
283 to_string(|s| s.print_pat(pat))
286 pub fn arm_to_string(arm: &ast::Arm) -> String {
287 to_string(|s| s.print_arm(arm))
290 pub fn expr_to_string(e: &ast::Expr) -> String {
291 to_string(|s| s.print_expr(e))
294 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
295 to_string(|s| s.print_lifetime(*lt))
298 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
299 to_string(|s| s.print_tt(tt))
302 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
303 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
306 pub fn tokens_to_string(tokens: TokenStream) -> String {
307 to_string(|s| s.print_tts(tokens))
310 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
311 to_string(|s| s.print_stmt(stmt))
314 pub fn attr_to_string(attr: &ast::Attribute) -> String {
315 to_string(|s| s.print_attribute(attr))
318 pub fn item_to_string(i: &ast::Item) -> String {
319 to_string(|s| s.print_item(i))
322 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
323 to_string(|s| s.print_impl_item(i))
326 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
327 to_string(|s| s.print_trait_item(i))
330 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
331 to_string(|s| s.print_generic_params(generic_params))
334 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
335 to_string(|s| s.print_where_clause(i))
338 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
339 to_string(|s| s.print_fn_block_args(p))
342 pub fn path_to_string(p: &ast::Path) -> String {
343 to_string(|s| s.print_path(p, false, 0))
346 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
347 to_string(|s| s.print_path_segment(p, false))
350 pub fn ident_to_string(id: ast::Ident) -> String {
351 to_string(|s| s.print_ident(id))
354 pub fn vis_to_string(v: &ast::Visibility) -> String {
355 to_string(|s| s.print_visibility(v))
358 pub fn fun_to_string(decl: &ast::FnDecl,
359 header: &ast::FnHeader,
361 generics: &ast::Generics)
365 s.print_fn(decl, header, Some(name),
366 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
367 s.end()?; // Close the head box
368 s.end() // Close the outer box
372 pub fn block_to_string(blk: &ast::Block) -> String {
374 // containing cbox, will be closed by print-block at }
375 s.cbox(INDENT_UNIT)?;
376 // head-ibox, will be closed by print-block after {
382 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
383 to_string(|s| s.print_meta_list_item(li))
386 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
387 to_string(|s| s.print_meta_item(mi))
390 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
391 to_string(|s| s.print_attribute(attr))
394 pub fn lit_to_string(l: &ast::Lit) -> String {
395 to_string(|s| s.print_literal(l))
398 pub fn variant_to_string(var: &ast::Variant) -> String {
399 to_string(|s| s.print_variant(var))
402 pub fn arg_to_string(arg: &ast::Arg) -> String {
403 to_string(|s| s.print_arg(arg, false))
406 pub fn mac_to_string(arg: &ast::Mac) -> String {
407 to_string(|s| s.print_mac(arg))
410 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
411 to_string(|s| s.print_foreign_item(arg))
414 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
415 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
418 pub trait PrintState<'a> {
419 fn writer(&mut self) -> &mut pp::Printer<'a>;
420 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
421 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
422 fn cur_cmnt(&mut self) -> &mut usize;
424 fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
425 self.writer().word(w)?;
426 self.writer().space()
429 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
431 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
433 fn is_begin(&mut self) -> bool {
434 match self.writer().last_token() {
435 pp::Token::Begin(_) => true,
440 fn is_end(&mut self) -> bool {
441 match self.writer().last_token() {
442 pp::Token::End => true,
447 // is this the beginning of a line?
448 fn is_bol(&mut self) -> bool {
449 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
452 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
454 self.writer().hardbreak()?
460 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
461 self.boxes().push(b);
462 self.writer().rbox(u, b)
465 fn ibox(&mut self, u: usize) -> io::Result<()> {
466 self.boxes().push(pp::Breaks::Inconsistent);
467 self.writer().ibox(u)
470 fn end(&mut self) -> io::Result<()> {
471 self.boxes().pop().unwrap();
475 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
476 where F: FnMut(&mut Self, &T) -> io::Result<()>,
479 let mut first = true;
481 if first { first = false; } else { self.word_space(",")?; }
487 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
488 while let Some(ref cmnt) = self.next_comment() {
490 self.print_comment(cmnt)?;
498 fn print_comment(&mut self,
499 cmnt: &comments::Comment) -> io::Result<()> {
500 let r = match cmnt.style {
502 assert_eq!(cmnt.lines.len(), 1);
503 self.writer().zerobreak()?;
504 self.writer().word(cmnt.lines[0].clone())?;
505 self.writer().zerobreak()
507 comments::Isolated => {
508 self.hardbreak_if_not_bol()?;
509 for line in &cmnt.lines {
510 // Don't print empty lines because they will end up as trailing
512 if !line.is_empty() {
513 self.writer().word(line.clone())?;
515 self.writer().hardbreak()?;
519 comments::Trailing => {
521 self.writer().word(" ")?;
523 if cmnt.lines.len() == 1 {
524 self.writer().word(cmnt.lines[0].clone())?;
525 self.writer().hardbreak()
528 for line in &cmnt.lines {
529 if !line.is_empty() {
530 self.writer().word(line.clone())?;
532 self.writer().hardbreak()?;
537 comments::BlankLine => {
538 // We need to do at least one, possibly two hardbreaks.
539 let is_semi = match self.writer().last_token() {
540 pp::Token::String(s, _) => ";" == s,
543 if is_semi || self.is_begin() || self.is_end() {
544 self.writer().hardbreak()?;
546 self.writer().hardbreak()
551 *self.cur_cmnt() = *self.cur_cmnt() + 1;
558 fn next_comment(&mut self) -> Option<comments::Comment> {
559 let cur_cmnt = *self.cur_cmnt();
560 match *self.comments() {
562 if cur_cmnt < cmnts.len() {
563 Some(cmnts[cur_cmnt].clone())
572 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
573 self.maybe_print_comment(lit.span.lo())?;
574 self.writer().word(literal_to_string(lit.token, lit.suffix))
577 fn print_string(&mut self, st: &str,
578 style: ast::StrStyle) -> io::Result<()> {
579 let st = match style {
580 ast::StrStyle::Cooked => {
581 (format!("\"{}\"", st.escape_debug()))
583 ast::StrStyle::Raw(n) => {
584 (format!("r{delim}\"{string}\"{delim}",
585 delim="#".repeat(n as usize),
589 self.writer().word(st)
592 fn print_inner_attributes(&mut self,
593 attrs: &[ast::Attribute]) -> io::Result<()> {
594 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
597 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
598 attrs: &[ast::Attribute])
600 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
603 fn print_outer_attributes(&mut self,
604 attrs: &[ast::Attribute]) -> io::Result<()> {
605 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
608 fn print_inner_attributes_inline(&mut self,
609 attrs: &[ast::Attribute]) -> io::Result<()> {
610 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
613 fn print_outer_attributes_inline(&mut self,
614 attrs: &[ast::Attribute]) -> io::Result<()> {
615 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
618 fn print_either_attributes(&mut self,
619 attrs: &[ast::Attribute],
620 kind: ast::AttrStyle,
622 trailing_hardbreak: bool) -> io::Result<()> {
625 if attr.style == kind {
626 self.print_attribute_inline(attr, is_inline)?;
633 if count > 0 && trailing_hardbreak && !is_inline {
634 self.hardbreak_if_not_bol()?;
639 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
640 for (i, segment) in path.segments.iter().enumerate() {
642 self.writer().word("::")?
644 if segment.ident.name != keywords::PathRoot.name() {
645 if segment.ident.name == keywords::DollarCrate.name() {
646 self.print_dollar_crate(segment.ident)?;
648 self.writer().word(segment.ident.as_str().to_string())?;
655 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
656 self.print_attribute_inline(attr, false)
659 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
660 is_inline: bool) -> io::Result<()> {
662 self.hardbreak_if_not_bol()?;
664 self.maybe_print_comment(attr.span.lo())?;
665 if attr.is_sugared_doc {
666 self.writer().word(attr.value_str().unwrap().as_str().to_string())?;
667 self.writer().hardbreak()
670 ast::AttrStyle::Inner => self.writer().word("#![")?,
671 ast::AttrStyle::Outer => self.writer().word("#[")?,
673 if let Some(mi) = attr.meta() {
674 self.print_meta_item(&mi)?
676 self.print_attribute_path(&attr.path)?;
677 self.writer().space()?;
678 self.print_tts(attr.tokens.clone())?;
680 self.writer().word("]")
684 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
686 ast::NestedMetaItem::MetaItem(ref mi) => {
687 self.print_meta_item(mi)
689 ast::NestedMetaItem::Literal(ref lit) => {
690 self.print_literal(lit)
695 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
696 self.ibox(INDENT_UNIT)?;
698 ast::MetaItemKind::Word => self.print_attribute_path(&item.path)?,
699 ast::MetaItemKind::NameValue(ref value) => {
700 self.print_attribute_path(&item.path)?;
701 self.writer().space()?;
702 self.word_space("=")?;
703 self.print_literal(value)?;
705 ast::MetaItemKind::List(ref items) => {
706 self.print_attribute_path(&item.path)?;
708 self.commasep(Consistent,
710 |s, i| s.print_meta_list_item(i))?;
717 /// This doesn't deserve to be called "pretty" printing, but it should be
718 /// meaning-preserving. A quick hack that might help would be to look at the
719 /// spans embedded in the TTs to decide where to put spaces and newlines.
720 /// But it'd be better to parse these according to the grammar of the
721 /// appropriate macro, transcribe back into the grammar we just parsed from,
722 /// and then pretty-print the resulting AST nodes (so, e.g., we print
723 /// expression arguments as expressions). It can be done! I think.
724 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
726 TokenTree::Token(_, ref tk) => {
727 self.writer().word(token_to_string(tk))?;
729 parse::token::DocComment(..) => {
730 self.writer().hardbreak()
735 TokenTree::Delimited(_, delim, tts) => {
736 self.writer().word(token_to_string(&token::OpenDelim(delim)))?;
737 self.writer().space()?;
738 self.print_tts(tts)?;
739 self.writer().space()?;
740 self.writer().word(token_to_string(&token::CloseDelim(delim)))
745 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
747 for (i, tt) in tts.into_trees().enumerate() {
749 self.writer().space()?;
756 fn space_if_not_bol(&mut self) -> io::Result<()> {
757 if !self.is_bol() { self.writer().space()?; }
761 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
763 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
764 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
765 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
766 // So we need to somehow pretty-print `$crate` in paths in a way preserving at least some of
767 // its hygiene data, most importantly name of the crate it refers to.
768 // As a result we print `$crate` as `crate` if it refers to the local crate
769 // and as `::other_crate_name` if it refers to some other crate.
770 fn print_dollar_crate(&mut self, ident: ast::Ident) -> io::Result<()> {
771 let name = ident.span.ctxt().dollar_crate_name();
772 if !ast::Ident::with_empty_ctxt(name).is_path_segment_keyword() {
773 self.writer().word("::")?;
775 self.writer().word(name.as_str().to_string())
779 impl<'a> PrintState<'a> for State<'a> {
780 fn writer(&mut self) -> &mut pp::Printer<'a> {
784 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
788 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
792 fn cur_cmnt(&mut self) -> &mut usize {
798 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
799 self.boxes.push(pp::Breaks::Consistent);
803 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
808 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
810 // outer-box is consistent
811 self.cbox(INDENT_UNIT)?;
812 // head-box is inconsistent
813 self.ibox(w.len() + 1)?;
814 // keyword that starts the head
821 pub fn bopen(&mut self) -> io::Result<()> {
823 self.end() // close the head-box
826 pub fn bclose_(&mut self, span: syntax_pos::Span,
827 indented: usize) -> io::Result<()> {
828 self.bclose_maybe_open(span, indented, true)
830 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
831 indented: usize, close_box: bool) -> io::Result<()> {
832 self.maybe_print_comment(span.hi())?;
833 self.break_offset_if_not_bol(1, -(indented as isize))?;
836 self.end()?; // close the outer-box
840 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
841 self.bclose_(span, INDENT_UNIT)
844 pub fn in_cbox(&self) -> bool {
845 match self.boxes.last() {
846 Some(&last_box) => last_box == pp::Breaks::Consistent,
851 pub fn break_offset_if_not_bol(&mut self, n: usize,
852 off: isize) -> io::Result<()> {
854 self.s.break_offset(n, off)
856 if off != 0 && self.s.last_token().is_hardbreak_tok() {
857 // We do something pretty sketchy here: tuck the nonzero
858 // offset-adjustment we were going to deposit along with the
859 // break into the previous hardbreak.
860 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
866 // Synthesizes a comment that was not textually present in the original source
868 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
878 pub fn commasep_cmnt<T, F, G>(&mut self,
882 mut get_span: G) -> io::Result<()> where
883 F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
884 G: FnMut(&T) -> syntax_pos::Span,
887 let len = elts.len();
890 self.maybe_print_comment(get_span(elt).hi())?;
895 self.maybe_print_trailing_comment(get_span(elt),
896 Some(get_span(&elts[i]).hi()))?;
897 self.space_if_not_bol()?;
903 pub fn commasep_exprs(&mut self, b: Breaks,
904 exprs: &[P<ast::Expr>]) -> io::Result<()> {
905 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
908 pub fn print_mod(&mut self, _mod: &ast::Mod,
909 attrs: &[ast::Attribute]) -> io::Result<()> {
910 self.print_inner_attributes(attrs)?;
911 for item in &_mod.items {
912 self.print_item(item)?;
917 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
918 attrs: &[ast::Attribute]) -> io::Result<()> {
919 self.print_inner_attributes(attrs)?;
920 for item in &nmod.items {
921 self.print_foreign_item(item)?;
926 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
927 if let Some(lt) = *lifetime {
928 self.print_lifetime(lt)?;
934 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
936 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
937 GenericArg::Type(ty) => self.print_type(ty),
938 GenericArg::Const(ct) => self.print_expr(&ct.value),
942 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
943 self.maybe_print_comment(ty.span.lo())?;
946 ast::TyKind::Slice(ref ty) => {
948 self.print_type(ty)?;
951 ast::TyKind::Ptr(ref mt) => {
954 ast::Mutability::Mutable => self.word_nbsp("mut")?,
955 ast::Mutability::Immutable => self.word_nbsp("const")?,
957 self.print_type(&mt.ty)?;
959 ast::TyKind::Rptr(ref lifetime, ref mt) => {
961 self.print_opt_lifetime(lifetime)?;
964 ast::TyKind::Never => {
967 ast::TyKind::Tup(ref elts) => {
969 self.commasep(Inconsistent, &elts[..],
970 |s, ty| s.print_type(ty))?;
976 ast::TyKind::Paren(ref typ) => {
978 self.print_type(typ)?;
981 ast::TyKind::BareFn(ref f) => {
982 self.print_ty_fn(f.abi,
988 ast::TyKind::Path(None, ref path) => {
989 self.print_path(path, false, 0)?;
991 ast::TyKind::Path(Some(ref qself), ref path) => {
992 self.print_qpath(path, qself, false)?
994 ast::TyKind::TraitObject(ref bounds, syntax) => {
995 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
996 self.print_type_bounds(prefix, &bounds[..])?;
998 ast::TyKind::ImplTrait(_, ref bounds) => {
999 self.print_type_bounds("impl", &bounds[..])?;
1001 ast::TyKind::Array(ref ty, ref length) => {
1003 self.print_type(ty)?;
1005 self.print_expr(&length.value)?;
1008 ast::TyKind::Typeof(ref e) => {
1009 self.s.word("typeof(")?;
1010 self.print_expr(&e.value)?;
1013 ast::TyKind::Infer => {
1016 ast::TyKind::Err => {
1018 self.s.word("/*ERROR*/")?;
1021 ast::TyKind::ImplicitSelf => {
1022 self.s.word("Self")?;
1024 ast::TyKind::Mac(ref m) => {
1027 ast::TyKind::CVarArgs => {
1028 self.s.word("...")?;
1034 pub fn print_foreign_item(&mut self,
1035 item: &ast::ForeignItem) -> io::Result<()> {
1036 self.hardbreak_if_not_bol()?;
1037 self.maybe_print_comment(item.span.lo())?;
1038 self.print_outer_attributes(&item.attrs)?;
1040 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1042 self.print_fn(decl, &ast::FnHeader::default(),
1044 generics, &item.vis)?;
1045 self.end()?; // end head-ibox
1047 self.end() // end the outer fn box
1049 ast::ForeignItemKind::Static(ref t, m) => {
1050 self.head(visibility_qualified(&item.vis, "static"))?;
1051 if m == ast::Mutability::Mutable {
1052 self.word_space("mut")?;
1054 self.print_ident(item.ident)?;
1055 self.word_space(":")?;
1056 self.print_type(t)?;
1058 self.end()?; // end the head-ibox
1059 self.end() // end the outer cbox
1061 ast::ForeignItemKind::Ty => {
1062 self.head(visibility_qualified(&item.vis, "type"))?;
1063 self.print_ident(item.ident)?;
1065 self.end()?; // end the head-ibox
1066 self.end() // end the outer cbox
1068 ast::ForeignItemKind::Macro(ref m) => {
1070 match m.node.delim {
1071 MacDelimiter::Brace => Ok(()),
1072 _ => self.s.word(";")
1078 fn print_associated_const(&mut self,
1081 default: Option<&ast::Expr>,
1082 vis: &ast::Visibility)
1085 self.s.word(visibility_qualified(vis, ""))?;
1086 self.word_space("const")?;
1087 self.print_ident(ident)?;
1088 self.word_space(":")?;
1089 self.print_type(ty)?;
1090 if let Some(expr) = default {
1092 self.word_space("=")?;
1093 self.print_expr(expr)?;
1098 fn print_associated_type(&mut self,
1100 bounds: Option<&ast::GenericBounds>,
1101 ty: Option<&ast::Ty>)
1103 self.word_space("type")?;
1104 self.print_ident(ident)?;
1105 if let Some(bounds) = bounds {
1106 self.print_type_bounds(":", bounds)?;
1108 if let Some(ty) = ty {
1110 self.word_space("=")?;
1111 self.print_type(ty)?;
1116 /// Pretty-print an item
1117 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1118 self.hardbreak_if_not_bol()?;
1119 self.maybe_print_comment(item.span.lo())?;
1120 self.print_outer_attributes(&item.attrs)?;
1121 self.ann.pre(self, AnnNode::Item(item))?;
1123 ast::ItemKind::ExternCrate(orig_name) => {
1124 self.head(visibility_qualified(&item.vis, "extern crate"))?;
1125 if let Some(orig_name) = orig_name {
1126 self.print_name(orig_name)?;
1131 self.print_ident(item.ident)?;
1133 self.end()?; // end inner head-block
1134 self.end()?; // end outer head-block
1136 ast::ItemKind::Use(ref tree) => {
1137 self.head(visibility_qualified(&item.vis, "use"))?;
1138 self.print_use_tree(tree)?;
1140 self.end()?; // end inner head-block
1141 self.end()?; // end outer head-block
1143 ast::ItemKind::Static(ref ty, m, ref expr) => {
1144 self.head(visibility_qualified(&item.vis, "static"))?;
1145 if m == ast::Mutability::Mutable {
1146 self.word_space("mut")?;
1148 self.print_ident(item.ident)?;
1149 self.word_space(":")?;
1150 self.print_type(ty)?;
1152 self.end()?; // end the head-ibox
1154 self.word_space("=")?;
1155 self.print_expr(expr)?;
1157 self.end()?; // end the outer cbox
1159 ast::ItemKind::Const(ref ty, ref expr) => {
1160 self.head(visibility_qualified(&item.vis, "const"))?;
1161 self.print_ident(item.ident)?;
1162 self.word_space(":")?;
1163 self.print_type(ty)?;
1165 self.end()?; // end the head-ibox
1167 self.word_space("=")?;
1168 self.print_expr(expr)?;
1170 self.end()?; // end the outer cbox
1172 ast::ItemKind::Fn(ref decl, ref header, ref param_names, ref body) => {
1182 self.print_block_with_attrs(body, &item.attrs)?;
1184 ast::ItemKind::Mod(ref _mod) => {
1185 self.head(visibility_qualified(&item.vis, "mod"))?;
1186 self.print_ident(item.ident)?;
1188 if _mod.inline || self.is_expanded {
1191 self.print_mod(_mod, &item.attrs)?;
1192 self.bclose(item.span)?;
1195 self.end()?; // end inner head-block
1196 self.end()?; // end outer head-block
1200 ast::ItemKind::ForeignMod(ref nmod) => {
1201 self.head("extern")?;
1202 self.word_nbsp(nmod.abi.to_string())?;
1204 self.print_foreign_mod(nmod, &item.attrs)?;
1205 self.bclose(item.span)?;
1207 ast::ItemKind::GlobalAsm(ref ga) => {
1208 self.head(visibility_qualified(&item.vis, "global_asm!"))?;
1209 self.s.word(ga.asm.as_str().to_string())?;
1212 ast::ItemKind::Ty(ref ty, ref generics) => {
1213 self.head(visibility_qualified(&item.vis, "type"))?;
1214 self.print_ident(item.ident)?;
1215 self.print_generic_params(&generics.params)?;
1216 self.end()?; // end the inner ibox
1218 self.print_where_clause(&generics.where_clause)?;
1220 self.word_space("=")?;
1221 self.print_type(ty)?;
1223 self.end()?; // end the outer ibox
1225 ast::ItemKind::Existential(ref bounds, ref generics) => {
1226 self.head(visibility_qualified(&item.vis, "existential type"))?;
1227 self.print_ident(item.ident)?;
1228 self.print_generic_params(&generics.params)?;
1229 self.end()?; // end the inner ibox
1231 self.print_where_clause(&generics.where_clause)?;
1233 self.print_type_bounds(":", bounds)?;
1235 self.end()?; // end the outer ibox
1237 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1238 self.print_enum_def(
1246 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1247 self.head(visibility_qualified(&item.vis, "struct"))?;
1248 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1250 ast::ItemKind::Union(ref struct_def, ref generics) => {
1251 self.head(visibility_qualified(&item.vis, "union"))?;
1252 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1254 ast::ItemKind::Impl(unsafety,
1260 ref impl_items) => {
1262 self.print_visibility(&item.vis)?;
1263 self.print_defaultness(defaultness)?;
1264 self.print_unsafety(unsafety)?;
1265 self.word_nbsp("impl")?;
1267 if !generics.params.is_empty() {
1268 self.print_generic_params(&generics.params)?;
1272 if polarity == ast::ImplPolarity::Negative {
1276 if let Some(ref t) = *opt_trait {
1277 self.print_trait_ref(t)?;
1279 self.word_space("for")?;
1282 self.print_type(ty)?;
1283 self.print_where_clause(&generics.where_clause)?;
1287 self.print_inner_attributes(&item.attrs)?;
1288 for impl_item in impl_items {
1289 self.print_impl_item(impl_item)?;
1291 self.bclose(item.span)?;
1293 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1295 self.print_visibility(&item.vis)?;
1296 self.print_unsafety(unsafety)?;
1297 self.print_is_auto(is_auto)?;
1298 self.word_nbsp("trait")?;
1299 self.print_ident(item.ident)?;
1300 self.print_generic_params(&generics.params)?;
1301 let mut real_bounds = Vec::with_capacity(bounds.len());
1302 for b in bounds.iter() {
1303 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1305 self.word_space("for ?")?;
1306 self.print_trait_ref(&ptr.trait_ref)?;
1308 real_bounds.push(b.clone());
1311 self.print_type_bounds(":", &real_bounds[..])?;
1312 self.print_where_clause(&generics.where_clause)?;
1315 for trait_item in trait_items {
1316 self.print_trait_item(trait_item)?;
1318 self.bclose(item.span)?;
1320 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1322 self.print_visibility(&item.vis)?;
1323 self.word_nbsp("trait")?;
1324 self.print_ident(item.ident)?;
1325 self.print_generic_params(&generics.params)?;
1326 let mut real_bounds = Vec::with_capacity(bounds.len());
1327 // FIXME(durka) this seems to be some quite outdated syntax
1328 for b in bounds.iter() {
1329 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1331 self.word_space("for ?")?;
1332 self.print_trait_ref(&ptr.trait_ref)?;
1334 real_bounds.push(b.clone());
1338 self.print_type_bounds("=", &real_bounds[..])?;
1339 self.print_where_clause(&generics.where_clause)?;
1342 ast::ItemKind::Mac(ref mac) => {
1343 if item.ident.name == keywords::Invalid.name() {
1344 self.print_mac(mac)?;
1345 match mac.node.delim {
1346 MacDelimiter::Brace => {}
1347 _ => self.s.word(";")?,
1350 self.print_path(&mac.node.path, false, 0)?;
1352 self.print_ident(item.ident)?;
1353 self.cbox(INDENT_UNIT)?;
1355 self.print_tts(mac.node.stream())?;
1361 ast::ItemKind::MacroDef(ref tts) => {
1362 self.s.word("macro_rules! ")?;
1363 self.print_ident(item.ident)?;
1364 self.cbox(INDENT_UNIT)?;
1366 self.print_tts(tts.stream())?;
1372 self.ann.post(self, AnnNode::Item(item))
1375 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1376 self.print_path(&t.path, false, 0)
1379 fn print_formal_generic_params(
1381 generic_params: &[ast::GenericParam]
1382 ) -> io::Result<()> {
1383 if !generic_params.is_empty() {
1384 self.s.word("for")?;
1385 self.print_generic_params(generic_params)?;
1391 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1392 self.print_formal_generic_params(&t.bound_generic_params)?;
1393 self.print_trait_ref(&t.trait_ref)
1396 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1397 generics: &ast::Generics, ident: ast::Ident,
1398 span: syntax_pos::Span,
1399 visibility: &ast::Visibility) -> io::Result<()> {
1400 self.head(visibility_qualified(visibility, "enum"))?;
1401 self.print_ident(ident)?;
1402 self.print_generic_params(&generics.params)?;
1403 self.print_where_clause(&generics.where_clause)?;
1405 self.print_variants(&enum_definition.variants, span)
1408 pub fn print_variants(&mut self,
1409 variants: &[ast::Variant],
1410 span: syntax_pos::Span) -> io::Result<()> {
1413 self.space_if_not_bol()?;
1414 self.maybe_print_comment(v.span.lo())?;
1415 self.print_outer_attributes(&v.node.attrs)?;
1416 self.ibox(INDENT_UNIT)?;
1417 self.print_variant(v)?;
1420 self.maybe_print_trailing_comment(v.span, None)?;
1425 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1427 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1428 ast::VisibilityKind::Crate(sugar) => match sugar {
1429 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1430 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1432 ast::VisibilityKind::Restricted { ref path, .. } => {
1433 let path = to_string(|s| s.print_path(path, false, 0));
1434 if path == "self" || path == "super" {
1435 self.word_nbsp(format!("pub({})", path))
1437 self.word_nbsp(format!("pub(in {})", path))
1440 ast::VisibilityKind::Inherited => Ok(())
1444 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1445 if let ast::Defaultness::Default = defaultness {
1446 self.word_nbsp("default")?;
1451 pub fn print_struct(&mut self,
1452 struct_def: &ast::VariantData,
1453 generics: &ast::Generics,
1455 span: syntax_pos::Span,
1456 print_finalizer: bool) -> io::Result<()> {
1457 self.print_ident(ident)?;
1458 self.print_generic_params(&generics.params)?;
1460 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1461 if let ast::VariantData::Tuple(..) = struct_def {
1464 Inconsistent, struct_def.fields(),
1466 s.maybe_print_comment(field.span.lo())?;
1467 s.print_outer_attributes(&field.attrs)?;
1468 s.print_visibility(&field.vis)?;
1469 s.print_type(&field.ty)
1474 self.print_where_clause(&generics.where_clause)?;
1475 if print_finalizer {
1479 self.end() // close the outer-box
1481 ast::VariantData::Struct(..) => {
1482 self.print_where_clause(&generics.where_clause)?;
1485 self.hardbreak_if_not_bol()?;
1487 for field in struct_def.fields() {
1488 self.hardbreak_if_not_bol()?;
1489 self.maybe_print_comment(field.span.lo())?;
1490 self.print_outer_attributes(&field.attrs)?;
1491 self.print_visibility(&field.vis)?;
1492 self.print_ident(field.ident.unwrap())?;
1493 self.word_nbsp(":")?;
1494 self.print_type(&field.ty)?;
1503 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1505 let generics = ast::Generics::default();
1506 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1507 match v.node.disr_expr {
1510 self.word_space("=")?;
1511 self.print_expr(&d.value)
1517 pub fn print_method_sig(&mut self,
1519 generics: &ast::Generics,
1521 vis: &ast::Visibility)
1523 self.print_fn(&m.decl,
1530 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1532 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1533 self.hardbreak_if_not_bol()?;
1534 self.maybe_print_comment(ti.span.lo())?;
1535 self.print_outer_attributes(&ti.attrs)?;
1537 ast::TraitItemKind::Const(ref ty, ref default) => {
1538 self.print_associated_const(
1541 default.as_ref().map(|expr| &**expr),
1542 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1545 ast::TraitItemKind::Method(ref sig, ref body) => {
1549 self.print_method_sig(
1553 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1555 if let Some(ref body) = *body {
1557 self.print_block_with_attrs(body, &ti.attrs)?;
1562 ast::TraitItemKind::Type(ref bounds, ref default) => {
1563 self.print_associated_type(ti.ident, Some(bounds),
1564 default.as_ref().map(|ty| &**ty))?;
1566 ast::TraitItemKind::Macro(ref mac) => {
1567 self.print_mac(mac)?;
1568 match mac.node.delim {
1569 MacDelimiter::Brace => {}
1570 _ => self.s.word(";")?,
1574 self.ann.post(self, AnnNode::SubItem(ti.id))
1577 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1578 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1579 self.hardbreak_if_not_bol()?;
1580 self.maybe_print_comment(ii.span.lo())?;
1581 self.print_outer_attributes(&ii.attrs)?;
1582 self.print_defaultness(ii.defaultness)?;
1584 ast::ImplItemKind::Const(ref ty, ref expr) => {
1585 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1587 ast::ImplItemKind::Method(ref sig, ref body) => {
1589 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1591 self.print_block_with_attrs(body, &ii.attrs)?;
1593 ast::ImplItemKind::Type(ref ty) => {
1594 self.print_associated_type(ii.ident, None, Some(ty))?;
1596 ast::ImplItemKind::Existential(ref bounds) => {
1597 self.word_space("existential")?;
1598 self.print_associated_type(ii.ident, Some(bounds), None)?;
1600 ast::ImplItemKind::Macro(ref mac) => {
1601 self.print_mac(mac)?;
1602 match mac.node.delim {
1603 MacDelimiter::Brace => {}
1604 _ => self.s.word(";")?,
1608 self.ann.post(self, AnnNode::SubItem(ii.id))
1611 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1612 self.maybe_print_comment(st.span.lo())?;
1614 ast::StmtKind::Local(ref loc) => {
1615 self.print_outer_attributes(&loc.attrs)?;
1616 self.space_if_not_bol()?;
1617 self.ibox(INDENT_UNIT)?;
1618 self.word_nbsp("let")?;
1620 self.ibox(INDENT_UNIT)?;
1621 self.print_local_decl(loc)?;
1623 if let Some(ref init) = loc.init {
1625 self.word_space("=")?;
1626 self.print_expr(init)?;
1631 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1632 ast::StmtKind::Expr(ref expr) => {
1633 self.space_if_not_bol()?;
1634 self.print_expr_outer_attr_style(expr, false)?;
1635 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1639 ast::StmtKind::Semi(ref expr) => {
1640 self.space_if_not_bol()?;
1641 self.print_expr_outer_attr_style(expr, false)?;
1644 ast::StmtKind::Mac(ref mac) => {
1645 let (ref mac, style, ref attrs) = **mac;
1646 self.space_if_not_bol()?;
1647 self.print_outer_attributes(attrs)?;
1648 self.print_mac(mac)?;
1649 if style == ast::MacStmtStyle::Semicolon {
1654 self.maybe_print_trailing_comment(st.span, None)
1657 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1658 self.print_block_with_attrs(blk, &[])
1661 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1662 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1665 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1666 attrs: &[ast::Attribute])
1668 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1671 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1672 indented: usize) -> io::Result<()> {
1673 self.print_block_maybe_unclosed(blk, indented, &[], false)
1676 pub fn print_block_with_attrs(&mut self,
1678 attrs: &[ast::Attribute]) -> io::Result<()> {
1679 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1682 pub fn print_block_maybe_unclosed(&mut self,
1685 attrs: &[ast::Attribute],
1686 close_box: bool) -> io::Result<()> {
1688 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1689 BlockCheckMode::Default => ()
1691 self.maybe_print_comment(blk.span.lo())?;
1692 self.ann.pre(self, AnnNode::Block(blk))?;
1695 self.print_inner_attributes(attrs)?;
1697 for (i, st) in blk.stmts.iter().enumerate() {
1699 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1700 self.maybe_print_comment(st.span.lo())?;
1701 self.space_if_not_bol()?;
1702 self.print_expr_outer_attr_style(expr, false)?;
1703 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1705 _ => self.print_stmt(st)?,
1709 self.bclose_maybe_open(blk.span, indented, close_box)?;
1710 self.ann.post(self, AnnNode::Block(blk))
1713 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1717 // "another else-if"
1718 ast::ExprKind::If(ref i, ref then, ref e) => {
1719 self.cbox(INDENT_UNIT - 1)?;
1721 self.s.word(" else if ")?;
1722 self.print_expr_as_cond(i)?;
1724 self.print_block(then)?;
1725 self.print_else(e.as_ref().map(|e| &**e))
1727 // "another else-if-let"
1728 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1729 self.cbox(INDENT_UNIT - 1)?;
1731 self.s.word(" else if let ")?;
1732 self.print_pats(pats)?;
1734 self.word_space("=")?;
1735 self.print_expr_as_cond(expr)?;
1737 self.print_block(then)?;
1738 self.print_else(e.as_ref().map(|e| &**e))
1741 ast::ExprKind::Block(ref b, _) => {
1742 self.cbox(INDENT_UNIT - 1)?;
1744 self.s.word(" else ")?;
1747 // BLEAH, constraints would be great here
1749 panic!("print_if saw if with weird alternative");
1757 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1758 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1760 self.print_expr_as_cond(test)?;
1762 self.print_block(blk)?;
1763 self.print_else(elseopt)
1766 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1767 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1768 self.head("if let")?;
1769 self.print_pats(pats)?;
1771 self.word_space("=")?;
1772 self.print_expr_as_cond(expr)?;
1774 self.print_block(blk)?;
1775 self.print_else(elseopt)
1778 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1779 self.print_path(&m.node.path, false, 0)?;
1781 match m.node.delim {
1782 MacDelimiter::Parenthesis => self.popen()?,
1783 MacDelimiter::Bracket => self.s.word("[")?,
1784 MacDelimiter::Brace => {
1789 self.print_tts(m.node.stream())?;
1790 match m.node.delim {
1791 MacDelimiter::Parenthesis => self.pclose(),
1792 MacDelimiter::Bracket => self.s.word("]"),
1793 MacDelimiter::Brace => self.bclose(m.span),
1798 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1800 self.commasep_exprs(Inconsistent, args)?;
1804 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1805 let needs_par = expr.precedence().order() < prec;
1809 self.print_expr(expr)?;
1816 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1817 /// `if cond { ... }`.
1818 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1819 let needs_par = match expr.node {
1820 // These cases need parens due to the parse error observed in #26461: `if return {}`
1821 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1822 ast::ExprKind::Closure(..) |
1823 ast::ExprKind::Ret(..) |
1824 ast::ExprKind::Break(..) => true,
1826 _ => parser::contains_exterior_struct_lit(expr),
1832 self.print_expr(expr)?;
1839 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1840 attrs: &[Attribute]) -> io::Result<()> {
1841 self.ibox(INDENT_UNIT)?;
1843 self.print_inner_attributes_inline(attrs)?;
1844 self.commasep_exprs(Inconsistent, &exprs[..])?;
1849 fn print_expr_repeat(&mut self,
1850 element: &ast::Expr,
1851 count: &ast::AnonConst,
1852 attrs: &[Attribute]) -> io::Result<()> {
1853 self.ibox(INDENT_UNIT)?;
1855 self.print_inner_attributes_inline(attrs)?;
1856 self.print_expr(element)?;
1857 self.word_space(";")?;
1858 self.print_expr(&count.value)?;
1863 fn print_expr_struct(&mut self,
1865 fields: &[ast::Field],
1866 wth: &Option<P<ast::Expr>>,
1867 attrs: &[Attribute]) -> io::Result<()> {
1868 self.print_path(path, true, 0)?;
1870 self.print_inner_attributes_inline(attrs)?;
1875 s.ibox(INDENT_UNIT)?;
1876 if !field.is_shorthand {
1877 s.print_ident(field.ident)?;
1880 s.print_expr(&field.expr)?;
1886 self.ibox(INDENT_UNIT)?;
1887 if !fields.is_empty() {
1892 self.print_expr(expr)?;
1895 _ => if !fields.is_empty() {
1903 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1904 attrs: &[Attribute]) -> io::Result<()> {
1906 self.print_inner_attributes_inline(attrs)?;
1907 self.commasep_exprs(Inconsistent, &exprs[..])?;
1908 if exprs.len() == 1 {
1914 fn print_expr_call(&mut self,
1916 args: &[P<ast::Expr>]) -> io::Result<()> {
1919 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1920 _ => parser::PREC_POSTFIX,
1923 self.print_expr_maybe_paren(func, prec)?;
1924 self.print_call_post(args)
1927 fn print_expr_method_call(&mut self,
1928 segment: &ast::PathSegment,
1929 args: &[P<ast::Expr>]) -> io::Result<()> {
1930 let base_args = &args[1..];
1931 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1933 self.print_ident(segment.ident)?;
1934 if let Some(ref args) = segment.args {
1935 self.print_generic_args(args, true)?;
1937 self.print_call_post(base_args)
1940 fn print_expr_binary(&mut self,
1943 rhs: &ast::Expr) -> io::Result<()> {
1944 let assoc_op = AssocOp::from_ast_binop(op.node);
1945 let prec = assoc_op.precedence() as i8;
1946 let fixity = assoc_op.fixity();
1948 let (left_prec, right_prec) = match fixity {
1949 Fixity::Left => (prec, prec + 1),
1950 Fixity::Right => (prec + 1, prec),
1951 Fixity::None => (prec + 1, prec + 1),
1954 let left_prec = match (&lhs.node, op.node) {
1955 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1956 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1957 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1958 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1959 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1963 self.print_expr_maybe_paren(lhs, left_prec)?;
1965 self.word_space(op.node.to_string())?;
1966 self.print_expr_maybe_paren(rhs, right_prec)
1969 fn print_expr_unary(&mut self,
1971 expr: &ast::Expr) -> io::Result<()> {
1972 self.s.word(ast::UnOp::to_string(op))?;
1973 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1976 fn print_expr_addr_of(&mut self,
1977 mutability: ast::Mutability,
1978 expr: &ast::Expr) -> io::Result<()> {
1980 self.print_mutability(mutability)?;
1981 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1984 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1985 self.print_expr_outer_attr_style(expr, true)
1988 fn print_expr_outer_attr_style(&mut self,
1990 is_inline: bool) -> io::Result<()> {
1991 self.maybe_print_comment(expr.span.lo())?;
1993 let attrs = &expr.attrs;
1995 self.print_outer_attributes_inline(attrs)?;
1997 self.print_outer_attributes(attrs)?;
2000 self.ibox(INDENT_UNIT)?;
2001 self.ann.pre(self, AnnNode::Expr(expr))?;
2003 ast::ExprKind::Box(ref expr) => {
2004 self.word_space("box")?;
2005 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2007 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2008 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2009 self.print_expr_maybe_paren(place, prec + 1)?;
2011 self.word_space("<-")?;
2012 self.print_expr_maybe_paren(expr, prec)?;
2014 ast::ExprKind::Array(ref exprs) => {
2015 self.print_expr_vec(&exprs[..], attrs)?;
2017 ast::ExprKind::Repeat(ref element, ref count) => {
2018 self.print_expr_repeat(element, count, attrs)?;
2020 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2021 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2023 ast::ExprKind::Tup(ref exprs) => {
2024 self.print_expr_tup(&exprs[..], attrs)?;
2026 ast::ExprKind::Call(ref func, ref args) => {
2027 self.print_expr_call(func, &args[..])?;
2029 ast::ExprKind::MethodCall(ref segment, ref args) => {
2030 self.print_expr_method_call(segment, &args[..])?;
2032 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2033 self.print_expr_binary(op, lhs, rhs)?;
2035 ast::ExprKind::Unary(op, ref expr) => {
2036 self.print_expr_unary(op, expr)?;
2038 ast::ExprKind::AddrOf(m, ref expr) => {
2039 self.print_expr_addr_of(m, expr)?;
2041 ast::ExprKind::Lit(ref lit) => {
2042 self.print_literal(lit)?;
2044 ast::ExprKind::Cast(ref expr, ref ty) => {
2045 let prec = AssocOp::As.precedence() as i8;
2046 self.print_expr_maybe_paren(expr, prec)?;
2048 self.word_space("as")?;
2049 self.print_type(ty)?;
2051 ast::ExprKind::Type(ref expr, ref ty) => {
2052 let prec = AssocOp::Colon.precedence() as i8;
2053 self.print_expr_maybe_paren(expr, prec)?;
2054 self.word_space(":")?;
2055 self.print_type(ty)?;
2057 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2058 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2060 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2061 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2063 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2064 if let Some(label) = opt_label {
2065 self.print_ident(label.ident)?;
2066 self.word_space(":")?;
2068 self.head("while")?;
2069 self.print_expr_as_cond(test)?;
2071 self.print_block_with_attrs(blk, attrs)?;
2073 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2074 if let Some(label) = opt_label {
2075 self.print_ident(label.ident)?;
2076 self.word_space(":")?;
2078 self.head("while let")?;
2079 self.print_pats(pats)?;
2081 self.word_space("=")?;
2082 self.print_expr_as_cond(expr)?;
2084 self.print_block_with_attrs(blk, attrs)?;
2086 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2087 if let Some(label) = opt_label {
2088 self.print_ident(label.ident)?;
2089 self.word_space(":")?;
2092 self.print_pat(pat)?;
2094 self.word_space("in")?;
2095 self.print_expr_as_cond(iter)?;
2097 self.print_block_with_attrs(blk, attrs)?;
2099 ast::ExprKind::Loop(ref blk, opt_label) => {
2100 if let Some(label) = opt_label {
2101 self.print_ident(label.ident)?;
2102 self.word_space(":")?;
2106 self.print_block_with_attrs(blk, attrs)?;
2108 ast::ExprKind::Match(ref expr, ref arms) => {
2109 self.cbox(INDENT_UNIT)?;
2111 self.word_nbsp("match")?;
2112 self.print_expr_as_cond(expr)?;
2115 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2117 self.print_arm(arm)?;
2119 self.bclose_(expr.span, INDENT_UNIT)?;
2121 ast::ExprKind::Closure(
2122 capture_clause, ref asyncness, movability, ref decl, ref body, _) => {
2123 self.print_movability(movability)?;
2124 self.print_asyncness(asyncness)?;
2125 self.print_capture_clause(capture_clause)?;
2127 self.print_fn_block_args(decl)?;
2129 self.print_expr(body)?;
2130 self.end()?; // need to close a box
2132 // a box will be closed by print_expr, but we didn't want an overall
2133 // wrapper so we closed the corresponding opening. so create an
2134 // empty box to satisfy the close.
2137 ast::ExprKind::Block(ref blk, opt_label) => {
2138 if let Some(label) = opt_label {
2139 self.print_ident(label.ident)?;
2140 self.word_space(":")?;
2142 // containing cbox, will be closed by print-block at }
2143 self.cbox(INDENT_UNIT)?;
2144 // head-box, will be closed by print-block after {
2146 self.print_block_with_attrs(blk, attrs)?;
2148 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2149 self.word_nbsp("async")?;
2150 self.print_capture_clause(capture_clause)?;
2152 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2153 self.cbox(INDENT_UNIT)?;
2155 self.print_block_with_attrs(blk, attrs)?;
2157 ast::ExprKind::Await(origin, ref expr) => {
2159 ast::AwaitOrigin::MacroLike => {
2160 self.s.word("await!")?;
2161 self.print_expr_maybe_paren(expr, parser::PREC_FORCE_PAREN)?;
2163 ast::AwaitOrigin::FieldLike => {
2164 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2165 self.s.word(".await")?;
2169 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2170 let prec = AssocOp::Assign.precedence() as i8;
2171 self.print_expr_maybe_paren(lhs, prec + 1)?;
2173 self.word_space("=")?;
2174 self.print_expr_maybe_paren(rhs, prec)?;
2176 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2177 let prec = AssocOp::Assign.precedence() as i8;
2178 self.print_expr_maybe_paren(lhs, prec + 1)?;
2180 self.s.word(op.node.to_string())?;
2181 self.word_space("=")?;
2182 self.print_expr_maybe_paren(rhs, prec)?;
2184 ast::ExprKind::Field(ref expr, ident) => {
2185 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2187 self.print_ident(ident)?;
2189 ast::ExprKind::Index(ref expr, ref index) => {
2190 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2192 self.print_expr(index)?;
2195 ast::ExprKind::Range(ref start, ref end, limits) => {
2196 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2197 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2198 // Here we use a fake precedence value so that any child with lower precedence than
2199 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2200 let fake_prec = AssocOp::LOr.precedence() as i8;
2201 if let Some(ref e) = *start {
2202 self.print_expr_maybe_paren(e, fake_prec)?;
2204 if limits == ast::RangeLimits::HalfOpen {
2207 self.s.word("..=")?;
2209 if let Some(ref e) = *end {
2210 self.print_expr_maybe_paren(e, fake_prec)?;
2213 ast::ExprKind::Path(None, ref path) => {
2214 self.print_path(path, true, 0)?
2216 ast::ExprKind::Path(Some(ref qself), ref path) => {
2217 self.print_qpath(path, qself, true)?
2219 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2220 self.s.word("break")?;
2222 if let Some(label) = opt_label {
2223 self.print_ident(label.ident)?;
2226 if let Some(ref expr) = *opt_expr {
2227 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2231 ast::ExprKind::Continue(opt_label) => {
2232 self.s.word("continue")?;
2234 if let Some(label) = opt_label {
2235 self.print_ident(label.ident)?;
2239 ast::ExprKind::Ret(ref result) => {
2240 self.s.word("return")?;
2241 if let Some(ref expr) = *result {
2243 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2246 ast::ExprKind::InlineAsm(ref a) => {
2247 self.s.word("asm!")?;
2249 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2250 self.word_space(":")?;
2252 self.commasep(Inconsistent, &a.outputs, |s, out| {
2253 let constraint = out.constraint.as_str();
2254 let mut ch = constraint.chars();
2256 Some('=') if out.is_rw => {
2257 s.print_string(&format!("+{}", ch.as_str()),
2258 ast::StrStyle::Cooked)?
2260 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2263 s.print_expr(&out.expr)?;
2268 self.word_space(":")?;
2270 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2271 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2278 self.word_space(":")?;
2280 self.commasep(Inconsistent, &a.clobbers,
2282 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2286 let mut options = vec![];
2288 options.push("volatile");
2291 options.push("alignstack");
2293 if a.dialect == ast::AsmDialect::Intel {
2294 options.push("intel");
2297 if !options.is_empty() {
2299 self.word_space(":")?;
2300 self.commasep(Inconsistent, &options,
2302 s.print_string(co, ast::StrStyle::Cooked)?;
2309 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2310 ast::ExprKind::Paren(ref e) => {
2312 self.print_inner_attributes_inline(attrs)?;
2313 self.print_expr(e)?;
2316 ast::ExprKind::Yield(ref e) => {
2317 self.s.word("yield")?;
2321 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2326 ast::ExprKind::Try(ref e) => {
2327 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2330 ast::ExprKind::TryBlock(ref blk) => {
2333 self.print_block_with_attrs(blk, attrs)?
2335 ast::ExprKind::Err => {
2337 self.s.word("/*ERROR*/")?;
2341 self.ann.post(self, AnnNode::Expr(expr))?;
2345 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2346 self.print_pat(&loc.pat)?;
2347 if let Some(ref ty) = loc.ty {
2348 self.word_space(":")?;
2349 self.print_type(ty)?;
2354 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2355 if ident.is_raw_guess() {
2356 self.s.word(format!("r#{}", ident))?;
2358 self.s.word(ident.as_str().to_string())?;
2360 self.ann.post(self, AnnNode::Ident(&ident))
2363 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2364 self.s.word(i.to_string())
2367 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2368 self.s.word(name.as_str().to_string())?;
2369 self.ann.post(self, AnnNode::Name(&name))
2372 pub fn print_for_decl(&mut self, loc: &ast::Local,
2373 coll: &ast::Expr) -> io::Result<()> {
2374 self.print_local_decl(loc)?;
2376 self.word_space("in")?;
2377 self.print_expr(coll)
2380 fn print_path(&mut self,
2382 colons_before_params: bool,
2386 self.maybe_print_comment(path.span.lo())?;
2388 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2392 self.print_path_segment(segment, colons_before_params)?;
2398 fn print_path_segment(&mut self,
2399 segment: &ast::PathSegment,
2400 colons_before_params: bool)
2403 if segment.ident.name != keywords::PathRoot.name() {
2404 if segment.ident.name == keywords::DollarCrate.name() {
2405 self.print_dollar_crate(segment.ident)?;
2407 self.print_ident(segment.ident)?;
2409 if let Some(ref args) = segment.args {
2410 self.print_generic_args(args, colons_before_params)?;
2416 fn print_qpath(&mut self,
2419 colons_before_params: bool)
2423 self.print_type(&qself.ty)?;
2424 if qself.position > 0 {
2426 self.word_space("as")?;
2427 let depth = path.segments.len() - qself.position;
2428 self.print_path(path, false, depth)?;
2432 let item_segment = path.segments.last().unwrap();
2433 self.print_ident(item_segment.ident)?;
2434 match item_segment.args {
2435 Some(ref args) => self.print_generic_args(args, colons_before_params),
2440 fn print_generic_args(&mut self,
2441 args: &ast::GenericArgs,
2442 colons_before_params: bool)
2445 if colons_before_params {
2450 ast::GenericArgs::AngleBracketed(ref data) => {
2453 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2454 s.print_generic_arg(generic_arg)
2457 let mut comma = data.args.len() != 0;
2459 for binding in data.bindings.iter() {
2461 self.word_space(",")?
2463 self.print_ident(binding.ident)?;
2465 self.word_space("=")?;
2466 self.print_type(&binding.ty)?;
2473 ast::GenericArgs::Parenthesized(ref data) => {
2478 |s, ty| s.print_type(ty))?;
2481 if let Some(ref ty) = data.output {
2482 self.space_if_not_bol()?;
2483 self.word_space("->")?;
2484 self.print_type(ty)?;
2492 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2493 self.maybe_print_comment(pat.span.lo())?;
2494 self.ann.pre(self, AnnNode::Pat(pat))?;
2495 /* Pat isn't normalized, but the beauty of it
2496 is that it doesn't matter */
2498 PatKind::Wild => self.s.word("_")?,
2499 PatKind::Ident(binding_mode, ident, ref sub) => {
2500 match binding_mode {
2501 ast::BindingMode::ByRef(mutbl) => {
2502 self.word_nbsp("ref")?;
2503 self.print_mutability(mutbl)?;
2505 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2506 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2507 self.word_nbsp("mut")?;
2510 self.print_ident(ident)?;
2511 if let Some(ref p) = *sub {
2516 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2517 self.print_path(path, true, 0)?;
2519 if let Some(ddpos) = ddpos {
2520 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2522 self.word_space(",")?;
2525 if ddpos != elts.len() {
2527 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2530 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2534 PatKind::Path(None, ref path) => {
2535 self.print_path(path, true, 0)?;
2537 PatKind::Path(Some(ref qself), ref path) => {
2538 self.print_qpath(path, qself, false)?;
2540 PatKind::Struct(ref path, ref fields, etc) => {
2541 self.print_path(path, true, 0)?;
2543 self.word_space("{")?;
2545 Consistent, &fields[..],
2547 s.cbox(INDENT_UNIT)?;
2548 if !f.node.is_shorthand {
2549 s.print_ident(f.node.ident)?;
2552 s.print_pat(&f.node.pat)?;
2555 |f| f.node.pat.span)?;
2557 if !fields.is_empty() { self.word_space(",")?; }
2563 PatKind::Tuple(ref elts, ddpos) => {
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))?;
2577 if elts.len() == 1 {
2583 PatKind::Box(ref inner) => {
2584 self.s.word("box ")?;
2585 self.print_pat(inner)?;
2587 PatKind::Ref(ref inner, mutbl) => {
2589 if mutbl == ast::Mutability::Mutable {
2590 self.s.word("mut ")?;
2592 self.print_pat(inner)?;
2594 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2595 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2596 self.print_expr(begin)?;
2599 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2600 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2601 RangeEnd::Excluded => self.s.word("..")?,
2603 self.print_expr(end)?;
2605 PatKind::Slice(ref before, ref slice, ref after) => {
2607 self.commasep(Inconsistent,
2609 |s, p| s.print_pat(p))?;
2610 if let Some(ref p) = *slice {
2611 if !before.is_empty() { self.word_space(",")?; }
2612 if let PatKind::Wild = p.node {
2618 if !after.is_empty() { self.word_space(",")?; }
2620 self.commasep(Inconsistent,
2622 |s, p| s.print_pat(p))?;
2625 PatKind::Paren(ref inner) => {
2627 self.print_pat(inner)?;
2630 PatKind::Mac(ref m) => self.print_mac(m)?,
2632 self.ann.post(self, AnnNode::Pat(pat))
2635 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2636 let mut first = true;
2642 self.word_space("|")?;
2649 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2650 // I have no idea why this check is necessary, but here it
2652 if arm.attrs.is_empty() {
2655 self.cbox(INDENT_UNIT)?;
2657 self.maybe_print_comment(arm.pats[0].span.lo())?;
2658 self.print_outer_attributes(&arm.attrs)?;
2659 self.print_pats(&arm.pats)?;
2661 if let Some(ref g) = arm.guard {
2663 ast::Guard::If(ref e) => {
2664 self.word_space("if")?;
2665 self.print_expr(e)?;
2670 self.word_space("=>")?;
2672 match arm.body.node {
2673 ast::ExprKind::Block(ref blk, opt_label) => {
2674 if let Some(label) = opt_label {
2675 self.print_ident(label.ident)?;
2676 self.word_space(":")?;
2679 // the block will close the pattern's ibox
2680 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2682 // If it is a user-provided unsafe block, print a comma after it
2683 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2688 self.end()?; // close the ibox for the pattern
2689 self.print_expr(&arm.body)?;
2693 self.end() // close enclosing cbox
2696 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2697 match explicit_self.node {
2698 SelfKind::Value(m) => {
2699 self.print_mutability(m)?;
2702 SelfKind::Region(ref lt, m) => {
2704 self.print_opt_lifetime(lt)?;
2705 self.print_mutability(m)?;
2708 SelfKind::Explicit(ref typ, m) => {
2709 self.print_mutability(m)?;
2710 self.s.word("self")?;
2711 self.word_space(":")?;
2712 self.print_type(typ)
2717 pub fn print_fn(&mut self,
2719 header: &ast::FnHeader,
2720 name: Option<ast::Ident>,
2721 generics: &ast::Generics,
2722 vis: &ast::Visibility) -> io::Result<()> {
2723 self.print_fn_header_info(header, vis)?;
2725 if let Some(name) = name {
2727 self.print_ident(name)?;
2729 self.print_generic_params(&generics.params)?;
2730 self.print_fn_args_and_ret(decl)?;
2731 self.print_where_clause(&generics.where_clause)
2734 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2737 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2740 self.print_fn_output(decl)
2743 pub fn print_fn_block_args(
2748 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2751 if let ast::FunctionRetTy::Default(..) = decl.output {
2755 self.space_if_not_bol()?;
2756 self.word_space("->")?;
2758 ast::FunctionRetTy::Ty(ref ty) => {
2759 self.print_type(ty)?;
2760 self.maybe_print_comment(ty.span.lo())
2762 ast::FunctionRetTy::Default(..) => unreachable!(),
2766 pub fn print_movability(&mut self, movability: ast::Movability)
2769 ast::Movability::Static => self.word_space("static"),
2770 ast::Movability::Movable => Ok(()),
2774 pub fn print_asyncness(&mut self, asyncness: &ast::IsAsync) -> io::Result<()> {
2775 if asyncness.is_async() {
2776 self.word_nbsp("async")?;
2781 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2783 match capture_clause {
2784 ast::CaptureBy::Value => self.word_space("move"),
2785 ast::CaptureBy::Ref => Ok(()),
2789 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
2791 if !bounds.is_empty() {
2792 self.s.word(prefix)?;
2793 let mut first = true;
2794 for bound in bounds {
2795 if !(first && prefix.is_empty()) {
2801 self.word_space("+")?;
2805 GenericBound::Trait(tref, modifier) => {
2806 if modifier == &TraitBoundModifier::Maybe {
2809 self.print_poly_trait_ref(tref)?;
2811 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2818 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2819 self.print_name(lifetime.ident.name)
2822 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2825 self.print_lifetime(lifetime)?;
2826 if !bounds.is_empty() {
2828 for (i, bound) in bounds.iter().enumerate() {
2830 self.s.word(" + ")?;
2833 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2841 pub fn print_generic_params(
2843 generic_params: &[ast::GenericParam]
2844 ) -> io::Result<()> {
2845 if generic_params.is_empty() {
2851 self.commasep(Inconsistent, &generic_params, |s, param| {
2853 ast::GenericParamKind::Lifetime => {
2854 s.print_outer_attributes_inline(¶m.attrs)?;
2855 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2856 s.print_lifetime_bounds(lt, ¶m.bounds)
2858 ast::GenericParamKind::Type { ref default } => {
2859 s.print_outer_attributes_inline(¶m.attrs)?;
2860 s.print_ident(param.ident)?;
2861 s.print_type_bounds(":", ¶m.bounds)?;
2863 Some(ref default) => {
2866 s.print_type(default)
2871 ast::GenericParamKind::Const { ref ty } => {
2872 s.print_outer_attributes_inline(¶m.attrs)?;
2873 s.word_space("const")?;
2874 s.print_ident(param.ident)?;
2878 s.print_type_bounds(":", ¶m.bounds)
2887 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2889 if where_clause.predicates.is_empty() {
2894 self.word_space("where")?;
2896 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2898 self.word_space(",")?;
2902 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2903 ref bound_generic_params,
2908 self.print_formal_generic_params(bound_generic_params)?;
2909 self.print_type(bounded_ty)?;
2910 self.print_type_bounds(":", bounds)?;
2912 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2915 self.print_lifetime_bounds(*lifetime, bounds)?;
2917 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2920 self.print_type(lhs_ty)?;
2922 self.word_space("=")?;
2923 self.print_type(rhs_ty)?;
2931 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2933 ast::UseTreeKind::Simple(rename, ..) => {
2934 self.print_path(&tree.prefix, false, 0)?;
2935 if let Some(rename) = rename {
2937 self.word_space("as")?;
2938 self.print_ident(rename)?;
2941 ast::UseTreeKind::Glob => {
2942 if !tree.prefix.segments.is_empty() {
2943 self.print_path(&tree.prefix, false, 0)?;
2948 ast::UseTreeKind::Nested(ref items) => {
2949 if tree.prefix.segments.is_empty() {
2952 self.print_path(&tree.prefix, false, 0)?;
2953 self.s.word("::{")?;
2955 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2956 this.print_use_tree(tree)
2965 pub fn print_mutability(&mut self,
2966 mutbl: ast::Mutability) -> io::Result<()> {
2968 ast::Mutability::Mutable => self.word_nbsp("mut"),
2969 ast::Mutability::Immutable => Ok(()),
2973 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2974 self.print_mutability(mt.mutbl)?;
2975 self.print_type(&mt.ty)
2978 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2979 self.ibox(INDENT_UNIT)?;
2980 match input.ty.node {
2981 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2983 if let Some(eself) = input.to_self() {
2984 self.print_explicit_self(&eself)?;
2986 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2987 ident.name == keywords::Invalid.name()
2992 self.print_pat(&input.pat)?;
2996 self.print_type(&input.ty)?;
3003 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3004 if let ast::FunctionRetTy::Default(..) = decl.output {
3008 self.space_if_not_bol()?;
3009 self.ibox(INDENT_UNIT)?;
3010 self.word_space("->")?;
3012 ast::FunctionRetTy::Default(..) => unreachable!(),
3013 ast::FunctionRetTy::Ty(ref ty) =>
3014 self.print_type(ty)?
3019 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3024 pub fn print_ty_fn(&mut self,
3026 unsafety: ast::Unsafety,
3028 name: Option<ast::Ident>,
3029 generic_params: &[ast::GenericParam])
3031 self.ibox(INDENT_UNIT)?;
3032 if !generic_params.is_empty() {
3033 self.s.word("for")?;
3034 self.print_generic_params(generic_params)?;
3036 let generics = ast::Generics {
3038 where_clause: ast::WhereClause {
3039 id: ast::DUMMY_NODE_ID,
3040 predicates: Vec::new(),
3041 span: syntax_pos::DUMMY_SP,
3043 span: syntax_pos::DUMMY_SP,
3046 &ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3049 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3053 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3054 next_pos: Option<BytePos>)
3056 let cm = match self.cm {
3060 if let Some(ref cmnt) = self.next_comment() {
3061 if cmnt.style != comments::Trailing { return Ok(()) }
3062 let span_line = cm.lookup_char_pos(span.hi());
3063 let comment_line = cm.lookup_char_pos(cmnt.pos);
3064 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
3065 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3066 self.print_comment(cmnt)?;
3072 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3073 // If there aren't any remaining comments, then we need to manually
3074 // make sure there is a line break at the end.
3075 if self.next_comment().is_none() {
3076 self.s.hardbreak()?;
3078 while let Some(ref cmnt) = self.next_comment() {
3079 self.print_comment(cmnt)?;
3084 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3085 opt_abi: Option<Abi>)
3088 Some(Abi::Rust) => Ok(()),
3090 self.word_nbsp("extern")?;
3091 self.word_nbsp(abi.to_string())
3097 pub fn print_extern_opt_abi(&mut self,
3098 opt_abi: Option<Abi>) -> io::Result<()> {
3101 self.word_nbsp("extern")?;
3102 self.word_nbsp(abi.to_string())
3108 pub fn print_fn_header_info(&mut self,
3109 header: &ast::FnHeader,
3110 vis: &ast::Visibility) -> io::Result<()> {
3111 self.s.word(visibility_qualified(vis, ""))?;
3113 match header.constness.node {
3114 ast::Constness::NotConst => {}
3115 ast::Constness::Const => self.word_nbsp("const")?
3118 self.print_asyncness(&header.asyncness.node)?;
3119 self.print_unsafety(header.unsafety)?;
3121 if header.abi != Abi::Rust {
3122 self.word_nbsp("extern")?;
3123 self.word_nbsp(header.abi.to_string())?;
3129 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3131 ast::Unsafety::Normal => Ok(()),
3132 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3136 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3138 ast::IsAuto::Yes => self.word_nbsp("auto"),
3139 ast::IsAuto::No => Ok(()),
3149 use crate::source_map;
3150 use crate::with_globals;
3154 fn test_fun_to_string() {
3156 let abba_ident = ast::Ident::from_str("abba");
3158 let decl = ast::FnDecl {
3160 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3163 let generics = ast::Generics::default();
3168 unsafety: ast::Unsafety::Normal,
3169 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3170 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
3182 fn test_variant_to_string() {
3184 let ident = ast::Ident::from_str("principal_skinner");
3186 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3189 id: ast::DUMMY_NODE_ID,
3190 // making this up as I go.... ?
3191 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3195 let varstr = variant_to_string(&var);
3196 assert_eq!(varstr, "principal_skinner");