1 use crate::pp::Breaks::{Consistent, Inconsistent};
2 use crate::pp::{self, Breaks};
6 use rustc_ast::token::{self, BinOpToken, CommentKind, DelimToken, Nonterminal, Token, TokenKind};
7 use rustc_ast::tokenstream::{TokenStream, TokenTree};
8 use rustc_ast::util::classify;
9 use rustc_ast::util::comments::{gather_comments, Comment, CommentStyle};
10 use rustc_ast::util::parser::{self, AssocOp, Fixity};
11 use rustc_ast::{self as ast, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
12 use rustc_ast::{GenericArg, MacArgs, ModKind};
13 use rustc_ast::{GenericBound, SelfKind, TraitBoundModifier};
14 use rustc_ast::{InlineAsmOperand, InlineAsmRegOrRegClass};
15 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
16 use rustc_span::edition::Edition;
17 use rustc_span::source_map::{SourceMap, Spanned};
18 use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol};
19 use rustc_span::{BytePos, FileName, Span};
23 pub enum MacHeader<'a> {
25 Keyword(&'static str),
28 pub enum AnnNode<'a> {
31 Block(&'a ast::Block),
36 Crate(&'a ast::Crate),
40 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
44 #[derive(Copy, Clone)]
47 impl PpAnn for NoAnn {}
49 pub struct Comments<'a> {
51 comments: Vec<Comment>,
55 impl<'a> Comments<'a> {
56 pub fn new(sm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
57 let comments = gather_comments(sm, filename, input);
58 Comments { sm, comments, current: 0 }
61 pub fn next(&self) -> Option<Comment> {
62 self.comments.get(self.current).cloned()
65 pub fn trailing_comment(
67 span: rustc_span::Span,
68 next_pos: Option<BytePos>,
69 ) -> Option<Comment> {
70 if let Some(cmnt) = self.next() {
71 if cmnt.style != CommentStyle::Trailing {
74 let span_line = self.sm.lookup_char_pos(span.hi());
75 let comment_line = self.sm.lookup_char_pos(cmnt.pos);
76 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
77 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
86 pub struct State<'a> {
88 comments: Option<Comments<'a>>,
89 ann: &'a (dyn PpAnn + 'a),
92 crate const INDENT_UNIT: usize = 4;
94 /// Requires you to pass an input filename and reader so that
95 /// it can scan the input text for comments to copy forward.
96 pub fn print_crate<'a>(
106 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann };
108 if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
109 // We need to print `#![no_std]` (and its feature gate) so that
110 // compiling pretty-printed source won't inject libstd again.
111 // However, we don't want these attributes in the AST because
112 // of the feature gate, so we fake them up here.
114 // `#![feature(prelude_import)]`
115 let pi_nested = attr::mk_nested_word_item(Ident::with_dummy_span(sym::prelude_import));
116 let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), vec![pi_nested]);
117 let fake_attr = attr::mk_attr_inner(list);
118 s.print_attribute(&fake_attr);
120 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
121 // root, so this is not needed, and actually breaks things.
122 if edition == Edition::Edition2015 {
124 let no_std_meta = attr::mk_word_item(Ident::with_dummy_span(sym::no_std));
125 let fake_attr = attr::mk_attr_inner(no_std_meta);
126 s.print_attribute(&fake_attr);
130 s.print_inner_attributes(&krate.attrs);
131 for item in &krate.items {
134 s.print_remaining_comments();
135 s.ann.post(&mut s, AnnNode::Crate(krate));
139 /// This makes printed token streams look slightly nicer,
140 /// and also addresses some specific regressions described in #63896 and #73345.
141 fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool {
142 if let TokenTree::Token(token) = prev {
143 if matches!(token.kind, token::Dot | token::Dollar) {
146 if let token::DocComment(comment_kind, ..) = token.kind {
147 return comment_kind != CommentKind::Line;
151 TokenTree::Token(token) => !matches!(token.kind, token::Comma | token::Not | token::Dot),
152 TokenTree::Delimited(_, DelimToken::Paren, _) => {
153 !matches!(prev, TokenTree::Token(Token { kind: token::Ident(..), .. }))
155 TokenTree::Delimited(_, DelimToken::Bracket, _) => {
156 !matches!(prev, TokenTree::Token(Token { kind: token::Pound, .. }))
158 TokenTree::Delimited(..) => true,
162 fn binop_to_string(op: BinOpToken) -> &'static str {
168 token::Percent => "%",
177 fn doc_comment_to_string(
178 comment_kind: CommentKind,
179 attr_style: ast::AttrStyle,
182 match (comment_kind, attr_style) {
183 (CommentKind::Line, ast::AttrStyle::Outer) => format!("///{}", data),
184 (CommentKind::Line, ast::AttrStyle::Inner) => format!("//!{}", data),
185 (CommentKind::Block, ast::AttrStyle::Outer) => format!("/**{}*/", data),
186 (CommentKind::Block, ast::AttrStyle::Inner) => format!("/*!{}*/", data),
190 pub fn literal_to_string(lit: token::Lit) -> String {
191 let token::Lit { kind, symbol, suffix } = lit;
192 let mut out = match kind {
193 token::Byte => format!("b'{}'", symbol),
194 token::Char => format!("'{}'", symbol),
195 token::Str => format!("\"{}\"", symbol),
196 token::StrRaw(n) => {
197 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
199 token::ByteStr => format!("b\"{}\"", symbol),
200 token::ByteStrRaw(n) => {
201 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
203 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
206 if let Some(suffix) = suffix {
207 out.push_str(suffix.as_str())
213 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
214 format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s)
217 impl std::ops::Deref for State<'_> {
218 type Target = pp::Printer;
219 fn deref(&self) -> &Self::Target {
224 impl std::ops::DerefMut for State<'_> {
225 fn deref_mut(&mut self) -> &mut Self::Target {
230 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
231 fn comments(&mut self) -> &mut Option<Comments<'a>>;
232 fn print_ident(&mut self, ident: Ident);
233 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
243 F: FnMut(&mut Self, &T),
246 if let Some((first, rest)) = elts.split_first() {
252 self.word_space(sep);
259 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
261 F: FnMut(&mut Self, &T),
263 self.strsep(",", false, b, elts, op)
266 fn maybe_print_comment(&mut self, pos: BytePos) -> bool {
267 let mut has_comment = false;
268 while let Some(ref cmnt) = self.next_comment() {
271 self.print_comment(cmnt);
279 fn print_comment(&mut self, cmnt: &Comment) {
281 CommentStyle::Mixed => {
282 if !self.is_beginning_of_line() {
285 if let Some((last, lines)) = cmnt.lines.split_last() {
289 self.word(line.clone());
293 self.word(last.clone());
300 CommentStyle::Isolated => {
301 self.hardbreak_if_not_bol();
302 for line in &cmnt.lines {
303 // Don't print empty lines because they will end up as trailing
305 if !line.is_empty() {
306 self.word(line.clone());
311 CommentStyle::Trailing => {
312 if !self.is_beginning_of_line() {
315 if cmnt.lines.len() == 1 {
316 self.word(cmnt.lines[0].clone());
320 for line in &cmnt.lines {
321 if !line.is_empty() {
322 self.word(line.clone());
329 CommentStyle::BlankLine => {
330 // We need to do at least one, possibly two hardbreaks.
331 let twice = match self.last_token() {
332 pp::Token::String(s) => ";" == s,
333 pp::Token::Begin(_) => true,
334 pp::Token::End => true,
343 if let Some(cmnts) = self.comments() {
348 fn next_comment(&mut self) -> Option<Comment> {
349 self.comments().as_mut().and_then(|c| c.next())
352 fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option<BytePos>) {
353 if let Some(cmnts) = self.comments() {
354 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
355 self.print_comment(&cmnt);
360 fn print_remaining_comments(&mut self) {
361 // If there aren't any remaining comments, then we need to manually
362 // make sure there is a line break at the end.
363 if self.next_comment().is_none() {
366 while let Some(ref cmnt) = self.next_comment() {
367 self.print_comment(cmnt)
371 fn print_literal(&mut self, lit: &ast::Lit) {
372 self.maybe_print_comment(lit.span.lo());
373 self.word(lit.token.to_string())
376 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
377 let st = match style {
378 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
379 ast::StrStyle::Raw(n) => {
380 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
386 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
387 self.print_string(sym.as_str(), style);
390 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
391 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
394 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool {
395 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
398 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
399 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
402 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool {
403 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
406 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool {
407 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
410 fn print_either_attributes(
412 attrs: &[ast::Attribute],
413 kind: ast::AttrStyle,
415 trailing_hardbreak: bool,
417 let mut printed = false;
419 if attr.style == kind {
420 self.print_attribute_inline(attr, is_inline);
427 if printed && trailing_hardbreak && !is_inline {
428 self.hardbreak_if_not_bol();
433 fn print_attribute(&mut self, attr: &ast::Attribute) {
434 self.print_attribute_inline(attr, false)
437 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
439 self.hardbreak_if_not_bol();
441 self.maybe_print_comment(attr.span.lo());
443 ast::AttrKind::Normal(ref item, _) => {
445 ast::AttrStyle::Inner => self.word("#!["),
446 ast::AttrStyle::Outer => self.word("#["),
448 self.print_attr_item(&item, attr.span);
451 ast::AttrKind::DocComment(comment_kind, data) => {
452 self.word(doc_comment_to_string(comment_kind, attr.style, data));
458 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
461 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
462 Some(MacHeader::Path(&item.path)),
470 MacArgs::Empty | MacArgs::Eq(..) => {
471 self.print_path(&item.path, false, 0);
472 if let MacArgs::Eq(_, token) = &item.args {
474 self.word_space("=");
475 let token_str = self.token_to_string_ext(token, true);
476 self.word(token_str);
483 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
485 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
486 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
490 fn print_meta_item(&mut self, item: &ast::MetaItem) {
491 self.ibox(INDENT_UNIT);
493 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
494 ast::MetaItemKind::NameValue(ref value) => {
495 self.print_path(&item.path, false, 0);
497 self.word_space("=");
498 self.print_literal(value);
500 ast::MetaItemKind::List(ref items) => {
501 self.print_path(&item.path, false, 0);
503 self.commasep(Consistent, &items, |s, i| s.print_meta_list_item(i));
510 /// This doesn't deserve to be called "pretty" printing, but it should be
511 /// meaning-preserving. A quick hack that might help would be to look at the
512 /// spans embedded in the TTs to decide where to put spaces and newlines.
513 /// But it'd be better to parse these according to the grammar of the
514 /// appropriate macro, transcribe back into the grammar we just parsed from,
515 /// and then pretty-print the resulting AST nodes (so, e.g., we print
516 /// expression arguments as expressions). It can be done! I think.
517 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
519 TokenTree::Token(token) => {
520 let token_str = self.token_to_string_ext(&token, convert_dollar_crate);
521 self.word(token_str);
522 if let token::DocComment(..) = token.kind {
526 TokenTree::Delimited(dspan, delim, tts) => {
527 self.print_mac_common(
533 convert_dollar_crate,
540 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
541 let mut iter = tts.trees().peekable();
542 while let Some(tt) = iter.next() {
543 self.print_tt(&tt, convert_dollar_crate);
544 if let Some(next) = iter.peek() {
545 if tt_prepend_space(next, &tt) {
554 header: Option<MacHeader<'_>>,
556 ident: Option<Ident>,
559 convert_dollar_crate: bool,
562 if delim == DelimToken::Brace {
563 self.cbox(INDENT_UNIT);
566 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
567 Some(MacHeader::Keyword(kw)) => self.word(kw),
573 if let Some(ident) = ident {
575 self.print_ident(ident);
578 DelimToken::Brace => {
579 if header.is_some() || has_bang || ident.is_some() {
588 let token_str = self.token_kind_to_string(&token::OpenDelim(delim));
593 self.print_tts(tts, convert_dollar_crate);
596 DelimToken::Brace => {
597 let empty = tts.is_empty();
598 self.bclose(span, empty);
601 let token_str = self.token_kind_to_string(&token::CloseDelim(delim));
609 macro_def: &ast::MacroDef,
612 print_visibility: impl FnOnce(&mut Self),
614 let (kw, has_bang) = if macro_def.macro_rules {
615 ("macro_rules", true)
617 print_visibility(self);
620 self.print_mac_common(
621 Some(MacHeader::Keyword(kw)),
624 macro_def.body.delim(),
625 ¯o_def.body.inner_tokens(),
629 if macro_def.body.need_semicolon() {
634 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
635 self.maybe_print_comment(path.span.lo());
637 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
641 self.print_path_segment(segment, colons_before_params);
645 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
646 if segment.ident.name != kw::PathRoot {
647 self.print_ident(segment.ident);
648 if let Some(ref args) = segment.args {
649 self.print_generic_args(args, colons_before_params);
654 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
656 // Outer-box is consistent.
657 self.cbox(INDENT_UNIT);
658 // Head-box is inconsistent.
659 self.ibox(w.len() + 1);
660 // Keyword that starts the head.
666 fn bopen(&mut self) {
668 self.end(); // Close the head-box.
671 fn bclose_maybe_open(&mut self, span: rustc_span::Span, empty: bool, close_box: bool) {
672 let has_comment = self.maybe_print_comment(span.hi());
673 if !empty || has_comment {
674 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
678 self.end(); // Close the outer-box.
682 fn bclose(&mut self, span: rustc_span::Span, empty: bool) {
683 let close_box = true;
684 self.bclose_maybe_open(span, empty, close_box)
687 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
688 if !self.is_beginning_of_line() {
689 self.break_offset(n, off)
690 } else if off != 0 && self.last_token().is_hardbreak_tok() {
691 // We do something pretty sketchy here: tuck the nonzero
692 // offset-adjustment we were going to deposit along with the
693 // break into the previous hardbreak.
694 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
698 fn nonterminal_to_string(&self, nt: &Nonterminal) -> String {
700 token::NtExpr(ref e) => self.expr_to_string(e),
701 token::NtMeta(ref e) => self.attr_item_to_string(e),
702 token::NtTy(ref e) => self.ty_to_string(e),
703 token::NtPath(ref e) => self.path_to_string(e),
704 token::NtItem(ref e) => self.item_to_string(e),
705 token::NtBlock(ref e) => self.block_to_string(e),
706 token::NtStmt(ref e) => self.stmt_to_string(e),
707 token::NtPat(ref e) => self.pat_to_string(e),
708 token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(),
709 token::NtLifetime(e) => e.to_string(),
710 token::NtLiteral(ref e) => self.expr_to_string(e),
711 token::NtTT(ref tree) => self.tt_to_string(tree),
712 token::NtVis(ref e) => self.vis_to_string(e),
716 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
717 fn token_kind_to_string(&self, tok: &TokenKind) -> Cow<'static, str> {
718 self.token_kind_to_string_ext(tok, None)
721 fn token_kind_to_string_ext(
724 convert_dollar_crate: Option<Span>,
725 ) -> Cow<'static, str> {
727 token::Eq => "=".into(),
728 token::Lt => "<".into(),
729 token::Le => "<=".into(),
730 token::EqEq => "==".into(),
731 token::Ne => "!=".into(),
732 token::Ge => ">=".into(),
733 token::Gt => ">".into(),
734 token::Not => "!".into(),
735 token::Tilde => "~".into(),
736 token::OrOr => "||".into(),
737 token::AndAnd => "&&".into(),
738 token::BinOp(op) => binop_to_string(op).into(),
739 token::BinOpEq(op) => format!("{}=", binop_to_string(op)).into(),
741 /* Structural symbols */
742 token::At => "@".into(),
743 token::Dot => ".".into(),
744 token::DotDot => "..".into(),
745 token::DotDotDot => "...".into(),
746 token::DotDotEq => "..=".into(),
747 token::Comma => ",".into(),
748 token::Semi => ";".into(),
749 token::Colon => ":".into(),
750 token::ModSep => "::".into(),
751 token::RArrow => "->".into(),
752 token::LArrow => "<-".into(),
753 token::FatArrow => "=>".into(),
754 token::OpenDelim(token::Paren) => "(".into(),
755 token::CloseDelim(token::Paren) => ")".into(),
756 token::OpenDelim(token::Bracket) => "[".into(),
757 token::CloseDelim(token::Bracket) => "]".into(),
758 token::OpenDelim(token::Brace) => "{".into(),
759 token::CloseDelim(token::Brace) => "}".into(),
760 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => "".into(),
761 token::Pound => "#".into(),
762 token::Dollar => "$".into(),
763 token::Question => "?".into(),
764 token::SingleQuote => "'".into(),
767 token::Literal(lit) => literal_to_string(lit).into(),
769 /* Name components */
770 token::Ident(s, is_raw) => {
771 IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string().into()
773 token::Lifetime(s) => s.to_string().into(),
776 token::DocComment(comment_kind, attr_style, data) => {
777 doc_comment_to_string(comment_kind, attr_style, data).into()
779 token::Eof => "<eof>".into(),
781 token::Interpolated(ref nt) => self.nonterminal_to_string(nt).into(),
785 /// Print the token precisely, without converting `$crate` into its respective crate name.
786 fn token_to_string(&self, token: &Token) -> Cow<'static, str> {
787 self.token_to_string_ext(token, false)
790 fn token_to_string_ext(&self, token: &Token, convert_dollar_crate: bool) -> Cow<'static, str> {
791 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
792 self.token_kind_to_string_ext(&token.kind, convert_dollar_crate)
795 fn ty_to_string(&self, ty: &ast::Ty) -> String {
796 Self::to_string(|s| s.print_type(ty))
799 fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String {
800 Self::to_string(|s| s.print_type_bounds("", bounds))
803 fn pat_to_string(&self, pat: &ast::Pat) -> String {
804 Self::to_string(|s| s.print_pat(pat))
807 fn expr_to_string(&self, e: &ast::Expr) -> String {
808 Self::to_string(|s| s.print_expr(e))
811 fn tt_to_string(&self, tt: &TokenTree) -> String {
812 Self::to_string(|s| s.print_tt(tt, false))
815 fn tts_to_string(&self, tokens: &TokenStream) -> String {
816 Self::to_string(|s| s.print_tts(tokens, false))
819 fn stmt_to_string(&self, stmt: &ast::Stmt) -> String {
820 Self::to_string(|s| s.print_stmt(stmt))
823 fn item_to_string(&self, i: &ast::Item) -> String {
824 Self::to_string(|s| s.print_item(i))
827 fn generic_params_to_string(&self, generic_params: &[ast::GenericParam]) -> String {
828 Self::to_string(|s| s.print_generic_params(generic_params))
831 fn path_to_string(&self, p: &ast::Path) -> String {
832 Self::to_string(|s| s.print_path(p, false, 0))
835 fn path_segment_to_string(&self, p: &ast::PathSegment) -> String {
836 Self::to_string(|s| s.print_path_segment(p, false))
839 fn vis_to_string(&self, v: &ast::Visibility) -> String {
840 Self::to_string(|s| s.print_visibility(v))
843 fn block_to_string(&self, blk: &ast::Block) -> String {
844 Self::to_string(|s| {
845 // Containing cbox, will be closed by `print_block` at `}`.
847 // Head-ibox, will be closed by `print_block` after `{`.
853 fn meta_list_item_to_string(&self, li: &ast::NestedMetaItem) -> String {
854 Self::to_string(|s| s.print_meta_list_item(li))
857 fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String {
858 Self::to_string(|s| s.print_attr_item(ai, ai.path.span))
861 fn attribute_to_string(&self, attr: &ast::Attribute) -> String {
862 Self::to_string(|s| s.print_attribute(attr))
865 fn param_to_string(&self, arg: &ast::Param) -> String {
866 Self::to_string(|s| s.print_param(arg, false))
869 fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
870 let mut printer = State::new();
876 impl<'a> PrintState<'a> for State<'a> {
877 fn comments(&mut self) -> &mut Option<Comments<'a>> {
881 fn print_ident(&mut self, ident: Ident) {
882 self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
883 self.ann.post(self, AnnNode::Ident(&ident))
886 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
887 if colons_before_params {
892 ast::GenericArgs::AngleBracketed(ref data) => {
894 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
895 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
896 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
901 ast::GenericArgs::Parenthesized(ref data) => {
903 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
905 self.print_fn_ret_ty(&data.output);
912 pub fn new() -> State<'a> {
913 State { s: pp::mk_printer(), comments: None, ann: &NoAnn }
916 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
918 F: FnMut(&mut State<'_>, &T),
919 G: FnMut(&T) -> rustc_span::Span,
922 let len = elts.len();
925 self.maybe_print_comment(get_span(elt).hi());
930 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
931 self.space_if_not_bol();
937 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
938 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
941 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
942 self.print_inner_attributes(attrs);
943 for item in &nmod.items {
944 self.print_foreign_item(item);
948 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
949 if let Some(lt) = *lifetime {
950 self.print_lifetime(lt);
955 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
956 self.print_ident(constraint.ident);
957 constraint.gen_args.as_ref().map(|args| self.print_generic_args(args, false));
959 match &constraint.kind {
960 ast::AssocTyConstraintKind::Equality { ty } => {
961 self.word_space("=");
964 ast::AssocTyConstraintKind::Bound { bounds } => {
965 self.print_type_bounds(":", &*bounds);
970 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
972 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
973 GenericArg::Type(ty) => self.print_type(ty),
974 GenericArg::Const(ct) => self.print_expr(&ct.value),
978 pub fn print_type(&mut self, ty: &ast::Ty) {
979 self.maybe_print_comment(ty.span.lo());
982 ast::TyKind::Slice(ref ty) => {
987 ast::TyKind::Ptr(ref mt) => {
989 self.print_mt(mt, true);
991 ast::TyKind::Rptr(ref lifetime, ref mt) => {
993 self.print_opt_lifetime(lifetime);
994 self.print_mt(mt, false);
996 ast::TyKind::Never => {
999 ast::TyKind::Tup(ref elts) => {
1001 self.commasep(Inconsistent, &elts, |s, ty| s.print_type(ty));
1002 if elts.len() == 1 {
1007 ast::TyKind::Paren(ref typ) => {
1009 self.print_type(typ);
1012 ast::TyKind::BareFn(ref f) => {
1013 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
1015 ast::TyKind::Path(None, ref path) => {
1016 self.print_path(path, false, 0);
1018 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
1019 ast::TyKind::TraitObject(ref bounds, syntax) => {
1020 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1021 self.print_type_bounds(prefix, &bounds);
1023 ast::TyKind::ImplTrait(_, ref bounds) => {
1024 self.print_type_bounds("impl", &bounds);
1026 ast::TyKind::Array(ref ty, ref length) => {
1028 self.print_type(ty);
1030 self.print_expr(&length.value);
1033 ast::TyKind::Typeof(ref e) => {
1034 self.word("typeof(");
1035 self.print_expr(&e.value);
1038 ast::TyKind::Infer => {
1041 ast::TyKind::Err => {
1043 self.word("/*ERROR*/");
1046 ast::TyKind::ImplicitSelf => {
1049 ast::TyKind::MacCall(ref m) => {
1052 ast::TyKind::CVarArgs => {
1059 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1060 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1061 self.ann.pre(self, AnnNode::SubItem(id));
1062 self.hardbreak_if_not_bol();
1063 self.maybe_print_comment(span.lo());
1064 self.print_outer_attributes(attrs);
1066 ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1067 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1069 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1070 let def = ast::Defaultness::Final;
1071 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1073 ast::ForeignItemKind::TyAlias(box ast::TyAlias {
1079 self.print_associated_type(
1088 ast::ForeignItemKind::MacCall(m) => {
1090 if m.args.need_semicolon() {
1095 self.ann.post(self, AnnNode::SubItem(id))
1098 fn print_item_const(
1101 mutbl: Option<ast::Mutability>,
1103 body: Option<&ast::Expr>,
1104 vis: &ast::Visibility,
1105 defaultness: ast::Defaultness,
1108 self.print_visibility(vis);
1109 self.print_defaultness(defaultness);
1110 let leading = match mutbl {
1112 Some(ast::Mutability::Not) => "static",
1113 Some(ast::Mutability::Mut) => "static mut",
1115 self.word_space(leading);
1116 self.print_ident(ident);
1117 self.word_space(":");
1118 self.print_type(ty);
1122 self.end(); // end the head-ibox
1123 if let Some(body) = body {
1124 self.word_space("=");
1125 self.print_expr(body);
1128 self.end(); // end the outer cbox
1131 fn print_associated_type(
1134 generics: &ast::Generics,
1135 bounds: &ast::GenericBounds,
1136 ty: Option<&ast::Ty>,
1137 vis: &ast::Visibility,
1138 defaultness: ast::Defaultness,
1141 self.print_visibility(vis);
1142 self.print_defaultness(defaultness);
1143 self.word_space("type");
1144 self.print_ident(ident);
1145 self.print_generic_params(&generics.params);
1146 self.print_type_bounds(":", bounds);
1147 self.print_where_clause(&generics.where_clause);
1148 if let Some(ty) = ty {
1150 self.word_space("=");
1151 self.print_type(ty);
1154 self.end(); // end inner head-block
1155 self.end(); // end outer head-block
1158 /// Pretty-prints an item.
1159 crate fn print_item(&mut self, item: &ast::Item) {
1160 self.hardbreak_if_not_bol();
1161 self.maybe_print_comment(item.span.lo());
1162 self.print_outer_attributes(&item.attrs);
1163 self.ann.pre(self, AnnNode::Item(item));
1165 ast::ItemKind::ExternCrate(orig_name) => {
1166 self.head(visibility_qualified(&item.vis, "extern crate"));
1167 if let Some(orig_name) = orig_name {
1168 self.print_name(orig_name);
1173 self.print_ident(item.ident);
1175 self.end(); // end inner head-block
1176 self.end(); // end outer head-block
1178 ast::ItemKind::Use(ref tree) => {
1179 self.head(visibility_qualified(&item.vis, "use"));
1180 self.print_use_tree(tree);
1182 self.end(); // end inner head-block
1183 self.end(); // end outer head-block
1185 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1186 let def = ast::Defaultness::Final;
1187 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1189 ast::ItemKind::Const(def, ref ty, ref body) => {
1190 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1192 ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => {
1193 let body = body.as_deref();
1204 ast::ItemKind::Mod(unsafety, ref mod_kind) => {
1205 self.head(Self::to_string(|s| {
1206 s.print_visibility(&item.vis);
1207 s.print_unsafety(unsafety);
1210 self.print_ident(item.ident);
1213 ModKind::Loaded(items, ..) => {
1216 self.print_inner_attributes(&item.attrs);
1218 self.print_item(item);
1220 let empty = item.attrs.is_empty() && items.is_empty();
1221 self.bclose(item.span, empty);
1223 ModKind::Unloaded => {
1225 self.end(); // end inner head-block
1226 self.end(); // end outer head-block
1230 ast::ItemKind::ForeignMod(ref nmod) => {
1231 self.head(Self::to_string(|s| {
1232 s.print_unsafety(nmod.unsafety);
1235 if let Some(abi) = nmod.abi {
1236 self.print_literal(&abi.as_lit());
1240 self.print_foreign_mod(nmod, &item.attrs);
1241 let empty = item.attrs.is_empty() && nmod.items.is_empty();
1242 self.bclose(item.span, empty);
1244 ast::ItemKind::GlobalAsm(ref asm) => {
1245 self.head(visibility_qualified(&item.vis, "global_asm!"));
1246 self.print_inline_asm(asm);
1249 ast::ItemKind::TyAlias(box ast::TyAlias {
1255 let ty = ty.as_deref();
1256 self.print_associated_type(
1265 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1266 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1268 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1269 self.head(visibility_qualified(&item.vis, "struct"));
1270 self.print_struct(struct_def, generics, item.ident, item.span, true);
1272 ast::ItemKind::Union(ref struct_def, ref generics) => {
1273 self.head(visibility_qualified(&item.vis, "union"));
1274 self.print_struct(struct_def, generics, item.ident, item.span, true);
1276 ast::ItemKind::Impl(box ast::Impl {
1287 self.print_visibility(&item.vis);
1288 self.print_defaultness(defaultness);
1289 self.print_unsafety(unsafety);
1292 if generics.params.is_empty() {
1295 self.print_generic_params(&generics.params);
1299 self.print_constness(constness);
1301 if let ast::ImplPolarity::Negative(_) = polarity {
1305 if let Some(ref t) = *of_trait {
1306 self.print_trait_ref(t);
1308 self.word_space("for");
1311 self.print_type(self_ty);
1312 self.print_where_clause(&generics.where_clause);
1316 self.print_inner_attributes(&item.attrs);
1317 for impl_item in items {
1318 self.print_assoc_item(impl_item);
1320 let empty = item.attrs.is_empty() && items.is_empty();
1321 self.bclose(item.span, empty);
1323 ast::ItemKind::Trait(box ast::Trait {
1332 self.print_visibility(&item.vis);
1333 self.print_unsafety(unsafety);
1334 self.print_is_auto(is_auto);
1335 self.word_nbsp("trait");
1336 self.print_ident(item.ident);
1337 self.print_generic_params(&generics.params);
1338 let mut real_bounds = Vec::with_capacity(bounds.len());
1339 for b in bounds.iter() {
1340 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1342 self.word_space("for ?");
1343 self.print_trait_ref(&ptr.trait_ref);
1345 real_bounds.push(b.clone());
1348 self.print_type_bounds(":", &real_bounds);
1349 self.print_where_clause(&generics.where_clause);
1352 self.print_inner_attributes(&item.attrs);
1353 for trait_item in items {
1354 self.print_assoc_item(trait_item);
1356 let empty = item.attrs.is_empty() && items.is_empty();
1357 self.bclose(item.span, empty);
1359 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1360 self.head(visibility_qualified(&item.vis, "trait"));
1361 self.print_ident(item.ident);
1362 self.print_generic_params(&generics.params);
1363 let mut real_bounds = Vec::with_capacity(bounds.len());
1364 // FIXME(durka) this seems to be some quite outdated syntax
1365 for b in bounds.iter() {
1366 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1368 self.word_space("for ?");
1369 self.print_trait_ref(&ptr.trait_ref);
1371 real_bounds.push(b.clone());
1375 self.print_type_bounds("=", &real_bounds);
1376 self.print_where_clause(&generics.where_clause);
1378 self.end(); // end inner head-block
1379 self.end(); // end outer head-block
1381 ast::ItemKind::MacCall(ref mac) => {
1382 self.print_mac(mac);
1383 if mac.args.need_semicolon() {
1387 ast::ItemKind::MacroDef(ref macro_def) => {
1388 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1389 state.print_visibility(&item.vis)
1393 self.ann.post(self, AnnNode::Item(item))
1396 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1397 self.print_path(&t.path, false, 0)
1400 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1401 if !generic_params.is_empty() {
1403 self.print_generic_params(generic_params);
1408 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1409 self.print_formal_generic_params(&t.bound_generic_params);
1410 self.print_trait_ref(&t.trait_ref)
1413 crate fn print_enum_def(
1415 enum_definition: &ast::EnumDef,
1416 generics: &ast::Generics,
1418 span: rustc_span::Span,
1419 visibility: &ast::Visibility,
1421 self.head(visibility_qualified(visibility, "enum"));
1422 self.print_ident(ident);
1423 self.print_generic_params(&generics.params);
1424 self.print_where_clause(&generics.where_clause);
1426 self.print_variants(&enum_definition.variants, span)
1429 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1432 self.space_if_not_bol();
1433 self.maybe_print_comment(v.span.lo());
1434 self.print_outer_attributes(&v.attrs);
1435 self.ibox(INDENT_UNIT);
1436 self.print_variant(v);
1439 self.maybe_print_trailing_comment(v.span, None);
1441 let empty = variants.is_empty();
1442 self.bclose(span, empty)
1445 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1447 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1448 ast::VisibilityKind::Crate(sugar) => match sugar {
1449 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1450 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1452 ast::VisibilityKind::Restricted { ref path, .. } => {
1453 let path = Self::to_string(|s| s.print_path(path, false, 0));
1454 if path == "self" || path == "super" {
1455 self.word_nbsp(format!("pub({})", path))
1457 self.word_nbsp(format!("pub(in {})", path))
1460 ast::VisibilityKind::Inherited => {}
1464 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1465 if let ast::Defaultness::Default(_) = defaultness {
1466 self.word_nbsp("default");
1470 crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1474 let empty = fields.is_empty();
1476 self.hardbreak_if_not_bol();
1478 for field in fields {
1479 self.hardbreak_if_not_bol();
1480 self.maybe_print_comment(field.span.lo());
1481 self.print_outer_attributes(&field.attrs);
1482 self.print_visibility(&field.vis);
1483 self.print_ident(field.ident.unwrap());
1484 self.word_nbsp(":");
1485 self.print_type(&field.ty);
1490 self.bclose(span, empty);
1493 crate fn print_struct(
1495 struct_def: &ast::VariantData,
1496 generics: &ast::Generics,
1498 span: rustc_span::Span,
1499 print_finalizer: bool,
1501 self.print_ident(ident);
1502 self.print_generic_params(&generics.params);
1504 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1505 if let ast::VariantData::Tuple(..) = struct_def {
1507 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1508 s.maybe_print_comment(field.span.lo());
1509 s.print_outer_attributes(&field.attrs);
1510 s.print_visibility(&field.vis);
1511 s.print_type(&field.ty)
1515 self.print_where_clause(&generics.where_clause);
1516 if print_finalizer {
1520 self.end(); // Close the outer-box.
1522 ast::VariantData::Struct(ref fields, ..) => {
1523 self.print_where_clause(&generics.where_clause);
1524 self.print_record_struct_body(fields, span);
1529 crate fn print_variant(&mut self, v: &ast::Variant) {
1531 self.print_visibility(&v.vis);
1532 let generics = ast::Generics::default();
1533 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1534 if let Some(ref d) = v.disr_expr {
1536 self.word_space("=");
1537 self.print_expr(&d.value)
1541 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1542 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1543 self.ann.pre(self, AnnNode::SubItem(id));
1544 self.hardbreak_if_not_bol();
1545 self.maybe_print_comment(span.lo());
1546 self.print_outer_attributes(attrs);
1548 ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1549 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1551 ast::AssocItemKind::Const(def, ty, body) => {
1552 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1554 ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
1555 self.print_associated_type(
1564 ast::AssocItemKind::MacCall(m) => {
1566 if m.args.need_semicolon() {
1571 self.ann.post(self, AnnNode::SubItem(id))
1574 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1575 self.maybe_print_comment(st.span.lo());
1577 ast::StmtKind::Local(ref loc) => {
1578 self.print_outer_attributes(&loc.attrs);
1579 self.space_if_not_bol();
1580 self.ibox(INDENT_UNIT);
1581 self.word_nbsp("let");
1583 self.ibox(INDENT_UNIT);
1584 self.print_local_decl(loc);
1586 if let Some((init, els)) = loc.kind.init_else_opt() {
1588 self.word_space("=");
1589 self.print_expr(init);
1590 if let Some(els) = els {
1591 self.cbox(INDENT_UNIT);
1592 self.ibox(INDENT_UNIT);
1593 self.word(" else ");
1594 self.print_block(els);
1598 self.end(); // `let` ibox
1600 ast::StmtKind::Item(ref item) => self.print_item(item),
1601 ast::StmtKind::Expr(ref expr) => {
1602 self.space_if_not_bol();
1603 self.print_expr_outer_attr_style(expr, false);
1604 if classify::expr_requires_semi_to_be_stmt(expr) {
1608 ast::StmtKind::Semi(ref expr) => {
1609 self.space_if_not_bol();
1610 self.print_expr_outer_attr_style(expr, false);
1613 ast::StmtKind::Empty => {
1614 self.space_if_not_bol();
1617 ast::StmtKind::MacCall(ref mac) => {
1618 self.space_if_not_bol();
1619 self.print_outer_attributes(&mac.attrs);
1620 self.print_mac(&mac.mac);
1621 if mac.style == ast::MacStmtStyle::Semicolon {
1626 self.maybe_print_trailing_comment(st.span, None)
1629 crate fn print_block(&mut self, blk: &ast::Block) {
1630 self.print_block_with_attrs(blk, &[])
1633 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1634 self.print_block_maybe_unclosed(blk, &[], false)
1637 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1638 self.print_block_maybe_unclosed(blk, attrs, true)
1641 crate fn print_block_maybe_unclosed(
1644 attrs: &[ast::Attribute],
1648 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1649 BlockCheckMode::Default => (),
1651 self.maybe_print_comment(blk.span.lo());
1652 self.ann.pre(self, AnnNode::Block(blk));
1655 let has_attrs = self.print_inner_attributes(attrs);
1657 for (i, st) in blk.stmts.iter().enumerate() {
1659 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1660 self.maybe_print_comment(st.span.lo());
1661 self.space_if_not_bol();
1662 self.print_expr_outer_attr_style(expr, false);
1663 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1665 _ => self.print_stmt(st),
1669 let empty = !has_attrs && blk.stmts.is_empty();
1670 self.bclose_maybe_open(blk.span, empty, close_box);
1671 self.ann.post(self, AnnNode::Block(blk))
1674 /// Print a `let pat = expr` expression.
1675 crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1677 self.print_pat(pat);
1679 self.word_space("=");
1680 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1681 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1684 fn print_else(&mut self, els: Option<&ast::Expr>) {
1685 if let Some(_else) = els {
1687 // Another `else if` block.
1688 ast::ExprKind::If(ref i, ref then, ref e) => {
1689 self.cbox(INDENT_UNIT - 1);
1691 self.word(" else if ");
1692 self.print_expr_as_cond(i);
1694 self.print_block(then);
1695 self.print_else(e.as_deref())
1697 // Final `else` block.
1698 ast::ExprKind::Block(ref b, _) => {
1699 self.cbox(INDENT_UNIT - 1);
1701 self.word(" else ");
1704 // Constraints would be great here!
1706 panic!("print_if saw if with weird alternative");
1712 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1714 self.print_expr_as_cond(test);
1716 self.print_block(blk);
1717 self.print_else(elseopt)
1720 crate fn print_mac(&mut self, m: &ast::MacCall) {
1721 self.print_mac_common(
1722 Some(MacHeader::Path(&m.path)),
1726 &m.args.inner_tokens(),
1732 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1734 self.commasep_exprs(Inconsistent, args);
1738 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1739 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1742 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1743 /// `if cond { ... }`.
1744 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1745 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1748 // Does `expr` need parentheses when printed in a condition position?
1750 // These cases need parens due to the parse error observed in #26461: `if return {}`
1751 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1752 fn cond_needs_par(expr: &ast::Expr) -> bool {
1754 ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1755 _ => parser::contains_exterior_struct_lit(expr),
1759 /// Prints `expr` or `(expr)` when `needs_par` holds.
1760 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1764 self.print_expr(expr);
1770 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1771 self.ibox(INDENT_UNIT);
1773 self.commasep_exprs(Inconsistent, exprs);
1778 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1779 self.ibox(INDENT_UNIT);
1781 self.print_expr(&expr.value);
1785 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1786 self.ibox(INDENT_UNIT);
1788 self.print_expr(element);
1789 self.word_space(";");
1790 self.print_expr(&count.value);
1795 fn print_expr_struct(
1797 qself: &Option<ast::QSelf>,
1799 fields: &[ast::ExprField],
1800 rest: &ast::StructRest,
1802 if let Some(qself) = qself {
1803 self.print_qpath(path, qself, true);
1805 self.print_path(path, true, 0);
1812 s.print_outer_attributes(&field.attrs);
1813 s.ibox(INDENT_UNIT);
1814 if !field.is_shorthand {
1815 s.print_ident(field.ident);
1818 s.print_expr(&field.expr);
1824 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1825 self.ibox(INDENT_UNIT);
1826 if !fields.is_empty() {
1831 if let ast::StructRest::Base(ref expr) = *rest {
1832 self.print_expr(expr);
1836 ast::StructRest::None if !fields.is_empty() => self.word(","),
1842 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1844 self.commasep_exprs(Inconsistent, exprs);
1845 if exprs.len() == 1 {
1851 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1852 let prec = match func.kind {
1853 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1854 _ => parser::PREC_POSTFIX,
1857 self.print_expr_maybe_paren(func, prec);
1858 self.print_call_post(args)
1861 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1862 let base_args = &args[1..];
1863 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1865 self.print_ident(segment.ident);
1866 if let Some(ref args) = segment.args {
1867 self.print_generic_args(args, true);
1869 self.print_call_post(base_args)
1872 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1873 let assoc_op = AssocOp::from_ast_binop(op.node);
1874 let prec = assoc_op.precedence() as i8;
1875 let fixity = assoc_op.fixity();
1877 let (left_prec, right_prec) = match fixity {
1878 Fixity::Left => (prec, prec + 1),
1879 Fixity::Right => (prec + 1, prec),
1880 Fixity::None => (prec + 1, prec + 1),
1883 let left_prec = match (&lhs.kind, op.node) {
1884 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1885 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1886 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1887 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1888 parser::PREC_FORCE_PAREN
1890 // We are given `(let _ = a) OP b`.
1892 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1893 // as the parser will interpret this as `(let _ = a) OP b`.
1895 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1896 // parens are required since the parser would interpret `let a = b < c` as
1897 // `let a = (b < c)`. To achieve this, we force parens.
1898 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1899 parser::PREC_FORCE_PAREN
1904 self.print_expr_maybe_paren(lhs, left_prec);
1906 self.word_space(op.node.to_string());
1907 self.print_expr_maybe_paren(rhs, right_prec)
1910 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1911 self.word(ast::UnOp::to_string(op));
1912 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1915 fn print_expr_addr_of(
1917 kind: ast::BorrowKind,
1918 mutability: ast::Mutability,
1923 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1924 ast::BorrowKind::Raw => {
1925 self.word_nbsp("raw");
1926 self.print_mutability(mutability, true);
1929 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1932 pub fn print_expr(&mut self, expr: &ast::Expr) {
1933 self.print_expr_outer_attr_style(expr, true)
1936 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1937 self.maybe_print_comment(expr.span.lo());
1939 let attrs = &expr.attrs;
1941 self.print_outer_attributes_inline(attrs);
1943 self.print_outer_attributes(attrs);
1946 self.ibox(INDENT_UNIT);
1947 self.ann.pre(self, AnnNode::Expr(expr));
1949 ast::ExprKind::Box(ref expr) => {
1950 self.word_space("box");
1951 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1953 ast::ExprKind::Array(ref exprs) => {
1954 self.print_expr_vec(exprs);
1956 ast::ExprKind::ConstBlock(ref anon_const) => {
1957 self.print_expr_anon_const(anon_const);
1959 ast::ExprKind::Repeat(ref element, ref count) => {
1960 self.print_expr_repeat(element, count);
1962 ast::ExprKind::Struct(ref se) => {
1963 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1965 ast::ExprKind::Tup(ref exprs) => {
1966 self.print_expr_tup(exprs);
1968 ast::ExprKind::Call(ref func, ref args) => {
1969 self.print_expr_call(func, &args);
1971 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1972 self.print_expr_method_call(segment, &args);
1974 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1975 self.print_expr_binary(op, lhs, rhs);
1977 ast::ExprKind::Unary(op, ref expr) => {
1978 self.print_expr_unary(op, expr);
1980 ast::ExprKind::AddrOf(k, m, ref expr) => {
1981 self.print_expr_addr_of(k, m, expr);
1983 ast::ExprKind::Lit(ref lit) => {
1984 self.print_literal(lit);
1986 ast::ExprKind::Cast(ref expr, ref ty) => {
1987 let prec = AssocOp::As.precedence() as i8;
1988 self.print_expr_maybe_paren(expr, prec);
1990 self.word_space("as");
1991 self.print_type(ty);
1993 ast::ExprKind::Type(ref expr, ref ty) => {
1994 let prec = AssocOp::Colon.precedence() as i8;
1995 self.print_expr_maybe_paren(expr, prec);
1996 self.word_space(":");
1997 self.print_type(ty);
1999 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
2000 self.print_let(pat, scrutinee);
2002 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2003 self.print_if(test, blk, elseopt.as_deref())
2005 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2006 if let Some(label) = opt_label {
2007 self.print_ident(label.ident);
2008 self.word_space(":");
2011 self.print_expr_as_cond(test);
2013 self.print_block_with_attrs(blk, attrs);
2015 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2016 if let Some(label) = opt_label {
2017 self.print_ident(label.ident);
2018 self.word_space(":");
2021 self.print_pat(pat);
2023 self.word_space("in");
2024 self.print_expr_as_cond(iter);
2026 self.print_block_with_attrs(blk, attrs);
2028 ast::ExprKind::Loop(ref blk, opt_label) => {
2029 if let Some(label) = opt_label {
2030 self.print_ident(label.ident);
2031 self.word_space(":");
2034 self.print_block_with_attrs(blk, attrs);
2036 ast::ExprKind::Match(ref expr, ref arms) => {
2037 self.cbox(INDENT_UNIT);
2038 self.ibox(INDENT_UNIT);
2039 self.word_nbsp("match");
2040 self.print_expr_as_cond(expr);
2043 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2045 self.print_arm(arm);
2047 let empty = attrs.is_empty() && arms.is_empty();
2048 self.bclose(expr.span, empty);
2050 ast::ExprKind::Closure(
2058 self.print_movability(movability);
2059 self.print_asyncness(asyncness);
2060 self.print_capture_clause(capture_clause);
2062 self.print_fn_params_and_ret(decl, true);
2064 self.print_expr(body);
2065 self.end(); // need to close a box
2067 // a box will be closed by print_expr, but we didn't want an overall
2068 // wrapper so we closed the corresponding opening. so create an
2069 // empty box to satisfy the close.
2072 ast::ExprKind::Block(ref blk, opt_label) => {
2073 if let Some(label) = opt_label {
2074 self.print_ident(label.ident);
2075 self.word_space(":");
2077 // containing cbox, will be closed by print-block at }
2078 self.cbox(INDENT_UNIT);
2079 // head-box, will be closed by print-block after {
2081 self.print_block_with_attrs(blk, attrs);
2083 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2084 self.word_nbsp("async");
2085 self.print_capture_clause(capture_clause);
2086 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2087 self.cbox(INDENT_UNIT);
2089 self.print_block_with_attrs(blk, attrs);
2091 ast::ExprKind::Await(ref expr) => {
2092 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2093 self.word(".await");
2095 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2096 let prec = AssocOp::Assign.precedence() as i8;
2097 self.print_expr_maybe_paren(lhs, prec + 1);
2099 self.word_space("=");
2100 self.print_expr_maybe_paren(rhs, prec);
2102 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2103 let prec = AssocOp::Assign.precedence() as i8;
2104 self.print_expr_maybe_paren(lhs, prec + 1);
2106 self.word(op.node.to_string());
2107 self.word_space("=");
2108 self.print_expr_maybe_paren(rhs, prec);
2110 ast::ExprKind::Field(ref expr, ident) => {
2111 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2113 self.print_ident(ident);
2115 ast::ExprKind::Index(ref expr, ref index) => {
2116 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2118 self.print_expr(index);
2121 ast::ExprKind::Range(ref start, ref end, limits) => {
2122 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2123 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2124 // Here we use a fake precedence value so that any child with lower precedence than
2125 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2126 let fake_prec = AssocOp::LOr.precedence() as i8;
2127 if let Some(ref e) = *start {
2128 self.print_expr_maybe_paren(e, fake_prec);
2130 if limits == ast::RangeLimits::HalfOpen {
2135 if let Some(ref e) = *end {
2136 self.print_expr_maybe_paren(e, fake_prec);
2139 ast::ExprKind::Underscore => self.word("_"),
2140 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2141 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2142 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2144 if let Some(label) = opt_label {
2146 self.print_ident(label.ident);
2148 if let Some(ref expr) = *opt_expr {
2150 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2153 ast::ExprKind::Continue(opt_label) => {
2154 self.word("continue");
2155 if let Some(label) = opt_label {
2157 self.print_ident(label.ident);
2160 ast::ExprKind::Ret(ref result) => {
2161 self.word("return");
2162 if let Some(ref expr) = *result {
2164 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2167 ast::ExprKind::InlineAsm(ref a) => {
2169 self.print_inline_asm(a);
2171 ast::ExprKind::LlvmInlineAsm(ref a) => {
2172 self.word("llvm_asm!");
2174 self.print_symbol(a.asm, a.asm_str_style);
2175 self.word_space(":");
2177 self.commasep(Inconsistent, &a.outputs, |s, out| {
2178 let constraint = out.constraint.as_str();
2179 let mut ch = constraint.chars();
2181 Some('=') if out.is_rw => {
2182 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2184 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2187 s.print_expr(&out.expr);
2191 self.word_space(":");
2193 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2194 s.print_symbol(co, ast::StrStyle::Cooked);
2200 self.word_space(":");
2202 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2203 s.print_symbol(co, ast::StrStyle::Cooked);
2206 let mut options = vec![];
2208 options.push("volatile");
2211 options.push("alignstack");
2213 if a.dialect == ast::LlvmAsmDialect::Intel {
2214 options.push("intel");
2217 if !options.is_empty() {
2219 self.word_space(":");
2220 self.commasep(Inconsistent, &options, |s, &co| {
2221 s.print_string(co, ast::StrStyle::Cooked);
2227 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2228 ast::ExprKind::Paren(ref e) => {
2233 ast::ExprKind::Yield(ref e) => {
2236 if let Some(ref expr) = *e {
2238 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2241 ast::ExprKind::Try(ref e) => {
2242 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2245 ast::ExprKind::TryBlock(ref blk) => {
2247 self.print_block_with_attrs(blk, attrs)
2249 ast::ExprKind::Err => {
2251 self.word("/*ERROR*/");
2255 self.ann.post(self, AnnNode::Expr(expr));
2259 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2262 Operand(&'a InlineAsmOperand),
2264 Options(InlineAsmOptions),
2267 let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2268 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2269 for (abi, _) in &asm.clobber_abis {
2270 args.push(AsmArg::ClobberAbi(*abi));
2272 if !asm.options.is_empty() {
2273 args.push(AsmArg::Options(asm.options));
2277 self.commasep(Consistent, &args, |s, arg| match arg {
2278 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2279 AsmArg::Operand(op) => {
2280 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2281 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2282 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2285 InlineAsmOperand::In { reg, expr } => {
2288 print_reg_or_class(s, reg);
2293 InlineAsmOperand::Out { reg, late, expr } => {
2294 s.word(if *late { "lateout" } else { "out" });
2296 print_reg_or_class(s, reg);
2300 Some(expr) => s.print_expr(expr),
2301 None => s.word("_"),
2304 InlineAsmOperand::InOut { reg, late, expr } => {
2305 s.word(if *late { "inlateout" } else { "inout" });
2307 print_reg_or_class(s, reg);
2312 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2313 s.word(if *late { "inlateout" } else { "inout" });
2315 print_reg_or_class(s, reg);
2318 s.print_expr(in_expr);
2322 Some(out_expr) => s.print_expr(out_expr),
2323 None => s.word("_"),
2326 InlineAsmOperand::Const { anon_const } => {
2329 s.print_expr(&anon_const.value);
2331 InlineAsmOperand::Sym { expr } => {
2338 AsmArg::ClobberAbi(abi) => {
2339 s.word("clobber_abi");
2341 s.print_symbol(*abi, ast::StrStyle::Cooked);
2344 AsmArg::Options(opts) => {
2347 let mut options = vec![];
2348 if opts.contains(InlineAsmOptions::PURE) {
2349 options.push("pure");
2351 if opts.contains(InlineAsmOptions::NOMEM) {
2352 options.push("nomem");
2354 if opts.contains(InlineAsmOptions::READONLY) {
2355 options.push("readonly");
2357 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2358 options.push("preserves_flags");
2360 if opts.contains(InlineAsmOptions::NORETURN) {
2361 options.push("noreturn");
2363 if opts.contains(InlineAsmOptions::NOSTACK) {
2364 options.push("nostack");
2366 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2367 options.push("att_syntax");
2369 if opts.contains(InlineAsmOptions::RAW) {
2370 options.push("raw");
2372 if opts.contains(InlineAsmOptions::MAY_UNWIND) {
2373 options.push("may_unwind");
2375 s.commasep(Inconsistent, &options, |s, &opt| {
2384 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2385 self.print_pat(&loc.pat);
2386 if let Some(ref ty) = loc.ty {
2387 self.word_space(":");
2388 self.print_type(ty);
2392 crate fn print_name(&mut self, name: Symbol) {
2393 self.word(name.to_string());
2394 self.ann.post(self, AnnNode::Name(&name))
2397 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2399 self.print_type(&qself.ty);
2400 if qself.position > 0 {
2402 self.word_space("as");
2403 let depth = path.segments.len() - qself.position;
2404 self.print_path(path, false, depth);
2407 for item_segment in &path.segments[qself.position..] {
2409 self.print_ident(item_segment.ident);
2410 if let Some(ref args) = item_segment.args {
2411 self.print_generic_args(args, colons_before_params)
2416 crate fn print_pat(&mut self, pat: &ast::Pat) {
2417 self.maybe_print_comment(pat.span.lo());
2418 self.ann.pre(self, AnnNode::Pat(pat));
2419 /* Pat isn't normalized, but the beauty of it
2420 is that it doesn't matter */
2422 PatKind::Wild => self.word("_"),
2423 PatKind::Ident(binding_mode, ident, ref sub) => {
2424 match binding_mode {
2425 ast::BindingMode::ByRef(mutbl) => {
2426 self.word_nbsp("ref");
2427 self.print_mutability(mutbl, false);
2429 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2430 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2431 self.word_nbsp("mut");
2434 self.print_ident(ident);
2435 if let Some(ref p) = *sub {
2437 self.word_space("@");
2441 PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2442 if let Some(qself) = qself {
2443 self.print_qpath(path, qself, true);
2445 self.print_path(path, true, 0);
2448 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2451 PatKind::Or(ref pats) => {
2452 self.strsep("|", true, Inconsistent, &pats, |s, p| s.print_pat(p));
2454 PatKind::Path(None, ref path) => {
2455 self.print_path(path, true, 0);
2457 PatKind::Path(Some(ref qself), ref path) => {
2458 self.print_qpath(path, qself, false);
2460 PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2461 if let Some(qself) = qself {
2462 self.print_qpath(path, qself, true);
2464 self.print_path(path, true, 0);
2468 let empty = fields.is_empty() && !etc;
2476 s.cbox(INDENT_UNIT);
2477 if !f.is_shorthand {
2478 s.print_ident(f.ident);
2481 s.print_pat(&f.pat);
2487 if !fields.is_empty() {
2488 self.word_space(",");
2497 PatKind::Tuple(ref elts) => {
2499 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2500 if elts.len() == 1 {
2505 PatKind::Box(ref inner) => {
2507 self.print_pat(inner);
2509 PatKind::Ref(ref inner, mutbl) => {
2511 if mutbl == ast::Mutability::Mut {
2514 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2518 self.print_pat(inner);
2521 self.print_pat(inner);
2524 PatKind::Lit(ref e) => self.print_expr(&**e),
2525 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2526 if let Some(e) = begin {
2530 RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2531 RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2532 RangeEnd::Excluded => self.word(".."),
2534 if let Some(e) = end {
2538 PatKind::Slice(ref elts) => {
2540 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2543 PatKind::Rest => self.word(".."),
2544 PatKind::Paren(ref inner) => {
2546 self.print_pat(inner);
2549 PatKind::MacCall(ref m) => self.print_mac(m),
2551 self.ann.post(self, AnnNode::Pat(pat))
2554 fn print_arm(&mut self, arm: &ast::Arm) {
2555 // Note, I have no idea why this check is necessary, but here it is.
2556 if arm.attrs.is_empty() {
2559 self.cbox(INDENT_UNIT);
2561 self.maybe_print_comment(arm.pat.span.lo());
2562 self.print_outer_attributes(&arm.attrs);
2563 self.print_pat(&arm.pat);
2565 if let Some(ref e) = arm.guard {
2566 self.word_space("if");
2570 self.word_space("=>");
2572 match arm.body.kind {
2573 ast::ExprKind::Block(ref blk, opt_label) => {
2574 if let Some(label) = opt_label {
2575 self.print_ident(label.ident);
2576 self.word_space(":");
2579 // The block will close the pattern's ibox.
2580 self.print_block_unclosed_indent(blk);
2582 // If it is a user-provided unsafe block, print a comma after it.
2583 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2588 self.end(); // Close the ibox for the pattern.
2589 self.print_expr(&arm.body);
2593 self.end(); // Close enclosing cbox.
2596 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2597 match explicit_self.node {
2598 SelfKind::Value(m) => {
2599 self.print_mutability(m, false);
2602 SelfKind::Region(ref lt, m) => {
2604 self.print_opt_lifetime(lt);
2605 self.print_mutability(m, false);
2608 SelfKind::Explicit(ref typ, m) => {
2609 self.print_mutability(m, false);
2611 self.word_space(":");
2612 self.print_type(typ)
2621 generics: &ast::Generics,
2622 vis: &ast::Visibility,
2623 defaultness: ast::Defaultness,
2624 body: Option<&ast::Block>,
2625 attrs: &[ast::Attribute],
2630 self.print_visibility(vis);
2631 self.print_defaultness(defaultness);
2632 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2633 if let Some(body) = body {
2635 self.print_block_with_attrs(body, attrs);
2644 header: ast::FnHeader,
2645 name: Option<Ident>,
2646 generics: &ast::Generics,
2648 self.print_fn_header_info(header);
2649 if let Some(name) = name {
2651 self.print_ident(name);
2653 self.print_generic_params(&generics.params);
2654 self.print_fn_params_and_ret(decl, false);
2655 self.print_where_clause(&generics.where_clause)
2658 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2659 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2661 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2663 self.print_fn_ret_ty(&decl.output)
2666 crate fn print_movability(&mut self, movability: ast::Movability) {
2668 ast::Movability::Static => self.word_space("static"),
2669 ast::Movability::Movable => {}
2673 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2674 if asyncness.is_async() {
2675 self.word_nbsp("async");
2679 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2680 match capture_clause {
2681 ast::CaptureBy::Value => self.word_space("move"),
2682 ast::CaptureBy::Ref => {}
2686 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2687 if !bounds.is_empty() {
2689 let mut first = true;
2690 for bound in bounds {
2691 if !(first && prefix.is_empty()) {
2697 self.word_space("+");
2701 GenericBound::Trait(tref, modifier) => {
2702 if modifier == &TraitBoundModifier::Maybe {
2705 self.print_poly_trait_ref(tref);
2707 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2713 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2714 self.print_name(lifetime.ident.name)
2717 crate fn print_lifetime_bounds(
2719 lifetime: ast::Lifetime,
2720 bounds: &ast::GenericBounds,
2722 self.print_lifetime(lifetime);
2723 if !bounds.is_empty() {
2725 for (i, bound) in bounds.iter().enumerate() {
2730 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2737 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2738 if generic_params.is_empty() {
2744 self.commasep(Inconsistent, &generic_params, |s, param| {
2745 s.print_outer_attributes_inline(¶m.attrs);
2748 ast::GenericParamKind::Lifetime => {
2749 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2750 s.print_lifetime_bounds(lt, ¶m.bounds)
2752 ast::GenericParamKind::Type { ref default } => {
2753 s.print_ident(param.ident);
2754 s.print_type_bounds(":", ¶m.bounds);
2755 if let Some(ref default) = default {
2758 s.print_type(default)
2761 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2762 s.word_space("const");
2763 s.print_ident(param.ident);
2767 s.print_type_bounds(":", ¶m.bounds);
2768 if let Some(ref default) = default {
2771 s.print_expr(&default.value);
2780 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2781 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2786 self.word_space("where");
2788 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2790 self.word_space(",");
2793 self.print_where_predicate(predicate);
2797 pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
2799 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2800 bound_generic_params,
2805 self.print_formal_generic_params(bound_generic_params);
2806 self.print_type(bounded_ty);
2807 self.print_type_bounds(":", bounds);
2809 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2814 self.print_lifetime_bounds(*lifetime, bounds);
2816 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => {
2817 self.print_type(lhs_ty);
2819 self.word_space("=");
2820 self.print_type(rhs_ty);
2825 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2827 ast::UseTreeKind::Simple(rename, ..) => {
2828 self.print_path(&tree.prefix, false, 0);
2829 if let Some(rename) = rename {
2831 self.word_space("as");
2832 self.print_ident(rename);
2835 ast::UseTreeKind::Glob => {
2836 if !tree.prefix.segments.is_empty() {
2837 self.print_path(&tree.prefix, false, 0);
2842 ast::UseTreeKind::Nested(ref items) => {
2843 if tree.prefix.segments.is_empty() {
2846 self.print_path(&tree.prefix, false, 0);
2849 self.commasep(Inconsistent, &items, |this, &(ref tree, _)| {
2850 this.print_use_tree(tree)
2857 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2859 ast::Mutability::Mut => self.word_nbsp("mut"),
2860 ast::Mutability::Not => {
2862 self.word_nbsp("const");
2868 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2869 self.print_mutability(mt.mutbl, print_const);
2870 self.print_type(&mt.ty)
2873 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2874 self.ibox(INDENT_UNIT);
2876 self.print_outer_attributes_inline(&input.attrs);
2878 match input.ty.kind {
2879 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2881 if let Some(eself) = input.to_self() {
2882 self.print_explicit_self(&eself);
2884 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2885 ident.name == kw::Empty
2890 self.print_pat(&input.pat);
2894 self.print_type(&input.ty);
2901 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2902 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2903 self.space_if_not_bol();
2904 self.ibox(INDENT_UNIT);
2905 self.word_space("->");
2906 self.print_type(ty);
2908 self.maybe_print_comment(ty.span.lo());
2912 crate fn print_ty_fn(
2915 unsafety: ast::Unsafe,
2917 name: Option<Ident>,
2918 generic_params: &[ast::GenericParam],
2920 self.ibox(INDENT_UNIT);
2921 self.print_formal_generic_params(generic_params);
2922 let generics = ast::Generics {
2924 where_clause: ast::WhereClause {
2925 has_where_token: false,
2926 predicates: Vec::new(),
2927 span: rustc_span::DUMMY_SP,
2929 span: rustc_span::DUMMY_SP,
2931 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2932 self.print_fn(decl, header, name, &generics);
2936 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2937 self.print_constness(header.constness);
2938 self.print_asyncness(header.asyncness);
2939 self.print_unsafety(header.unsafety);
2942 ast::Extern::None => {}
2943 ast::Extern::Implicit => {
2944 self.word_nbsp("extern");
2946 ast::Extern::Explicit(abi) => {
2947 self.word_nbsp("extern");
2948 self.print_literal(&abi.as_lit());
2956 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2958 ast::Unsafe::No => {}
2959 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2963 crate fn print_constness(&mut self, s: ast::Const) {
2965 ast::Const::No => {}
2966 ast::Const::Yes(_) => self.word_nbsp("const"),
2970 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2972 ast::IsAuto::Yes => self.word_nbsp("auto"),
2973 ast::IsAuto::No => {}