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, TokenKind};
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::{kw, 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) -> String {
167 let token::Lit { kind, symbol, suffix } = lit;
168 let mut out = match kind {
169 token::Byte => format!("b'{}'", symbol),
170 token::Char => format!("'{}'", symbol),
171 token::Str => format!("\"{}\"", symbol),
172 token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}",
173 delim="#".repeat(n as usize),
175 token::ByteStr => format!("b\"{}\"", symbol),
176 token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}",
177 delim="#".repeat(n as usize),
182 token::Err => symbol.to_string(),
185 if let Some(suffix) = suffix {
186 out.push_str(&suffix.as_str())
192 pub fn token_kind_to_string(tok: &TokenKind) -> String {
194 token::Eq => "=".to_string(),
195 token::Lt => "<".to_string(),
196 token::Le => "<=".to_string(),
197 token::EqEq => "==".to_string(),
198 token::Ne => "!=".to_string(),
199 token::Ge => ">=".to_string(),
200 token::Gt => ">".to_string(),
201 token::Not => "!".to_string(),
202 token::Tilde => "~".to_string(),
203 token::OrOr => "||".to_string(),
204 token::AndAnd => "&&".to_string(),
205 token::BinOp(op) => binop_to_string(op).to_string(),
206 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
208 /* Structural symbols */
209 token::At => "@".to_string(),
210 token::Dot => ".".to_string(),
211 token::DotDot => "..".to_string(),
212 token::DotDotDot => "...".to_string(),
213 token::DotDotEq => "..=".to_string(),
214 token::Comma => ",".to_string(),
215 token::Semi => ";".to_string(),
216 token::Colon => ":".to_string(),
217 token::ModSep => "::".to_string(),
218 token::RArrow => "->".to_string(),
219 token::LArrow => "<-".to_string(),
220 token::FatArrow => "=>".to_string(),
221 token::OpenDelim(token::Paren) => "(".to_string(),
222 token::CloseDelim(token::Paren) => ")".to_string(),
223 token::OpenDelim(token::Bracket) => "[".to_string(),
224 token::CloseDelim(token::Bracket) => "]".to_string(),
225 token::OpenDelim(token::Brace) => "{".to_string(),
226 token::CloseDelim(token::Brace) => "}".to_string(),
227 token::OpenDelim(token::NoDelim) |
228 token::CloseDelim(token::NoDelim) => " ".to_string(),
229 token::Pound => "#".to_string(),
230 token::Dollar => "$".to_string(),
231 token::Question => "?".to_string(),
232 token::SingleQuote => "'".to_string(),
235 token::Literal(lit) => literal_to_string(lit),
237 /* Name components */
238 token::Ident(s, false) => s.to_string(),
239 token::Ident(s, true) => format!("r#{}", s),
240 token::Lifetime(s) => s.to_string(),
243 token::DocComment(s) => s.to_string(),
244 token::Eof => "<eof>".to_string(),
245 token::Whitespace => " ".to_string(),
246 token::Comment => "/* */".to_string(),
247 token::Shebang(s) => format!("/* shebang: {}*/", s),
249 token::Interpolated(ref nt) => nonterminal_to_string(nt),
253 pub fn token_to_string(token: &Token) -> String {
254 token_kind_to_string(&token.kind)
257 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
259 token::NtExpr(ref e) => expr_to_string(e),
260 token::NtMeta(ref e) => meta_item_to_string(e),
261 token::NtTy(ref e) => ty_to_string(e),
262 token::NtPath(ref e) => path_to_string(e),
263 token::NtItem(ref e) => item_to_string(e),
264 token::NtBlock(ref e) => block_to_string(e),
265 token::NtStmt(ref e) => stmt_to_string(e),
266 token::NtPat(ref e) => pat_to_string(e),
267 token::NtIdent(e, false) => ident_to_string(e),
268 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
269 token::NtLifetime(e) => ident_to_string(e),
270 token::NtLiteral(ref e) => expr_to_string(e),
271 token::NtTT(ref tree) => tt_to_string(tree.clone()),
272 token::NtImplItem(ref e) => impl_item_to_string(e),
273 token::NtTraitItem(ref e) => trait_item_to_string(e),
274 token::NtVis(ref e) => vis_to_string(e),
275 token::NtForeignItem(ref e) => foreign_item_to_string(e),
279 pub fn ty_to_string(ty: &ast::Ty) -> String {
280 to_string(|s| s.print_type(ty))
283 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
284 to_string(|s| s.print_type_bounds("", bounds))
287 pub fn pat_to_string(pat: &ast::Pat) -> String {
288 to_string(|s| s.print_pat(pat))
291 pub fn arm_to_string(arm: &ast::Arm) -> String {
292 to_string(|s| s.print_arm(arm))
295 pub fn expr_to_string(e: &ast::Expr) -> String {
296 to_string(|s| s.print_expr(e))
299 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
300 to_string(|s| s.print_lifetime(*lt))
303 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
304 to_string(|s| s.print_tt(tt))
307 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
308 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
311 pub fn tokens_to_string(tokens: TokenStream) -> String {
312 to_string(|s| s.print_tts(tokens))
315 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
316 to_string(|s| s.print_stmt(stmt))
319 pub fn attr_to_string(attr: &ast::Attribute) -> String {
320 to_string(|s| s.print_attribute(attr))
323 pub fn item_to_string(i: &ast::Item) -> String {
324 to_string(|s| s.print_item(i))
327 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
328 to_string(|s| s.print_impl_item(i))
331 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
332 to_string(|s| s.print_trait_item(i))
335 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
336 to_string(|s| s.print_generic_params(generic_params))
339 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
340 to_string(|s| s.print_where_clause(i))
343 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
344 to_string(|s| s.print_fn_block_args(p))
347 pub fn path_to_string(p: &ast::Path) -> String {
348 to_string(|s| s.print_path(p, false, 0))
351 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
352 to_string(|s| s.print_path_segment(p, false))
355 pub fn ident_to_string(id: ast::Ident) -> String {
356 to_string(|s| s.print_ident(id))
359 pub fn vis_to_string(v: &ast::Visibility) -> String {
360 to_string(|s| s.print_visibility(v))
363 pub fn fun_to_string(decl: &ast::FnDecl,
364 header: ast::FnHeader,
366 generics: &ast::Generics)
370 s.print_fn(decl, header, Some(name),
371 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
372 s.end()?; // Close the head box
373 s.end() // Close the outer box
377 pub fn block_to_string(blk: &ast::Block) -> String {
379 // containing cbox, will be closed by print-block at }
380 s.cbox(INDENT_UNIT)?;
381 // head-ibox, will be closed by print-block after {
387 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
388 to_string(|s| s.print_meta_list_item(li))
391 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
392 to_string(|s| s.print_meta_item(mi))
395 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
396 to_string(|s| s.print_attribute(attr))
399 pub fn lit_to_string(l: &ast::Lit) -> String {
400 to_string(|s| s.print_literal(l))
403 pub fn variant_to_string(var: &ast::Variant) -> String {
404 to_string(|s| s.print_variant(var))
407 pub fn arg_to_string(arg: &ast::Arg) -> String {
408 to_string(|s| s.print_arg(arg, false))
411 pub fn mac_to_string(arg: &ast::Mac) -> String {
412 to_string(|s| s.print_mac(arg))
415 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
416 to_string(|s| s.print_foreign_item(arg))
419 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
420 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
423 pub trait PrintState<'a> {
424 fn writer(&mut self) -> &mut pp::Printer<'a>;
425 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
426 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
427 fn cur_cmnt(&mut self) -> &mut usize;
429 fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
430 self.writer().word(w)?;
431 self.writer().space()
434 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
436 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
438 fn is_begin(&mut self) -> bool {
439 match self.writer().last_token() {
440 pp::Token::Begin(_) => true,
445 fn is_end(&mut self) -> bool {
446 match self.writer().last_token() {
447 pp::Token::End => true,
452 // is this the beginning of a line?
453 fn is_bol(&mut self) -> bool {
454 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
457 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
459 self.writer().hardbreak()?
465 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
466 self.boxes().push(b);
467 self.writer().rbox(u, b)
470 fn ibox(&mut self, u: usize) -> io::Result<()> {
471 self.boxes().push(pp::Breaks::Inconsistent);
472 self.writer().ibox(u)
475 fn end(&mut self) -> io::Result<()> {
476 self.boxes().pop().unwrap();
480 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
481 where F: FnMut(&mut Self, &T) -> io::Result<()>,
484 let mut first = true;
486 if first { first = false; } else { self.word_space(",")?; }
492 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
493 while let Some(ref cmnt) = self.next_comment() {
495 self.print_comment(cmnt)?;
503 fn print_comment(&mut self,
504 cmnt: &comments::Comment) -> io::Result<()> {
505 let r = match cmnt.style {
507 assert_eq!(cmnt.lines.len(), 1);
508 self.writer().zerobreak()?;
509 self.writer().word(cmnt.lines[0].clone())?;
510 self.writer().zerobreak()
512 comments::Isolated => {
513 self.hardbreak_if_not_bol()?;
514 for line in &cmnt.lines {
515 // Don't print empty lines because they will end up as trailing
517 if !line.is_empty() {
518 self.writer().word(line.clone())?;
520 self.writer().hardbreak()?;
524 comments::Trailing => {
526 self.writer().word(" ")?;
528 if cmnt.lines.len() == 1 {
529 self.writer().word(cmnt.lines[0].clone())?;
530 self.writer().hardbreak()
533 for line in &cmnt.lines {
534 if !line.is_empty() {
535 self.writer().word(line.clone())?;
537 self.writer().hardbreak()?;
542 comments::BlankLine => {
543 // We need to do at least one, possibly two hardbreaks.
544 let is_semi = match self.writer().last_token() {
545 pp::Token::String(s, _) => ";" == s,
548 if is_semi || self.is_begin() || self.is_end() {
549 self.writer().hardbreak()?;
551 self.writer().hardbreak()
556 *self.cur_cmnt() = *self.cur_cmnt() + 1;
563 fn next_comment(&mut self) -> Option<comments::Comment> {
564 let cur_cmnt = *self.cur_cmnt();
565 match *self.comments() {
567 if cur_cmnt < cmnts.len() {
568 Some(cmnts[cur_cmnt].clone())
577 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
578 self.maybe_print_comment(lit.span.lo())?;
579 self.writer().word(literal_to_string(lit.token))
582 fn print_string(&mut self, st: &str,
583 style: ast::StrStyle) -> io::Result<()> {
584 let st = match style {
585 ast::StrStyle::Cooked => {
586 (format!("\"{}\"", st.escape_debug()))
588 ast::StrStyle::Raw(n) => {
589 (format!("r{delim}\"{string}\"{delim}",
590 delim="#".repeat(n as usize),
594 self.writer().word(st)
597 fn print_inner_attributes(&mut self,
598 attrs: &[ast::Attribute]) -> io::Result<()> {
599 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
602 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
603 attrs: &[ast::Attribute])
605 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
608 fn print_outer_attributes(&mut self,
609 attrs: &[ast::Attribute]) -> io::Result<()> {
610 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
613 fn print_inner_attributes_inline(&mut self,
614 attrs: &[ast::Attribute]) -> io::Result<()> {
615 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
618 fn print_outer_attributes_inline(&mut self,
619 attrs: &[ast::Attribute]) -> io::Result<()> {
620 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
623 fn print_either_attributes(&mut self,
624 attrs: &[ast::Attribute],
625 kind: ast::AttrStyle,
627 trailing_hardbreak: bool) -> io::Result<()> {
630 if attr.style == kind {
631 self.print_attribute_inline(attr, is_inline)?;
638 if count > 0 && trailing_hardbreak && !is_inline {
639 self.hardbreak_if_not_bol()?;
644 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
645 for (i, segment) in path.segments.iter().enumerate() {
647 self.writer().word("::")?
649 if segment.ident.name != kw::PathRoot {
650 if segment.ident.name == kw::DollarCrate {
651 self.print_dollar_crate(segment.ident)?;
653 self.writer().word(segment.ident.as_str().to_string())?;
660 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
661 self.print_attribute_inline(attr, false)
664 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
665 is_inline: bool) -> io::Result<()> {
667 self.hardbreak_if_not_bol()?;
669 self.maybe_print_comment(attr.span.lo())?;
670 if attr.is_sugared_doc {
671 self.writer().word(attr.value_str().unwrap().as_str().to_string())?;
672 self.writer().hardbreak()
675 ast::AttrStyle::Inner => self.writer().word("#![")?,
676 ast::AttrStyle::Outer => self.writer().word("#[")?,
678 if let Some(mi) = attr.meta() {
679 self.print_meta_item(&mi)?
681 self.print_attribute_path(&attr.path)?;
682 self.writer().space()?;
683 self.print_tts(attr.tokens.clone())?;
685 self.writer().word("]")
689 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
691 ast::NestedMetaItem::MetaItem(ref mi) => {
692 self.print_meta_item(mi)
694 ast::NestedMetaItem::Literal(ref lit) => {
695 self.print_literal(lit)
700 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
701 self.ibox(INDENT_UNIT)?;
703 ast::MetaItemKind::Word => self.print_attribute_path(&item.path)?,
704 ast::MetaItemKind::NameValue(ref value) => {
705 self.print_attribute_path(&item.path)?;
706 self.writer().space()?;
707 self.word_space("=")?;
708 self.print_literal(value)?;
710 ast::MetaItemKind::List(ref items) => {
711 self.print_attribute_path(&item.path)?;
713 self.commasep(Consistent,
715 |s, i| s.print_meta_list_item(i))?;
722 /// This doesn't deserve to be called "pretty" printing, but it should be
723 /// meaning-preserving. A quick hack that might help would be to look at the
724 /// spans embedded in the TTs to decide where to put spaces and newlines.
725 /// But it'd be better to parse these according to the grammar of the
726 /// appropriate macro, transcribe back into the grammar we just parsed from,
727 /// and then pretty-print the resulting AST nodes (so, e.g., we print
728 /// expression arguments as expressions). It can be done! I think.
729 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
731 TokenTree::Token(ref token) => {
732 self.writer().word(token_to_string(&token))?;
734 token::DocComment(..) => {
735 self.writer().hardbreak()
740 TokenTree::Delimited(_, delim, tts) => {
741 self.writer().word(token_kind_to_string(&token::OpenDelim(delim)))?;
742 self.writer().space()?;
743 self.print_tts(tts)?;
744 self.writer().space()?;
745 self.writer().word(token_kind_to_string(&token::CloseDelim(delim)))
750 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
752 for (i, tt) in tts.into_trees().enumerate() {
754 self.writer().space()?;
761 fn space_if_not_bol(&mut self) -> io::Result<()> {
762 if !self.is_bol() { self.writer().space()?; }
766 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
768 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
769 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
770 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
771 // So we need to somehow pretty-print `$crate` in paths in a way preserving at least some of
772 // its hygiene data, most importantly name of the crate it refers to.
773 // As a result we print `$crate` as `crate` if it refers to the local crate
774 // and as `::other_crate_name` if it refers to some other crate.
775 fn print_dollar_crate(&mut self, ident: ast::Ident) -> io::Result<()> {
776 let name = ident.span.ctxt().dollar_crate_name();
777 if !ast::Ident::with_empty_ctxt(name).is_path_segment_keyword() {
778 self.writer().word("::")?;
780 self.writer().word(name.as_str().to_string())
784 impl<'a> PrintState<'a> for State<'a> {
785 fn writer(&mut self) -> &mut pp::Printer<'a> {
789 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
793 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
797 fn cur_cmnt(&mut self) -> &mut usize {
803 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
804 self.boxes.push(pp::Breaks::Consistent);
808 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
813 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
815 // outer-box is consistent
816 self.cbox(INDENT_UNIT)?;
817 // head-box is inconsistent
818 self.ibox(w.len() + 1)?;
819 // keyword that starts the head
826 pub fn bopen(&mut self) -> io::Result<()> {
828 self.end() // close the head-box
831 pub fn bclose_(&mut self, span: syntax_pos::Span,
832 indented: usize) -> io::Result<()> {
833 self.bclose_maybe_open(span, indented, true)
835 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
836 indented: usize, close_box: bool) -> io::Result<()> {
837 self.maybe_print_comment(span.hi())?;
838 self.break_offset_if_not_bol(1, -(indented as isize))?;
841 self.end()?; // close the outer-box
845 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
846 self.bclose_(span, INDENT_UNIT)
849 pub fn in_cbox(&self) -> bool {
850 match self.boxes.last() {
851 Some(&last_box) => last_box == pp::Breaks::Consistent,
856 pub fn break_offset_if_not_bol(&mut self, n: usize,
857 off: isize) -> io::Result<()> {
859 self.s.break_offset(n, off)
861 if off != 0 && self.s.last_token().is_hardbreak_tok() {
862 // We do something pretty sketchy here: tuck the nonzero
863 // offset-adjustment we were going to deposit along with the
864 // break into the previous hardbreak.
865 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
871 // Synthesizes a comment that was not textually present in the original source
873 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
883 pub fn commasep_cmnt<T, F, G>(&mut self,
887 mut get_span: G) -> io::Result<()> where
888 F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
889 G: FnMut(&T) -> syntax_pos::Span,
892 let len = elts.len();
895 self.maybe_print_comment(get_span(elt).hi())?;
900 self.maybe_print_trailing_comment(get_span(elt),
901 Some(get_span(&elts[i]).hi()))?;
902 self.space_if_not_bol()?;
908 pub fn commasep_exprs(&mut self, b: Breaks,
909 exprs: &[P<ast::Expr>]) -> io::Result<()> {
910 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
913 pub fn print_mod(&mut self, _mod: &ast::Mod,
914 attrs: &[ast::Attribute]) -> io::Result<()> {
915 self.print_inner_attributes(attrs)?;
916 for item in &_mod.items {
917 self.print_item(item)?;
922 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
923 attrs: &[ast::Attribute]) -> io::Result<()> {
924 self.print_inner_attributes(attrs)?;
925 for item in &nmod.items {
926 self.print_foreign_item(item)?;
931 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
932 if let Some(lt) = *lifetime {
933 self.print_lifetime(lt)?;
939 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
941 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
942 GenericArg::Type(ty) => self.print_type(ty),
943 GenericArg::Const(ct) => self.print_expr(&ct.value),
947 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
948 self.maybe_print_comment(ty.span.lo())?;
951 ast::TyKind::Slice(ref ty) => {
953 self.print_type(ty)?;
956 ast::TyKind::Ptr(ref mt) => {
959 ast::Mutability::Mutable => self.word_nbsp("mut")?,
960 ast::Mutability::Immutable => self.word_nbsp("const")?,
962 self.print_type(&mt.ty)?;
964 ast::TyKind::Rptr(ref lifetime, ref mt) => {
966 self.print_opt_lifetime(lifetime)?;
969 ast::TyKind::Never => {
972 ast::TyKind::Tup(ref elts) => {
974 self.commasep(Inconsistent, &elts[..],
975 |s, ty| s.print_type(ty))?;
981 ast::TyKind::Paren(ref typ) => {
983 self.print_type(typ)?;
986 ast::TyKind::BareFn(ref f) => {
987 self.print_ty_fn(f.abi,
993 ast::TyKind::Path(None, ref path) => {
994 self.print_path(path, false, 0)?;
996 ast::TyKind::Path(Some(ref qself), ref path) => {
997 self.print_qpath(path, qself, false)?
999 ast::TyKind::TraitObject(ref bounds, syntax) => {
1000 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1001 self.print_type_bounds(prefix, &bounds[..])?;
1003 ast::TyKind::ImplTrait(_, ref bounds) => {
1004 self.print_type_bounds("impl", &bounds[..])?;
1006 ast::TyKind::Array(ref ty, ref length) => {
1008 self.print_type(ty)?;
1010 self.print_expr(&length.value)?;
1013 ast::TyKind::Typeof(ref e) => {
1014 self.s.word("typeof(")?;
1015 self.print_expr(&e.value)?;
1018 ast::TyKind::Infer => {
1021 ast::TyKind::Err => {
1023 self.s.word("/*ERROR*/")?;
1026 ast::TyKind::ImplicitSelf => {
1027 self.s.word("Self")?;
1029 ast::TyKind::Mac(ref m) => {
1032 ast::TyKind::CVarArgs => {
1033 self.s.word("...")?;
1039 pub fn print_foreign_item(&mut self,
1040 item: &ast::ForeignItem) -> io::Result<()> {
1041 self.hardbreak_if_not_bol()?;
1042 self.maybe_print_comment(item.span.lo())?;
1043 self.print_outer_attributes(&item.attrs)?;
1045 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1047 self.print_fn(decl, ast::FnHeader::default(),
1049 generics, &item.vis)?;
1050 self.end()?; // end head-ibox
1052 self.end() // end the outer fn box
1054 ast::ForeignItemKind::Static(ref t, m) => {
1055 self.head(visibility_qualified(&item.vis, "static"))?;
1056 if m == ast::Mutability::Mutable {
1057 self.word_space("mut")?;
1059 self.print_ident(item.ident)?;
1060 self.word_space(":")?;
1061 self.print_type(t)?;
1063 self.end()?; // end the head-ibox
1064 self.end() // end the outer cbox
1066 ast::ForeignItemKind::Ty => {
1067 self.head(visibility_qualified(&item.vis, "type"))?;
1068 self.print_ident(item.ident)?;
1070 self.end()?; // end the head-ibox
1071 self.end() // end the outer cbox
1073 ast::ForeignItemKind::Macro(ref m) => {
1075 match m.node.delim {
1076 MacDelimiter::Brace => Ok(()),
1077 _ => self.s.word(";")
1083 fn print_associated_const(&mut self,
1086 default: Option<&ast::Expr>,
1087 vis: &ast::Visibility)
1090 self.s.word(visibility_qualified(vis, ""))?;
1091 self.word_space("const")?;
1092 self.print_ident(ident)?;
1093 self.word_space(":")?;
1094 self.print_type(ty)?;
1095 if let Some(expr) = default {
1097 self.word_space("=")?;
1098 self.print_expr(expr)?;
1103 fn print_associated_type(&mut self,
1105 bounds: Option<&ast::GenericBounds>,
1106 ty: Option<&ast::Ty>)
1108 self.word_space("type")?;
1109 self.print_ident(ident)?;
1110 if let Some(bounds) = bounds {
1111 self.print_type_bounds(":", bounds)?;
1113 if let Some(ty) = ty {
1115 self.word_space("=")?;
1116 self.print_type(ty)?;
1121 /// Pretty-print an item
1122 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1123 self.hardbreak_if_not_bol()?;
1124 self.maybe_print_comment(item.span.lo())?;
1125 self.print_outer_attributes(&item.attrs)?;
1126 self.ann.pre(self, AnnNode::Item(item))?;
1128 ast::ItemKind::ExternCrate(orig_name) => {
1129 self.head(visibility_qualified(&item.vis, "extern crate"))?;
1130 if let Some(orig_name) = orig_name {
1131 self.print_name(orig_name)?;
1136 self.print_ident(item.ident)?;
1138 self.end()?; // end inner head-block
1139 self.end()?; // end outer head-block
1141 ast::ItemKind::Use(ref tree) => {
1142 self.head(visibility_qualified(&item.vis, "use"))?;
1143 self.print_use_tree(tree)?;
1145 self.end()?; // end inner head-block
1146 self.end()?; // end outer head-block
1148 ast::ItemKind::Static(ref ty, m, ref expr) => {
1149 self.head(visibility_qualified(&item.vis, "static"))?;
1150 if m == ast::Mutability::Mutable {
1151 self.word_space("mut")?;
1153 self.print_ident(item.ident)?;
1154 self.word_space(":")?;
1155 self.print_type(ty)?;
1157 self.end()?; // end the head-ibox
1159 self.word_space("=")?;
1160 self.print_expr(expr)?;
1162 self.end()?; // end the outer cbox
1164 ast::ItemKind::Const(ref ty, ref expr) => {
1165 self.head(visibility_qualified(&item.vis, "const"))?;
1166 self.print_ident(item.ident)?;
1167 self.word_space(":")?;
1168 self.print_type(ty)?;
1170 self.end()?; // end the head-ibox
1172 self.word_space("=")?;
1173 self.print_expr(expr)?;
1175 self.end()?; // end the outer cbox
1177 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1187 self.print_block_with_attrs(body, &item.attrs)?;
1189 ast::ItemKind::Mod(ref _mod) => {
1190 self.head(visibility_qualified(&item.vis, "mod"))?;
1191 self.print_ident(item.ident)?;
1193 if _mod.inline || self.is_expanded {
1196 self.print_mod(_mod, &item.attrs)?;
1197 self.bclose(item.span)?;
1200 self.end()?; // end inner head-block
1201 self.end()?; // end outer head-block
1205 ast::ItemKind::ForeignMod(ref nmod) => {
1206 self.head("extern")?;
1207 self.word_nbsp(nmod.abi.to_string())?;
1209 self.print_foreign_mod(nmod, &item.attrs)?;
1210 self.bclose(item.span)?;
1212 ast::ItemKind::GlobalAsm(ref ga) => {
1213 self.head(visibility_qualified(&item.vis, "global_asm!"))?;
1214 self.s.word(ga.asm.as_str().to_string())?;
1217 ast::ItemKind::Ty(ref ty, ref generics) => {
1218 self.head(visibility_qualified(&item.vis, "type"))?;
1219 self.print_ident(item.ident)?;
1220 self.print_generic_params(&generics.params)?;
1221 self.end()?; // end the inner ibox
1223 self.print_where_clause(&generics.where_clause)?;
1225 self.word_space("=")?;
1226 self.print_type(ty)?;
1228 self.end()?; // end the outer ibox
1230 ast::ItemKind::Existential(ref bounds, ref generics) => {
1231 self.head(visibility_qualified(&item.vis, "existential type"))?;
1232 self.print_ident(item.ident)?;
1233 self.print_generic_params(&generics.params)?;
1234 self.end()?; // end the inner ibox
1236 self.print_where_clause(&generics.where_clause)?;
1238 self.print_type_bounds(":", bounds)?;
1240 self.end()?; // end the outer ibox
1242 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1243 self.print_enum_def(
1251 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1252 self.head(visibility_qualified(&item.vis, "struct"))?;
1253 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1255 ast::ItemKind::Union(ref struct_def, ref generics) => {
1256 self.head(visibility_qualified(&item.vis, "union"))?;
1257 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1259 ast::ItemKind::Impl(unsafety,
1265 ref impl_items) => {
1267 self.print_visibility(&item.vis)?;
1268 self.print_defaultness(defaultness)?;
1269 self.print_unsafety(unsafety)?;
1270 self.word_nbsp("impl")?;
1272 if !generics.params.is_empty() {
1273 self.print_generic_params(&generics.params)?;
1277 if polarity == ast::ImplPolarity::Negative {
1281 if let Some(ref t) = *opt_trait {
1282 self.print_trait_ref(t)?;
1284 self.word_space("for")?;
1287 self.print_type(ty)?;
1288 self.print_where_clause(&generics.where_clause)?;
1292 self.print_inner_attributes(&item.attrs)?;
1293 for impl_item in impl_items {
1294 self.print_impl_item(impl_item)?;
1296 self.bclose(item.span)?;
1298 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1300 self.print_visibility(&item.vis)?;
1301 self.print_unsafety(unsafety)?;
1302 self.print_is_auto(is_auto)?;
1303 self.word_nbsp("trait")?;
1304 self.print_ident(item.ident)?;
1305 self.print_generic_params(&generics.params)?;
1306 let mut real_bounds = Vec::with_capacity(bounds.len());
1307 for b in bounds.iter() {
1308 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1310 self.word_space("for ?")?;
1311 self.print_trait_ref(&ptr.trait_ref)?;
1313 real_bounds.push(b.clone());
1316 self.print_type_bounds(":", &real_bounds[..])?;
1317 self.print_where_clause(&generics.where_clause)?;
1320 for trait_item in trait_items {
1321 self.print_trait_item(trait_item)?;
1323 self.bclose(item.span)?;
1325 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1327 self.print_visibility(&item.vis)?;
1328 self.word_nbsp("trait")?;
1329 self.print_ident(item.ident)?;
1330 self.print_generic_params(&generics.params)?;
1331 let mut real_bounds = Vec::with_capacity(bounds.len());
1332 // FIXME(durka) this seems to be some quite outdated syntax
1333 for b in bounds.iter() {
1334 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1336 self.word_space("for ?")?;
1337 self.print_trait_ref(&ptr.trait_ref)?;
1339 real_bounds.push(b.clone());
1343 self.print_type_bounds("=", &real_bounds[..])?;
1344 self.print_where_clause(&generics.where_clause)?;
1347 ast::ItemKind::Mac(ref mac) => {
1348 if item.ident.name == kw::Invalid {
1349 self.print_mac(mac)?;
1350 match mac.node.delim {
1351 MacDelimiter::Brace => {}
1352 _ => self.s.word(";")?,
1355 self.print_path(&mac.node.path, false, 0)?;
1357 self.print_ident(item.ident)?;
1358 self.cbox(INDENT_UNIT)?;
1360 self.print_tts(mac.node.stream())?;
1366 ast::ItemKind::MacroDef(ref tts) => {
1367 self.s.word("macro_rules! ")?;
1368 self.print_ident(item.ident)?;
1369 self.cbox(INDENT_UNIT)?;
1371 self.print_tts(tts.stream())?;
1377 self.ann.post(self, AnnNode::Item(item))
1380 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1381 self.print_path(&t.path, false, 0)
1384 fn print_formal_generic_params(
1386 generic_params: &[ast::GenericParam]
1387 ) -> io::Result<()> {
1388 if !generic_params.is_empty() {
1389 self.s.word("for")?;
1390 self.print_generic_params(generic_params)?;
1396 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1397 self.print_formal_generic_params(&t.bound_generic_params)?;
1398 self.print_trait_ref(&t.trait_ref)
1401 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1402 generics: &ast::Generics, ident: ast::Ident,
1403 span: syntax_pos::Span,
1404 visibility: &ast::Visibility) -> io::Result<()> {
1405 self.head(visibility_qualified(visibility, "enum"))?;
1406 self.print_ident(ident)?;
1407 self.print_generic_params(&generics.params)?;
1408 self.print_where_clause(&generics.where_clause)?;
1410 self.print_variants(&enum_definition.variants, span)
1413 pub fn print_variants(&mut self,
1414 variants: &[ast::Variant],
1415 span: syntax_pos::Span) -> io::Result<()> {
1418 self.space_if_not_bol()?;
1419 self.maybe_print_comment(v.span.lo())?;
1420 self.print_outer_attributes(&v.node.attrs)?;
1421 self.ibox(INDENT_UNIT)?;
1422 self.print_variant(v)?;
1425 self.maybe_print_trailing_comment(v.span, None)?;
1430 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1432 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1433 ast::VisibilityKind::Crate(sugar) => match sugar {
1434 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1435 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1437 ast::VisibilityKind::Restricted { ref path, .. } => {
1438 let path = to_string(|s| s.print_path(path, false, 0));
1439 if path == "self" || path == "super" {
1440 self.word_nbsp(format!("pub({})", path))
1442 self.word_nbsp(format!("pub(in {})", path))
1445 ast::VisibilityKind::Inherited => Ok(())
1449 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1450 if let ast::Defaultness::Default = defaultness {
1451 self.word_nbsp("default")?;
1456 pub fn print_struct(&mut self,
1457 struct_def: &ast::VariantData,
1458 generics: &ast::Generics,
1460 span: syntax_pos::Span,
1461 print_finalizer: bool) -> io::Result<()> {
1462 self.print_ident(ident)?;
1463 self.print_generic_params(&generics.params)?;
1465 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1466 if let ast::VariantData::Tuple(..) = struct_def {
1469 Inconsistent, struct_def.fields(),
1471 s.maybe_print_comment(field.span.lo())?;
1472 s.print_outer_attributes(&field.attrs)?;
1473 s.print_visibility(&field.vis)?;
1474 s.print_type(&field.ty)
1479 self.print_where_clause(&generics.where_clause)?;
1480 if print_finalizer {
1484 self.end() // close the outer-box
1486 ast::VariantData::Struct(..) => {
1487 self.print_where_clause(&generics.where_clause)?;
1490 self.hardbreak_if_not_bol()?;
1492 for field in struct_def.fields() {
1493 self.hardbreak_if_not_bol()?;
1494 self.maybe_print_comment(field.span.lo())?;
1495 self.print_outer_attributes(&field.attrs)?;
1496 self.print_visibility(&field.vis)?;
1497 self.print_ident(field.ident.unwrap())?;
1498 self.word_nbsp(":")?;
1499 self.print_type(&field.ty)?;
1508 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1510 let generics = ast::Generics::default();
1511 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1512 match v.node.disr_expr {
1515 self.word_space("=")?;
1516 self.print_expr(&d.value)
1522 pub fn print_method_sig(&mut self,
1524 generics: &ast::Generics,
1526 vis: &ast::Visibility)
1528 self.print_fn(&m.decl,
1535 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1537 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1538 self.hardbreak_if_not_bol()?;
1539 self.maybe_print_comment(ti.span.lo())?;
1540 self.print_outer_attributes(&ti.attrs)?;
1542 ast::TraitItemKind::Const(ref ty, ref default) => {
1543 self.print_associated_const(
1546 default.as_ref().map(|expr| &**expr),
1547 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1550 ast::TraitItemKind::Method(ref sig, ref body) => {
1554 self.print_method_sig(
1558 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1560 if let Some(ref body) = *body {
1562 self.print_block_with_attrs(body, &ti.attrs)?;
1567 ast::TraitItemKind::Type(ref bounds, ref default) => {
1568 self.print_associated_type(ti.ident, Some(bounds),
1569 default.as_ref().map(|ty| &**ty))?;
1571 ast::TraitItemKind::Macro(ref mac) => {
1572 self.print_mac(mac)?;
1573 match mac.node.delim {
1574 MacDelimiter::Brace => {}
1575 _ => self.s.word(";")?,
1579 self.ann.post(self, AnnNode::SubItem(ti.id))
1582 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1583 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1584 self.hardbreak_if_not_bol()?;
1585 self.maybe_print_comment(ii.span.lo())?;
1586 self.print_outer_attributes(&ii.attrs)?;
1587 self.print_defaultness(ii.defaultness)?;
1589 ast::ImplItemKind::Const(ref ty, ref expr) => {
1590 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1592 ast::ImplItemKind::Method(ref sig, ref body) => {
1594 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1596 self.print_block_with_attrs(body, &ii.attrs)?;
1598 ast::ImplItemKind::Type(ref ty) => {
1599 self.print_associated_type(ii.ident, None, Some(ty))?;
1601 ast::ImplItemKind::Existential(ref bounds) => {
1602 self.word_space("existential")?;
1603 self.print_associated_type(ii.ident, Some(bounds), None)?;
1605 ast::ImplItemKind::Macro(ref mac) => {
1606 self.print_mac(mac)?;
1607 match mac.node.delim {
1608 MacDelimiter::Brace => {}
1609 _ => self.s.word(";")?,
1613 self.ann.post(self, AnnNode::SubItem(ii.id))
1616 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1617 self.maybe_print_comment(st.span.lo())?;
1619 ast::StmtKind::Local(ref loc) => {
1620 self.print_outer_attributes(&loc.attrs)?;
1621 self.space_if_not_bol()?;
1622 self.ibox(INDENT_UNIT)?;
1623 self.word_nbsp("let")?;
1625 self.ibox(INDENT_UNIT)?;
1626 self.print_local_decl(loc)?;
1628 if let Some(ref init) = loc.init {
1630 self.word_space("=")?;
1631 self.print_expr(init)?;
1636 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1637 ast::StmtKind::Expr(ref expr) => {
1638 self.space_if_not_bol()?;
1639 self.print_expr_outer_attr_style(expr, false)?;
1640 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1644 ast::StmtKind::Semi(ref expr) => {
1645 self.space_if_not_bol()?;
1646 self.print_expr_outer_attr_style(expr, false)?;
1649 ast::StmtKind::Mac(ref mac) => {
1650 let (ref mac, style, ref attrs) = **mac;
1651 self.space_if_not_bol()?;
1652 self.print_outer_attributes(attrs)?;
1653 self.print_mac(mac)?;
1654 if style == ast::MacStmtStyle::Semicolon {
1659 self.maybe_print_trailing_comment(st.span, None)
1662 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1663 self.print_block_with_attrs(blk, &[])
1666 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1667 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1670 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1671 attrs: &[ast::Attribute])
1673 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1676 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1677 indented: usize) -> io::Result<()> {
1678 self.print_block_maybe_unclosed(blk, indented, &[], false)
1681 pub fn print_block_with_attrs(&mut self,
1683 attrs: &[ast::Attribute]) -> io::Result<()> {
1684 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1687 pub fn print_block_maybe_unclosed(&mut self,
1690 attrs: &[ast::Attribute],
1691 close_box: bool) -> io::Result<()> {
1693 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1694 BlockCheckMode::Default => ()
1696 self.maybe_print_comment(blk.span.lo())?;
1697 self.ann.pre(self, AnnNode::Block(blk))?;
1700 self.print_inner_attributes(attrs)?;
1702 for (i, st) in blk.stmts.iter().enumerate() {
1704 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1705 self.maybe_print_comment(st.span.lo())?;
1706 self.space_if_not_bol()?;
1707 self.print_expr_outer_attr_style(expr, false)?;
1708 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1710 _ => self.print_stmt(st)?,
1714 self.bclose_maybe_open(blk.span, indented, close_box)?;
1715 self.ann.post(self, AnnNode::Block(blk))
1718 /// Print a `let pats = scrutinee` expression.
1719 pub fn print_let(&mut self, pats: &[P<ast::Pat>], scrutinee: &ast::Expr) -> io::Result<()> {
1720 self.s.word("let ")?;
1722 self.print_pats(pats)?;
1725 self.word_space("=")?;
1726 self.print_expr_cond_paren(
1728 Self::cond_needs_par(scrutinee)
1729 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1733 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1737 // Another `else if` block.
1738 ast::ExprKind::If(ref i, ref then, ref e) => {
1739 self.cbox(INDENT_UNIT - 1)?;
1741 self.s.word(" else if ")?;
1742 self.print_expr_as_cond(i)?;
1744 self.print_block(then)?;
1745 self.print_else(e.as_ref().map(|e| &**e))
1747 // Final `else` block.
1748 ast::ExprKind::Block(ref b, _) => {
1749 self.cbox(INDENT_UNIT - 1)?;
1751 self.s.word(" else ")?;
1754 // Constraints would be great here!
1756 panic!("print_if saw if with weird alternative");
1764 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1765 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1768 self.print_expr_as_cond(test)?;
1771 self.print_block(blk)?;
1772 self.print_else(elseopt)
1775 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1776 self.print_path(&m.node.path, false, 0)?;
1778 match m.node.delim {
1779 MacDelimiter::Parenthesis => self.popen()?,
1780 MacDelimiter::Bracket => self.s.word("[")?,
1781 MacDelimiter::Brace => {
1786 self.print_tts(m.node.stream())?;
1787 match m.node.delim {
1788 MacDelimiter::Parenthesis => self.pclose(),
1789 MacDelimiter::Bracket => self.s.word("]"),
1790 MacDelimiter::Brace => self.bclose(m.span),
1795 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1797 self.commasep_exprs(Inconsistent, args)?;
1801 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1802 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1805 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1806 /// `if cond { ... }`.
1807 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1808 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1811 /// Does `expr` need parenthesis when printed in a condition position?
1812 fn cond_needs_par(expr: &ast::Expr) -> bool {
1814 // These cases need parens due to the parse error observed in #26461: `if return {}`
1815 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1816 ast::ExprKind::Closure(..) |
1817 ast::ExprKind::Ret(..) |
1818 ast::ExprKind::Break(..) => true,
1820 _ => parser::contains_exterior_struct_lit(expr),
1824 /// Print `expr` or `(expr)` when `needs_par` holds.
1825 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) -> io::Result<()> {
1829 self.print_expr(expr)?;
1836 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1837 attrs: &[Attribute]) -> io::Result<()> {
1838 self.ibox(INDENT_UNIT)?;
1840 self.print_inner_attributes_inline(attrs)?;
1841 self.commasep_exprs(Inconsistent, &exprs[..])?;
1846 fn print_expr_repeat(&mut self,
1847 element: &ast::Expr,
1848 count: &ast::AnonConst,
1849 attrs: &[Attribute]) -> io::Result<()> {
1850 self.ibox(INDENT_UNIT)?;
1852 self.print_inner_attributes_inline(attrs)?;
1853 self.print_expr(element)?;
1854 self.word_space(";")?;
1855 self.print_expr(&count.value)?;
1860 fn print_expr_struct(&mut self,
1862 fields: &[ast::Field],
1863 wth: &Option<P<ast::Expr>>,
1864 attrs: &[Attribute]) -> io::Result<()> {
1865 self.print_path(path, true, 0)?;
1867 self.print_inner_attributes_inline(attrs)?;
1872 s.ibox(INDENT_UNIT)?;
1873 if !field.is_shorthand {
1874 s.print_ident(field.ident)?;
1877 s.print_expr(&field.expr)?;
1883 self.ibox(INDENT_UNIT)?;
1884 if !fields.is_empty() {
1889 self.print_expr(expr)?;
1892 _ => if !fields.is_empty() {
1900 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1901 attrs: &[Attribute]) -> io::Result<()> {
1903 self.print_inner_attributes_inline(attrs)?;
1904 self.commasep_exprs(Inconsistent, &exprs[..])?;
1905 if exprs.len() == 1 {
1911 fn print_expr_call(&mut self,
1913 args: &[P<ast::Expr>]) -> io::Result<()> {
1916 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1917 _ => parser::PREC_POSTFIX,
1920 self.print_expr_maybe_paren(func, prec)?;
1921 self.print_call_post(args)
1924 fn print_expr_method_call(&mut self,
1925 segment: &ast::PathSegment,
1926 args: &[P<ast::Expr>]) -> io::Result<()> {
1927 let base_args = &args[1..];
1928 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1930 self.print_ident(segment.ident)?;
1931 if let Some(ref args) = segment.args {
1932 self.print_generic_args(args, true)?;
1934 self.print_call_post(base_args)
1937 fn print_expr_binary(&mut self,
1940 rhs: &ast::Expr) -> io::Result<()> {
1941 let assoc_op = AssocOp::from_ast_binop(op.node);
1942 let prec = assoc_op.precedence() as i8;
1943 let fixity = assoc_op.fixity();
1945 let (left_prec, right_prec) = match fixity {
1946 Fixity::Left => (prec, prec + 1),
1947 Fixity::Right => (prec + 1, prec),
1948 Fixity::None => (prec + 1, prec + 1),
1951 let left_prec = match (&lhs.node, op.node) {
1952 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1953 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1954 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1955 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1956 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1957 // We are given `(let _ = a) OP b`.
1959 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1960 // as the parser will interpret this as `(let _ = a) OP b`.
1962 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1963 // parens are required since the parser would interpret `let a = b < c` as
1964 // `let a = (b < c)`. To achieve this, we force parens.
1965 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1966 parser::PREC_FORCE_PAREN
1971 self.print_expr_maybe_paren(lhs, left_prec)?;
1973 self.word_space(op.node.to_string())?;
1974 self.print_expr_maybe_paren(rhs, right_prec)
1977 fn print_expr_unary(&mut self,
1979 expr: &ast::Expr) -> io::Result<()> {
1980 self.s.word(ast::UnOp::to_string(op))?;
1981 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1984 fn print_expr_addr_of(&mut self,
1985 mutability: ast::Mutability,
1986 expr: &ast::Expr) -> io::Result<()> {
1988 self.print_mutability(mutability)?;
1989 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1992 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1993 self.print_expr_outer_attr_style(expr, true)
1996 fn print_expr_outer_attr_style(&mut self,
1998 is_inline: bool) -> io::Result<()> {
1999 self.maybe_print_comment(expr.span.lo())?;
2001 let attrs = &expr.attrs;
2003 self.print_outer_attributes_inline(attrs)?;
2005 self.print_outer_attributes(attrs)?;
2008 self.ibox(INDENT_UNIT)?;
2009 self.ann.pre(self, AnnNode::Expr(expr))?;
2011 ast::ExprKind::Box(ref expr) => {
2012 self.word_space("box")?;
2013 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2015 ast::ExprKind::Array(ref exprs) => {
2016 self.print_expr_vec(&exprs[..], attrs)?;
2018 ast::ExprKind::Repeat(ref element, ref count) => {
2019 self.print_expr_repeat(element, count, attrs)?;
2021 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2022 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2024 ast::ExprKind::Tup(ref exprs) => {
2025 self.print_expr_tup(&exprs[..], attrs)?;
2027 ast::ExprKind::Call(ref func, ref args) => {
2028 self.print_expr_call(func, &args[..])?;
2030 ast::ExprKind::MethodCall(ref segment, ref args) => {
2031 self.print_expr_method_call(segment, &args[..])?;
2033 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2034 self.print_expr_binary(op, lhs, rhs)?;
2036 ast::ExprKind::Unary(op, ref expr) => {
2037 self.print_expr_unary(op, expr)?;
2039 ast::ExprKind::AddrOf(m, ref expr) => {
2040 self.print_expr_addr_of(m, expr)?;
2042 ast::ExprKind::Lit(ref lit) => {
2043 self.print_literal(lit)?;
2045 ast::ExprKind::Cast(ref expr, ref ty) => {
2046 let prec = AssocOp::As.precedence() as i8;
2047 self.print_expr_maybe_paren(expr, prec)?;
2049 self.word_space("as")?;
2050 self.print_type(ty)?;
2052 ast::ExprKind::Type(ref expr, ref ty) => {
2053 let prec = AssocOp::Colon.precedence() as i8;
2054 self.print_expr_maybe_paren(expr, prec)?;
2055 self.word_space(":")?;
2056 self.print_type(ty)?;
2058 ast::ExprKind::Let(ref pats, ref scrutinee) => {
2059 self.print_let(pats, scrutinee)?;
2061 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2062 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2064 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2065 if let Some(label) = opt_label {
2066 self.print_ident(label.ident)?;
2067 self.word_space(":")?;
2069 self.head("while")?;
2070 self.print_expr_as_cond(test)?;
2072 self.print_block_with_attrs(blk, attrs)?;
2074 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2075 if let Some(label) = opt_label {
2076 self.print_ident(label.ident)?;
2077 self.word_space(":")?;
2080 self.print_pat(pat)?;
2082 self.word_space("in")?;
2083 self.print_expr_as_cond(iter)?;
2085 self.print_block_with_attrs(blk, attrs)?;
2087 ast::ExprKind::Loop(ref blk, opt_label) => {
2088 if let Some(label) = opt_label {
2089 self.print_ident(label.ident)?;
2090 self.word_space(":")?;
2094 self.print_block_with_attrs(blk, attrs)?;
2096 ast::ExprKind::Match(ref expr, ref arms) => {
2097 self.cbox(INDENT_UNIT)?;
2099 self.word_nbsp("match")?;
2100 self.print_expr_as_cond(expr)?;
2103 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2105 self.print_arm(arm)?;
2107 self.bclose_(expr.span, INDENT_UNIT)?;
2109 ast::ExprKind::Closure(
2110 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2111 self.print_movability(movability)?;
2112 self.print_asyncness(asyncness)?;
2113 self.print_capture_clause(capture_clause)?;
2115 self.print_fn_block_args(decl)?;
2117 self.print_expr(body)?;
2118 self.end()?; // need to close a box
2120 // a box will be closed by print_expr, but we didn't want an overall
2121 // wrapper so we closed the corresponding opening. so create an
2122 // empty box to satisfy the close.
2125 ast::ExprKind::Block(ref blk, opt_label) => {
2126 if let Some(label) = opt_label {
2127 self.print_ident(label.ident)?;
2128 self.word_space(":")?;
2130 // containing cbox, will be closed by print-block at }
2131 self.cbox(INDENT_UNIT)?;
2132 // head-box, will be closed by print-block after {
2134 self.print_block_with_attrs(blk, attrs)?;
2136 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2137 self.word_nbsp("async")?;
2138 self.print_capture_clause(capture_clause)?;
2140 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2141 self.cbox(INDENT_UNIT)?;
2143 self.print_block_with_attrs(blk, attrs)?;
2145 ast::ExprKind::Await(origin, ref expr) => {
2147 ast::AwaitOrigin::MacroLike => {
2148 self.s.word("await!")?;
2149 self.print_expr_maybe_paren(expr, parser::PREC_FORCE_PAREN)?;
2151 ast::AwaitOrigin::FieldLike => {
2152 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2153 self.s.word(".await")?;
2157 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2158 let prec = AssocOp::Assign.precedence() as i8;
2159 self.print_expr_maybe_paren(lhs, prec + 1)?;
2161 self.word_space("=")?;
2162 self.print_expr_maybe_paren(rhs, prec)?;
2164 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2165 let prec = AssocOp::Assign.precedence() as i8;
2166 self.print_expr_maybe_paren(lhs, prec + 1)?;
2168 self.s.word(op.node.to_string())?;
2169 self.word_space("=")?;
2170 self.print_expr_maybe_paren(rhs, prec)?;
2172 ast::ExprKind::Field(ref expr, ident) => {
2173 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2175 self.print_ident(ident)?;
2177 ast::ExprKind::Index(ref expr, ref index) => {
2178 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2180 self.print_expr(index)?;
2183 ast::ExprKind::Range(ref start, ref end, limits) => {
2184 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2185 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2186 // Here we use a fake precedence value so that any child with lower precedence than
2187 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2188 let fake_prec = AssocOp::LOr.precedence() as i8;
2189 if let Some(ref e) = *start {
2190 self.print_expr_maybe_paren(e, fake_prec)?;
2192 if limits == ast::RangeLimits::HalfOpen {
2195 self.s.word("..=")?;
2197 if let Some(ref e) = *end {
2198 self.print_expr_maybe_paren(e, fake_prec)?;
2201 ast::ExprKind::Path(None, ref path) => {
2202 self.print_path(path, true, 0)?
2204 ast::ExprKind::Path(Some(ref qself), ref path) => {
2205 self.print_qpath(path, qself, true)?
2207 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2208 self.s.word("break")?;
2210 if let Some(label) = opt_label {
2211 self.print_ident(label.ident)?;
2214 if let Some(ref expr) = *opt_expr {
2215 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2219 ast::ExprKind::Continue(opt_label) => {
2220 self.s.word("continue")?;
2222 if let Some(label) = opt_label {
2223 self.print_ident(label.ident)?;
2227 ast::ExprKind::Ret(ref result) => {
2228 self.s.word("return")?;
2229 if let Some(ref expr) = *result {
2231 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2234 ast::ExprKind::InlineAsm(ref a) => {
2235 self.s.word("asm!")?;
2237 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2238 self.word_space(":")?;
2240 self.commasep(Inconsistent, &a.outputs, |s, out| {
2241 let constraint = out.constraint.as_str();
2242 let mut ch = constraint.chars();
2244 Some('=') if out.is_rw => {
2245 s.print_string(&format!("+{}", ch.as_str()),
2246 ast::StrStyle::Cooked)?
2248 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2251 s.print_expr(&out.expr)?;
2256 self.word_space(":")?;
2258 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2259 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2266 self.word_space(":")?;
2268 self.commasep(Inconsistent, &a.clobbers,
2270 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2274 let mut options = vec![];
2276 options.push("volatile");
2279 options.push("alignstack");
2281 if a.dialect == ast::AsmDialect::Intel {
2282 options.push("intel");
2285 if !options.is_empty() {
2287 self.word_space(":")?;
2288 self.commasep(Inconsistent, &options,
2290 s.print_string(co, ast::StrStyle::Cooked)?;
2297 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2298 ast::ExprKind::Paren(ref e) => {
2300 self.print_inner_attributes_inline(attrs)?;
2301 self.print_expr(e)?;
2304 ast::ExprKind::Yield(ref e) => {
2305 self.s.word("yield")?;
2309 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2314 ast::ExprKind::Try(ref e) => {
2315 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2318 ast::ExprKind::TryBlock(ref blk) => {
2321 self.print_block_with_attrs(blk, attrs)?
2323 ast::ExprKind::Err => {
2325 self.s.word("/*ERROR*/")?;
2329 self.ann.post(self, AnnNode::Expr(expr))?;
2333 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2334 self.print_pat(&loc.pat)?;
2335 if let Some(ref ty) = loc.ty {
2336 self.word_space(":")?;
2337 self.print_type(ty)?;
2342 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2343 if ident.is_raw_guess() {
2344 self.s.word(format!("r#{}", ident))?;
2346 self.s.word(ident.as_str().to_string())?;
2348 self.ann.post(self, AnnNode::Ident(&ident))
2351 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2352 self.s.word(i.to_string())
2355 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2356 self.s.word(name.as_str().to_string())?;
2357 self.ann.post(self, AnnNode::Name(&name))
2360 pub fn print_for_decl(&mut self, loc: &ast::Local,
2361 coll: &ast::Expr) -> io::Result<()> {
2362 self.print_local_decl(loc)?;
2364 self.word_space("in")?;
2365 self.print_expr(coll)
2368 fn print_path(&mut self,
2370 colons_before_params: bool,
2374 self.maybe_print_comment(path.span.lo())?;
2376 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2380 self.print_path_segment(segment, colons_before_params)?;
2386 fn print_path_segment(&mut self,
2387 segment: &ast::PathSegment,
2388 colons_before_params: bool)
2391 if segment.ident.name != kw::PathRoot {
2392 if segment.ident.name == kw::DollarCrate {
2393 self.print_dollar_crate(segment.ident)?;
2395 self.print_ident(segment.ident)?;
2397 if let Some(ref args) = segment.args {
2398 self.print_generic_args(args, colons_before_params)?;
2404 fn print_qpath(&mut self,
2407 colons_before_params: bool)
2411 self.print_type(&qself.ty)?;
2412 if qself.position > 0 {
2414 self.word_space("as")?;
2415 let depth = path.segments.len() - qself.position;
2416 self.print_path(path, false, depth)?;
2420 let item_segment = path.segments.last().unwrap();
2421 self.print_ident(item_segment.ident)?;
2422 match item_segment.args {
2423 Some(ref args) => self.print_generic_args(args, colons_before_params),
2428 fn print_generic_args(&mut self,
2429 args: &ast::GenericArgs,
2430 colons_before_params: bool)
2433 if colons_before_params {
2438 ast::GenericArgs::AngleBracketed(ref data) => {
2441 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2442 s.print_generic_arg(generic_arg)
2445 let mut comma = data.args.len() != 0;
2447 for constraint in data.constraints.iter() {
2449 self.word_space(",")?
2451 self.print_ident(constraint.ident)?;
2453 match constraint.kind {
2454 ast::AssocTyConstraintKind::Equality { ref ty } => {
2455 self.word_space("=")?;
2456 self.print_type(ty)?;
2458 ast::AssocTyConstraintKind::Bound { ref bounds } => {
2459 self.print_type_bounds(":", &*bounds)?;
2468 ast::GenericArgs::Parenthesized(ref data) => {
2473 |s, ty| s.print_type(ty))?;
2476 if let Some(ref ty) = data.output {
2477 self.space_if_not_bol()?;
2478 self.word_space("->")?;
2479 self.print_type(ty)?;
2487 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2488 self.maybe_print_comment(pat.span.lo())?;
2489 self.ann.pre(self, AnnNode::Pat(pat))?;
2490 /* Pat isn't normalized, but the beauty of it
2491 is that it doesn't matter */
2493 PatKind::Wild => self.s.word("_")?,
2494 PatKind::Ident(binding_mode, ident, ref sub) => {
2495 match binding_mode {
2496 ast::BindingMode::ByRef(mutbl) => {
2497 self.word_nbsp("ref")?;
2498 self.print_mutability(mutbl)?;
2500 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2501 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2502 self.word_nbsp("mut")?;
2505 self.print_ident(ident)?;
2506 if let Some(ref p) = *sub {
2511 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2512 self.print_path(path, true, 0)?;
2514 if let Some(ddpos) = ddpos {
2515 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2517 self.word_space(",")?;
2520 if ddpos != elts.len() {
2522 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2525 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2529 PatKind::Path(None, ref path) => {
2530 self.print_path(path, true, 0)?;
2532 PatKind::Path(Some(ref qself), ref path) => {
2533 self.print_qpath(path, qself, false)?;
2535 PatKind::Struct(ref path, ref fields, etc) => {
2536 self.print_path(path, true, 0)?;
2538 self.word_space("{")?;
2540 Consistent, &fields[..],
2542 s.cbox(INDENT_UNIT)?;
2543 if !f.node.is_shorthand {
2544 s.print_ident(f.node.ident)?;
2547 s.print_pat(&f.node.pat)?;
2550 |f| f.node.pat.span)?;
2552 if !fields.is_empty() { self.word_space(",")?; }
2558 PatKind::Tuple(ref elts, ddpos) => {
2560 if let Some(ddpos) = ddpos {
2561 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2563 self.word_space(",")?;
2566 if ddpos != elts.len() {
2568 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2571 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2572 if elts.len() == 1 {
2578 PatKind::Box(ref inner) => {
2579 self.s.word("box ")?;
2580 self.print_pat(inner)?;
2582 PatKind::Ref(ref inner, mutbl) => {
2584 if mutbl == ast::Mutability::Mutable {
2585 self.s.word("mut ")?;
2587 self.print_pat(inner)?;
2589 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2590 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2591 self.print_expr(begin)?;
2594 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2595 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2596 RangeEnd::Excluded => self.s.word("..")?,
2598 self.print_expr(end)?;
2600 PatKind::Slice(ref before, ref slice, ref after) => {
2602 self.commasep(Inconsistent,
2604 |s, p| s.print_pat(p))?;
2605 if let Some(ref p) = *slice {
2606 if !before.is_empty() { self.word_space(",")?; }
2607 if let PatKind::Wild = p.node {
2613 if !after.is_empty() { self.word_space(",")?; }
2615 self.commasep(Inconsistent,
2617 |s, p| s.print_pat(p))?;
2620 PatKind::Paren(ref inner) => {
2622 self.print_pat(inner)?;
2625 PatKind::Mac(ref m) => self.print_mac(m)?,
2627 self.ann.post(self, AnnNode::Pat(pat))
2630 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2631 let mut first = true;
2637 self.word_space("|")?;
2644 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2645 // I have no idea why this check is necessary, but here it
2647 if arm.attrs.is_empty() {
2650 self.cbox(INDENT_UNIT)?;
2652 self.maybe_print_comment(arm.pats[0].span.lo())?;
2653 self.print_outer_attributes(&arm.attrs)?;
2654 self.print_pats(&arm.pats)?;
2656 if let Some(ref e) = arm.guard {
2657 self.word_space("if")?;
2658 self.print_expr(e)?;
2661 self.word_space("=>")?;
2663 match arm.body.node {
2664 ast::ExprKind::Block(ref blk, opt_label) => {
2665 if let Some(label) = opt_label {
2666 self.print_ident(label.ident)?;
2667 self.word_space(":")?;
2670 // the block will close the pattern's ibox
2671 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2673 // If it is a user-provided unsafe block, print a comma after it
2674 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2679 self.end()?; // close the ibox for the pattern
2680 self.print_expr(&arm.body)?;
2684 self.end() // close enclosing cbox
2687 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2688 match explicit_self.node {
2689 SelfKind::Value(m) => {
2690 self.print_mutability(m)?;
2693 SelfKind::Region(ref lt, m) => {
2695 self.print_opt_lifetime(lt)?;
2696 self.print_mutability(m)?;
2699 SelfKind::Explicit(ref typ, m) => {
2700 self.print_mutability(m)?;
2701 self.s.word("self")?;
2702 self.word_space(":")?;
2703 self.print_type(typ)
2708 pub fn print_fn(&mut self,
2710 header: ast::FnHeader,
2711 name: Option<ast::Ident>,
2712 generics: &ast::Generics,
2713 vis: &ast::Visibility) -> io::Result<()> {
2714 self.print_fn_header_info(header, vis)?;
2716 if let Some(name) = name {
2718 self.print_ident(name)?;
2720 self.print_generic_params(&generics.params)?;
2721 self.print_fn_args_and_ret(decl)?;
2722 self.print_where_clause(&generics.where_clause)
2725 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2728 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2731 self.print_fn_output(decl)
2734 pub fn print_fn_block_args(
2739 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2742 if let ast::FunctionRetTy::Default(..) = decl.output {
2746 self.space_if_not_bol()?;
2747 self.word_space("->")?;
2749 ast::FunctionRetTy::Ty(ref ty) => {
2750 self.print_type(ty)?;
2751 self.maybe_print_comment(ty.span.lo())
2753 ast::FunctionRetTy::Default(..) => unreachable!(),
2757 pub fn print_movability(&mut self, movability: ast::Movability)
2760 ast::Movability::Static => self.word_space("static"),
2761 ast::Movability::Movable => Ok(()),
2765 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2767 if asyncness.is_async() {
2768 self.word_nbsp("async")?;
2773 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2775 match capture_clause {
2776 ast::CaptureBy::Value => self.word_space("move"),
2777 ast::CaptureBy::Ref => Ok(()),
2781 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
2783 if !bounds.is_empty() {
2784 self.s.word(prefix)?;
2785 let mut first = true;
2786 for bound in bounds {
2787 if !(first && prefix.is_empty()) {
2793 self.word_space("+")?;
2797 GenericBound::Trait(tref, modifier) => {
2798 if modifier == &TraitBoundModifier::Maybe {
2801 self.print_poly_trait_ref(tref)?;
2803 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2810 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2811 self.print_name(lifetime.ident.name)
2814 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2817 self.print_lifetime(lifetime)?;
2818 if !bounds.is_empty() {
2820 for (i, bound) in bounds.iter().enumerate() {
2822 self.s.word(" + ")?;
2825 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2833 pub fn print_generic_params(
2835 generic_params: &[ast::GenericParam]
2836 ) -> io::Result<()> {
2837 if generic_params.is_empty() {
2843 self.commasep(Inconsistent, &generic_params, |s, param| {
2845 ast::GenericParamKind::Lifetime => {
2846 s.print_outer_attributes_inline(¶m.attrs)?;
2847 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2848 s.print_lifetime_bounds(lt, ¶m.bounds)
2850 ast::GenericParamKind::Type { ref default } => {
2851 s.print_outer_attributes_inline(¶m.attrs)?;
2852 s.print_ident(param.ident)?;
2853 s.print_type_bounds(":", ¶m.bounds)?;
2855 Some(ref default) => {
2858 s.print_type(default)
2863 ast::GenericParamKind::Const { ref ty } => {
2864 s.print_outer_attributes_inline(¶m.attrs)?;
2865 s.word_space("const")?;
2866 s.print_ident(param.ident)?;
2870 s.print_type_bounds(":", ¶m.bounds)
2879 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2881 if where_clause.predicates.is_empty() {
2886 self.word_space("where")?;
2888 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2890 self.word_space(",")?;
2894 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2895 ref bound_generic_params,
2900 self.print_formal_generic_params(bound_generic_params)?;
2901 self.print_type(bounded_ty)?;
2902 self.print_type_bounds(":", bounds)?;
2904 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2907 self.print_lifetime_bounds(*lifetime, bounds)?;
2909 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2912 self.print_type(lhs_ty)?;
2914 self.word_space("=")?;
2915 self.print_type(rhs_ty)?;
2923 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2925 ast::UseTreeKind::Simple(rename, ..) => {
2926 self.print_path(&tree.prefix, false, 0)?;
2927 if let Some(rename) = rename {
2929 self.word_space("as")?;
2930 self.print_ident(rename)?;
2933 ast::UseTreeKind::Glob => {
2934 if !tree.prefix.segments.is_empty() {
2935 self.print_path(&tree.prefix, false, 0)?;
2940 ast::UseTreeKind::Nested(ref items) => {
2941 if tree.prefix.segments.is_empty() {
2944 self.print_path(&tree.prefix, false, 0)?;
2945 self.s.word("::{")?;
2947 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2948 this.print_use_tree(tree)
2957 pub fn print_mutability(&mut self,
2958 mutbl: ast::Mutability) -> io::Result<()> {
2960 ast::Mutability::Mutable => self.word_nbsp("mut"),
2961 ast::Mutability::Immutable => Ok(()),
2965 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2966 self.print_mutability(mt.mutbl)?;
2967 self.print_type(&mt.ty)
2970 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2971 self.ibox(INDENT_UNIT)?;
2972 match input.ty.node {
2973 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2975 if let Some(eself) = input.to_self() {
2976 self.print_explicit_self(&eself)?;
2978 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2979 ident.name == kw::Invalid
2984 self.print_pat(&input.pat)?;
2988 self.print_type(&input.ty)?;
2995 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2996 if let ast::FunctionRetTy::Default(..) = decl.output {
3000 self.space_if_not_bol()?;
3001 self.ibox(INDENT_UNIT)?;
3002 self.word_space("->")?;
3004 ast::FunctionRetTy::Default(..) => unreachable!(),
3005 ast::FunctionRetTy::Ty(ref ty) =>
3006 self.print_type(ty)?
3011 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3016 pub fn print_ty_fn(&mut self,
3018 unsafety: ast::Unsafety,
3020 name: Option<ast::Ident>,
3021 generic_params: &[ast::GenericParam])
3023 self.ibox(INDENT_UNIT)?;
3024 if !generic_params.is_empty() {
3025 self.s.word("for")?;
3026 self.print_generic_params(generic_params)?;
3028 let generics = ast::Generics {
3030 where_clause: ast::WhereClause {
3031 predicates: Vec::new(),
3032 span: syntax_pos::DUMMY_SP,
3034 span: syntax_pos::DUMMY_SP,
3037 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3040 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3044 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3045 next_pos: Option<BytePos>)
3047 let cm = match self.cm {
3051 if let Some(ref cmnt) = self.next_comment() {
3052 if cmnt.style != comments::Trailing { return Ok(()) }
3053 let span_line = cm.lookup_char_pos(span.hi());
3054 let comment_line = cm.lookup_char_pos(cmnt.pos);
3055 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
3056 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3057 self.print_comment(cmnt)?;
3063 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3064 // If there aren't any remaining comments, then we need to manually
3065 // make sure there is a line break at the end.
3066 if self.next_comment().is_none() {
3067 self.s.hardbreak()?;
3069 while let Some(ref cmnt) = self.next_comment() {
3070 self.print_comment(cmnt)?;
3075 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3076 opt_abi: Option<Abi>)
3079 Some(Abi::Rust) => Ok(()),
3081 self.word_nbsp("extern")?;
3082 self.word_nbsp(abi.to_string())
3088 pub fn print_extern_opt_abi(&mut self,
3089 opt_abi: Option<Abi>) -> io::Result<()> {
3092 self.word_nbsp("extern")?;
3093 self.word_nbsp(abi.to_string())
3099 pub fn print_fn_header_info(&mut self,
3100 header: ast::FnHeader,
3101 vis: &ast::Visibility) -> io::Result<()> {
3102 self.s.word(visibility_qualified(vis, ""))?;
3104 match header.constness.node {
3105 ast::Constness::NotConst => {}
3106 ast::Constness::Const => self.word_nbsp("const")?
3109 self.print_asyncness(header.asyncness.node)?;
3110 self.print_unsafety(header.unsafety)?;
3112 if header.abi != Abi::Rust {
3113 self.word_nbsp("extern")?;
3114 self.word_nbsp(header.abi.to_string())?;
3120 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3122 ast::Unsafety::Normal => Ok(()),
3123 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3127 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3129 ast::IsAuto::Yes => self.word_nbsp("auto"),
3130 ast::IsAuto::No => Ok(()),
3140 use crate::source_map;
3141 use crate::with_default_globals;
3145 fn test_fun_to_string() {
3146 with_default_globals(|| {
3147 let abba_ident = ast::Ident::from_str("abba");
3149 let decl = ast::FnDecl {
3151 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3154 let generics = ast::Generics::default();
3159 unsafety: ast::Unsafety::Normal,
3160 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3161 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
3173 fn test_variant_to_string() {
3174 with_default_globals(|| {
3175 let ident = ast::Ident::from_str("principal_skinner");
3177 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3180 id: ast::DUMMY_NODE_ID,
3181 // making this up as I go.... ?
3182 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3186 let varstr = variant_to_string(&var);
3187 assert_eq!(varstr, "principal_skinner");