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::new().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 {
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(&self, 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);
1290 self.word_nbsp("impl");
1291 self.print_constness(constness);
1293 if !generics.params.is_empty() {
1294 self.print_generic_params(&generics.params);
1298 if let ast::ImplPolarity::Negative(_) = polarity {
1302 if let Some(ref t) = *of_trait {
1303 self.print_trait_ref(t);
1305 self.word_space("for");
1308 self.print_type(self_ty);
1309 self.print_where_clause(&generics.where_clause);
1313 self.print_inner_attributes(&item.attrs);
1314 for impl_item in items {
1315 self.print_assoc_item(impl_item);
1317 let empty = item.attrs.is_empty() && items.is_empty();
1318 self.bclose(item.span, empty);
1320 ast::ItemKind::Trait(box ast::Trait {
1329 self.print_visibility(&item.vis);
1330 self.print_unsafety(unsafety);
1331 self.print_is_auto(is_auto);
1332 self.word_nbsp("trait");
1333 self.print_ident(item.ident);
1334 self.print_generic_params(&generics.params);
1335 let mut real_bounds = Vec::with_capacity(bounds.len());
1336 for b in bounds.iter() {
1337 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1339 self.word_space("for ?");
1340 self.print_trait_ref(&ptr.trait_ref);
1342 real_bounds.push(b.clone());
1345 self.print_type_bounds(":", &real_bounds);
1346 self.print_where_clause(&generics.where_clause);
1349 self.print_inner_attributes(&item.attrs);
1350 for trait_item in items {
1351 self.print_assoc_item(trait_item);
1353 let empty = item.attrs.is_empty() && items.is_empty();
1354 self.bclose(item.span, empty);
1356 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1358 self.print_visibility(&item.vis);
1359 self.word_nbsp("trait");
1360 self.print_ident(item.ident);
1361 self.print_generic_params(&generics.params);
1362 let mut real_bounds = Vec::with_capacity(bounds.len());
1363 // FIXME(durka) this seems to be some quite outdated syntax
1364 for b in bounds.iter() {
1365 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1367 self.word_space("for ?");
1368 self.print_trait_ref(&ptr.trait_ref);
1370 real_bounds.push(b.clone());
1374 self.print_type_bounds("=", &real_bounds);
1375 self.print_where_clause(&generics.where_clause);
1378 ast::ItemKind::MacCall(ref mac) => {
1379 self.print_mac(mac);
1380 if mac.args.need_semicolon() {
1384 ast::ItemKind::MacroDef(ref macro_def) => {
1385 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1386 state.print_visibility(&item.vis)
1390 self.ann.post(self, AnnNode::Item(item))
1393 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1394 self.print_path(&t.path, false, 0)
1397 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1398 if !generic_params.is_empty() {
1400 self.print_generic_params(generic_params);
1405 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1406 self.print_formal_generic_params(&t.bound_generic_params);
1407 self.print_trait_ref(&t.trait_ref)
1410 crate fn print_enum_def(
1412 enum_definition: &ast::EnumDef,
1413 generics: &ast::Generics,
1415 span: rustc_span::Span,
1416 visibility: &ast::Visibility,
1418 self.head(visibility_qualified(visibility, "enum"));
1419 self.print_ident(ident);
1420 self.print_generic_params(&generics.params);
1421 self.print_where_clause(&generics.where_clause);
1423 self.print_variants(&enum_definition.variants, span)
1426 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1429 self.space_if_not_bol();
1430 self.maybe_print_comment(v.span.lo());
1431 self.print_outer_attributes(&v.attrs);
1432 self.ibox(INDENT_UNIT);
1433 self.print_variant(v);
1436 self.maybe_print_trailing_comment(v.span, None);
1438 let empty = variants.is_empty();
1439 self.bclose(span, empty)
1442 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1444 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1445 ast::VisibilityKind::Crate(sugar) => match sugar {
1446 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1447 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1449 ast::VisibilityKind::Restricted { ref path, .. } => {
1450 let path = self.to_string(|s| s.print_path(path, false, 0));
1451 if path == "self" || path == "super" {
1452 self.word_nbsp(format!("pub({})", path))
1454 self.word_nbsp(format!("pub(in {})", path))
1457 ast::VisibilityKind::Inherited => {}
1461 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1462 if let ast::Defaultness::Default(_) = defaultness {
1463 self.word_nbsp("default");
1467 crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1471 let empty = fields.is_empty();
1473 self.hardbreak_if_not_bol();
1475 for field in fields {
1476 self.hardbreak_if_not_bol();
1477 self.maybe_print_comment(field.span.lo());
1478 self.print_outer_attributes(&field.attrs);
1479 self.print_visibility(&field.vis);
1480 self.print_ident(field.ident.unwrap());
1481 self.word_nbsp(":");
1482 self.print_type(&field.ty);
1487 self.bclose(span, empty);
1490 crate fn print_struct(
1492 struct_def: &ast::VariantData,
1493 generics: &ast::Generics,
1495 span: rustc_span::Span,
1496 print_finalizer: bool,
1498 self.print_ident(ident);
1499 self.print_generic_params(&generics.params);
1501 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1502 if let ast::VariantData::Tuple(..) = struct_def {
1504 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1505 s.maybe_print_comment(field.span.lo());
1506 s.print_outer_attributes(&field.attrs);
1507 s.print_visibility(&field.vis);
1508 s.print_type(&field.ty)
1512 self.print_where_clause(&generics.where_clause);
1513 if print_finalizer {
1517 self.end(); // Close the outer-box.
1519 ast::VariantData::Struct(ref fields, ..) => {
1520 self.print_where_clause(&generics.where_clause);
1521 self.print_record_struct_body(fields, span);
1526 crate fn print_variant(&mut self, v: &ast::Variant) {
1528 self.print_visibility(&v.vis);
1529 let generics = ast::Generics::default();
1530 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1531 if let Some(ref d) = v.disr_expr {
1533 self.word_space("=");
1534 self.print_expr(&d.value)
1538 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1539 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1540 self.ann.pre(self, AnnNode::SubItem(id));
1541 self.hardbreak_if_not_bol();
1542 self.maybe_print_comment(span.lo());
1543 self.print_outer_attributes(attrs);
1545 ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1546 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1548 ast::AssocItemKind::Const(def, ty, body) => {
1549 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1551 ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
1552 self.print_associated_type(
1561 ast::AssocItemKind::MacCall(m) => {
1563 if m.args.need_semicolon() {
1568 self.ann.post(self, AnnNode::SubItem(id))
1571 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1572 self.maybe_print_comment(st.span.lo());
1574 ast::StmtKind::Local(ref loc) => {
1575 self.print_outer_attributes(&loc.attrs);
1576 self.space_if_not_bol();
1577 self.ibox(INDENT_UNIT);
1578 self.word_nbsp("let");
1580 self.ibox(INDENT_UNIT);
1581 self.print_local_decl(loc);
1583 if let Some((init, els)) = loc.kind.init_else_opt() {
1585 self.word_space("=");
1586 self.print_expr(init);
1587 if let Some(els) = els {
1588 self.cbox(INDENT_UNIT);
1589 self.ibox(INDENT_UNIT);
1590 self.word(" else ");
1591 self.print_block(els);
1595 self.end(); // `let` ibox
1597 ast::StmtKind::Item(ref item) => self.print_item(item),
1598 ast::StmtKind::Expr(ref expr) => {
1599 self.space_if_not_bol();
1600 self.print_expr_outer_attr_style(expr, false);
1601 if classify::expr_requires_semi_to_be_stmt(expr) {
1605 ast::StmtKind::Semi(ref expr) => {
1606 self.space_if_not_bol();
1607 self.print_expr_outer_attr_style(expr, false);
1610 ast::StmtKind::Empty => {
1611 self.space_if_not_bol();
1614 ast::StmtKind::MacCall(ref mac) => {
1615 self.space_if_not_bol();
1616 self.print_outer_attributes(&mac.attrs);
1617 self.print_mac(&mac.mac);
1618 if mac.style == ast::MacStmtStyle::Semicolon {
1623 self.maybe_print_trailing_comment(st.span, None)
1626 crate fn print_block(&mut self, blk: &ast::Block) {
1627 self.print_block_with_attrs(blk, &[])
1630 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1631 self.print_block_maybe_unclosed(blk, &[], false)
1634 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1635 self.print_block_maybe_unclosed(blk, attrs, true)
1638 crate fn print_block_maybe_unclosed(
1641 attrs: &[ast::Attribute],
1645 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1646 BlockCheckMode::Default => (),
1648 self.maybe_print_comment(blk.span.lo());
1649 self.ann.pre(self, AnnNode::Block(blk));
1652 let has_attrs = self.print_inner_attributes(attrs);
1654 for (i, st) in blk.stmts.iter().enumerate() {
1656 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1657 self.maybe_print_comment(st.span.lo());
1658 self.space_if_not_bol();
1659 self.print_expr_outer_attr_style(expr, false);
1660 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1662 _ => self.print_stmt(st),
1666 let empty = !has_attrs && blk.stmts.is_empty();
1667 self.bclose_maybe_open(blk.span, empty, close_box);
1668 self.ann.post(self, AnnNode::Block(blk))
1671 /// Print a `let pat = expr` expression.
1672 crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1674 self.print_pat(pat);
1676 self.word_space("=");
1677 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1678 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1681 fn print_else(&mut self, els: Option<&ast::Expr>) {
1682 if let Some(_else) = els {
1684 // Another `else if` block.
1685 ast::ExprKind::If(ref i, ref then, ref e) => {
1686 self.cbox(INDENT_UNIT - 1);
1688 self.word(" else if ");
1689 self.print_expr_as_cond(i);
1691 self.print_block(then);
1692 self.print_else(e.as_deref())
1694 // Final `else` block.
1695 ast::ExprKind::Block(ref b, _) => {
1696 self.cbox(INDENT_UNIT - 1);
1698 self.word(" else ");
1701 // Constraints would be great here!
1703 panic!("print_if saw if with weird alternative");
1709 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1711 self.print_expr_as_cond(test);
1713 self.print_block(blk);
1714 self.print_else(elseopt)
1717 crate fn print_mac(&mut self, m: &ast::MacCall) {
1718 self.print_mac_common(
1719 Some(MacHeader::Path(&m.path)),
1723 &m.args.inner_tokens(),
1729 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1731 self.commasep_exprs(Inconsistent, args);
1735 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1736 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1739 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1740 /// `if cond { ... }`.
1741 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1742 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1745 // Does `expr` need parentheses when printed in a condition position?
1747 // These cases need parens due to the parse error observed in #26461: `if return {}`
1748 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1749 fn cond_needs_par(expr: &ast::Expr) -> bool {
1751 ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1752 _ => parser::contains_exterior_struct_lit(expr),
1756 /// Prints `expr` or `(expr)` when `needs_par` holds.
1757 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1761 self.print_expr(expr);
1767 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1768 self.ibox(INDENT_UNIT);
1770 self.commasep_exprs(Inconsistent, exprs);
1775 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1776 self.ibox(INDENT_UNIT);
1778 self.print_expr(&expr.value);
1782 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1783 self.ibox(INDENT_UNIT);
1785 self.print_expr(element);
1786 self.word_space(";");
1787 self.print_expr(&count.value);
1792 fn print_expr_struct(
1794 qself: &Option<ast::QSelf>,
1796 fields: &[ast::ExprField],
1797 rest: &ast::StructRest,
1799 if let Some(qself) = qself {
1800 self.print_qpath(path, qself, true);
1802 self.print_path(path, true, 0);
1809 s.print_outer_attributes(&field.attrs);
1810 s.ibox(INDENT_UNIT);
1811 if !field.is_shorthand {
1812 s.print_ident(field.ident);
1815 s.print_expr(&field.expr);
1821 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1822 self.ibox(INDENT_UNIT);
1823 if !fields.is_empty() {
1828 if let ast::StructRest::Base(ref expr) = *rest {
1829 self.print_expr(expr);
1833 ast::StructRest::None if !fields.is_empty() => self.word(","),
1839 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1841 self.commasep_exprs(Inconsistent, exprs);
1842 if exprs.len() == 1 {
1848 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1849 let prec = match func.kind {
1850 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1851 _ => parser::PREC_POSTFIX,
1854 self.print_expr_maybe_paren(func, prec);
1855 self.print_call_post(args)
1858 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1859 let base_args = &args[1..];
1860 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1862 self.print_ident(segment.ident);
1863 if let Some(ref args) = segment.args {
1864 self.print_generic_args(args, true);
1866 self.print_call_post(base_args)
1869 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1870 let assoc_op = AssocOp::from_ast_binop(op.node);
1871 let prec = assoc_op.precedence() as i8;
1872 let fixity = assoc_op.fixity();
1874 let (left_prec, right_prec) = match fixity {
1875 Fixity::Left => (prec, prec + 1),
1876 Fixity::Right => (prec + 1, prec),
1877 Fixity::None => (prec + 1, prec + 1),
1880 let left_prec = match (&lhs.kind, op.node) {
1881 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1882 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1883 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1884 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1885 parser::PREC_FORCE_PAREN
1887 // We are given `(let _ = a) OP b`.
1889 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1890 // as the parser will interpret this as `(let _ = a) OP b`.
1892 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1893 // parens are required since the parser would interpret `let a = b < c` as
1894 // `let a = (b < c)`. To achieve this, we force parens.
1895 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1896 parser::PREC_FORCE_PAREN
1901 self.print_expr_maybe_paren(lhs, left_prec);
1903 self.word_space(op.node.to_string());
1904 self.print_expr_maybe_paren(rhs, right_prec)
1907 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1908 self.word(ast::UnOp::to_string(op));
1909 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1912 fn print_expr_addr_of(
1914 kind: ast::BorrowKind,
1915 mutability: ast::Mutability,
1920 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1921 ast::BorrowKind::Raw => {
1922 self.word_nbsp("raw");
1923 self.print_mutability(mutability, true);
1926 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1929 pub fn print_expr(&mut self, expr: &ast::Expr) {
1930 self.print_expr_outer_attr_style(expr, true)
1933 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1934 self.maybe_print_comment(expr.span.lo());
1936 let attrs = &expr.attrs;
1938 self.print_outer_attributes_inline(attrs);
1940 self.print_outer_attributes(attrs);
1943 self.ibox(INDENT_UNIT);
1944 self.ann.pre(self, AnnNode::Expr(expr));
1946 ast::ExprKind::Box(ref expr) => {
1947 self.word_space("box");
1948 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1950 ast::ExprKind::Array(ref exprs) => {
1951 self.print_expr_vec(exprs);
1953 ast::ExprKind::ConstBlock(ref anon_const) => {
1954 self.print_expr_anon_const(anon_const);
1956 ast::ExprKind::Repeat(ref element, ref count) => {
1957 self.print_expr_repeat(element, count);
1959 ast::ExprKind::Struct(ref se) => {
1960 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1962 ast::ExprKind::Tup(ref exprs) => {
1963 self.print_expr_tup(exprs);
1965 ast::ExprKind::Call(ref func, ref args) => {
1966 self.print_expr_call(func, &args);
1968 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1969 self.print_expr_method_call(segment, &args);
1971 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1972 self.print_expr_binary(op, lhs, rhs);
1974 ast::ExprKind::Unary(op, ref expr) => {
1975 self.print_expr_unary(op, expr);
1977 ast::ExprKind::AddrOf(k, m, ref expr) => {
1978 self.print_expr_addr_of(k, m, expr);
1980 ast::ExprKind::Lit(ref lit) => {
1981 self.print_literal(lit);
1983 ast::ExprKind::Cast(ref expr, ref ty) => {
1984 let prec = AssocOp::As.precedence() as i8;
1985 self.print_expr_maybe_paren(expr, prec);
1987 self.word_space("as");
1988 self.print_type(ty);
1990 ast::ExprKind::Type(ref expr, ref ty) => {
1991 let prec = AssocOp::Colon.precedence() as i8;
1992 self.print_expr_maybe_paren(expr, prec);
1993 self.word_space(":");
1994 self.print_type(ty);
1996 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
1997 self.print_let(pat, scrutinee);
1999 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2000 self.print_if(test, blk, elseopt.as_deref())
2002 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2003 if let Some(label) = opt_label {
2004 self.print_ident(label.ident);
2005 self.word_space(":");
2008 self.print_expr_as_cond(test);
2010 self.print_block_with_attrs(blk, attrs);
2012 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2013 if let Some(label) = opt_label {
2014 self.print_ident(label.ident);
2015 self.word_space(":");
2018 self.print_pat(pat);
2020 self.word_space("in");
2021 self.print_expr_as_cond(iter);
2023 self.print_block_with_attrs(blk, attrs);
2025 ast::ExprKind::Loop(ref blk, opt_label) => {
2026 if let Some(label) = opt_label {
2027 self.print_ident(label.ident);
2028 self.word_space(":");
2031 self.print_block_with_attrs(blk, attrs);
2033 ast::ExprKind::Match(ref expr, ref arms) => {
2034 self.cbox(INDENT_UNIT);
2035 self.ibox(INDENT_UNIT);
2036 self.word_nbsp("match");
2037 self.print_expr_as_cond(expr);
2040 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2042 self.print_arm(arm);
2044 let empty = attrs.is_empty() && arms.is_empty();
2045 self.bclose(expr.span, empty);
2047 ast::ExprKind::Closure(
2055 self.print_movability(movability);
2056 self.print_asyncness(asyncness);
2057 self.print_capture_clause(capture_clause);
2059 self.print_fn_params_and_ret(decl, true);
2061 self.print_expr(body);
2062 self.end(); // need to close a box
2064 // a box will be closed by print_expr, but we didn't want an overall
2065 // wrapper so we closed the corresponding opening. so create an
2066 // empty box to satisfy the close.
2069 ast::ExprKind::Block(ref blk, opt_label) => {
2070 if let Some(label) = opt_label {
2071 self.print_ident(label.ident);
2072 self.word_space(":");
2074 // containing cbox, will be closed by print-block at }
2075 self.cbox(INDENT_UNIT);
2076 // head-box, will be closed by print-block after {
2078 self.print_block_with_attrs(blk, attrs);
2080 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2081 self.word_nbsp("async");
2082 self.print_capture_clause(capture_clause);
2083 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2084 self.cbox(INDENT_UNIT);
2086 self.print_block_with_attrs(blk, attrs);
2088 ast::ExprKind::Await(ref expr) => {
2089 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2090 self.word(".await");
2092 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2093 let prec = AssocOp::Assign.precedence() as i8;
2094 self.print_expr_maybe_paren(lhs, prec + 1);
2096 self.word_space("=");
2097 self.print_expr_maybe_paren(rhs, prec);
2099 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2100 let prec = AssocOp::Assign.precedence() as i8;
2101 self.print_expr_maybe_paren(lhs, prec + 1);
2103 self.word(op.node.to_string());
2104 self.word_space("=");
2105 self.print_expr_maybe_paren(rhs, prec);
2107 ast::ExprKind::Field(ref expr, ident) => {
2108 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2110 self.print_ident(ident);
2112 ast::ExprKind::Index(ref expr, ref index) => {
2113 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2115 self.print_expr(index);
2118 ast::ExprKind::Range(ref start, ref end, limits) => {
2119 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2120 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2121 // Here we use a fake precedence value so that any child with lower precedence than
2122 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2123 let fake_prec = AssocOp::LOr.precedence() as i8;
2124 if let Some(ref e) = *start {
2125 self.print_expr_maybe_paren(e, fake_prec);
2127 if limits == ast::RangeLimits::HalfOpen {
2132 if let Some(ref e) = *end {
2133 self.print_expr_maybe_paren(e, fake_prec);
2136 ast::ExprKind::Underscore => self.word("_"),
2137 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2138 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2139 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2141 if let Some(label) = opt_label {
2143 self.print_ident(label.ident);
2145 if let Some(ref expr) = *opt_expr {
2147 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2150 ast::ExprKind::Continue(opt_label) => {
2151 self.word("continue");
2152 if let Some(label) = opt_label {
2154 self.print_ident(label.ident);
2157 ast::ExprKind::Ret(ref result) => {
2158 self.word("return");
2159 if let Some(ref expr) = *result {
2161 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2164 ast::ExprKind::InlineAsm(ref a) => {
2166 self.print_inline_asm(a);
2168 ast::ExprKind::LlvmInlineAsm(ref a) => {
2169 self.word("llvm_asm!");
2171 self.print_symbol(a.asm, a.asm_str_style);
2172 self.word_space(":");
2174 self.commasep(Inconsistent, &a.outputs, |s, out| {
2175 let constraint = out.constraint.as_str();
2176 let mut ch = constraint.chars();
2178 Some('=') if out.is_rw => {
2179 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2181 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2184 s.print_expr(&out.expr);
2188 self.word_space(":");
2190 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2191 s.print_symbol(co, ast::StrStyle::Cooked);
2197 self.word_space(":");
2199 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2200 s.print_symbol(co, ast::StrStyle::Cooked);
2203 let mut options = vec![];
2205 options.push("volatile");
2208 options.push("alignstack");
2210 if a.dialect == ast::LlvmAsmDialect::Intel {
2211 options.push("intel");
2214 if !options.is_empty() {
2216 self.word_space(":");
2217 self.commasep(Inconsistent, &options, |s, &co| {
2218 s.print_string(co, ast::StrStyle::Cooked);
2224 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2225 ast::ExprKind::Paren(ref e) => {
2230 ast::ExprKind::Yield(ref e) => {
2233 if let Some(ref expr) = *e {
2235 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2238 ast::ExprKind::Try(ref e) => {
2239 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2242 ast::ExprKind::TryBlock(ref blk) => {
2244 self.print_block_with_attrs(blk, attrs)
2246 ast::ExprKind::Err => {
2248 self.word("/*ERROR*/");
2252 self.ann.post(self, AnnNode::Expr(expr));
2256 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2259 Operand(&'a InlineAsmOperand),
2261 Options(InlineAsmOptions),
2264 let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2265 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2266 for (abi, _) in &asm.clobber_abis {
2267 args.push(AsmArg::ClobberAbi(*abi));
2269 if !asm.options.is_empty() {
2270 args.push(AsmArg::Options(asm.options));
2274 self.commasep(Consistent, &args, |s, arg| match arg {
2275 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2276 AsmArg::Operand(op) => {
2277 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2278 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2279 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2282 InlineAsmOperand::In { reg, expr } => {
2285 print_reg_or_class(s, reg);
2290 InlineAsmOperand::Out { reg, late, expr } => {
2291 s.word(if *late { "lateout" } else { "out" });
2293 print_reg_or_class(s, reg);
2297 Some(expr) => s.print_expr(expr),
2298 None => s.word("_"),
2301 InlineAsmOperand::InOut { reg, late, expr } => {
2302 s.word(if *late { "inlateout" } else { "inout" });
2304 print_reg_or_class(s, reg);
2309 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2310 s.word(if *late { "inlateout" } else { "inout" });
2312 print_reg_or_class(s, reg);
2315 s.print_expr(in_expr);
2319 Some(out_expr) => s.print_expr(out_expr),
2320 None => s.word("_"),
2323 InlineAsmOperand::Const { anon_const } => {
2326 s.print_expr(&anon_const.value);
2328 InlineAsmOperand::Sym { expr } => {
2335 AsmArg::ClobberAbi(abi) => {
2336 s.word("clobber_abi");
2338 s.print_symbol(*abi, ast::StrStyle::Cooked);
2341 AsmArg::Options(opts) => {
2344 let mut options = vec![];
2345 if opts.contains(InlineAsmOptions::PURE) {
2346 options.push("pure");
2348 if opts.contains(InlineAsmOptions::NOMEM) {
2349 options.push("nomem");
2351 if opts.contains(InlineAsmOptions::READONLY) {
2352 options.push("readonly");
2354 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2355 options.push("preserves_flags");
2357 if opts.contains(InlineAsmOptions::NORETURN) {
2358 options.push("noreturn");
2360 if opts.contains(InlineAsmOptions::NOSTACK) {
2361 options.push("nostack");
2363 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2364 options.push("att_syntax");
2366 if opts.contains(InlineAsmOptions::RAW) {
2367 options.push("raw");
2369 if opts.contains(InlineAsmOptions::MAY_UNWIND) {
2370 options.push("may_unwind");
2372 s.commasep(Inconsistent, &options, |s, &opt| {
2381 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2382 self.print_pat(&loc.pat);
2383 if let Some(ref ty) = loc.ty {
2384 self.word_space(":");
2385 self.print_type(ty);
2389 crate fn print_name(&mut self, name: Symbol) {
2390 self.word(name.to_string());
2391 self.ann.post(self, AnnNode::Name(&name))
2394 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2396 self.print_type(&qself.ty);
2397 if qself.position > 0 {
2399 self.word_space("as");
2400 let depth = path.segments.len() - qself.position;
2401 self.print_path(path, false, depth);
2404 for item_segment in &path.segments[qself.position..] {
2406 self.print_ident(item_segment.ident);
2407 if let Some(ref args) = item_segment.args {
2408 self.print_generic_args(args, colons_before_params)
2413 crate fn print_pat(&mut self, pat: &ast::Pat) {
2414 self.maybe_print_comment(pat.span.lo());
2415 self.ann.pre(self, AnnNode::Pat(pat));
2416 /* Pat isn't normalized, but the beauty of it
2417 is that it doesn't matter */
2419 PatKind::Wild => self.word("_"),
2420 PatKind::Ident(binding_mode, ident, ref sub) => {
2421 match binding_mode {
2422 ast::BindingMode::ByRef(mutbl) => {
2423 self.word_nbsp("ref");
2424 self.print_mutability(mutbl, false);
2426 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2427 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2428 self.word_nbsp("mut");
2431 self.print_ident(ident);
2432 if let Some(ref p) = *sub {
2434 self.word_space("@");
2438 PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2439 if let Some(qself) = qself {
2440 self.print_qpath(path, qself, true);
2442 self.print_path(path, true, 0);
2445 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2448 PatKind::Or(ref pats) => {
2449 self.strsep("|", true, Inconsistent, &pats, |s, p| s.print_pat(p));
2451 PatKind::Path(None, ref path) => {
2452 self.print_path(path, true, 0);
2454 PatKind::Path(Some(ref qself), ref path) => {
2455 self.print_qpath(path, qself, false);
2457 PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2458 if let Some(qself) = qself {
2459 self.print_qpath(path, qself, true);
2461 self.print_path(path, true, 0);
2464 self.word_space("{");
2469 s.cbox(INDENT_UNIT);
2470 if !f.is_shorthand {
2471 s.print_ident(f.ident);
2474 s.print_pat(&f.pat);
2480 if !fields.is_empty() {
2481 self.word_space(",");
2488 PatKind::Tuple(ref elts) => {
2490 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2491 if elts.len() == 1 {
2496 PatKind::Box(ref inner) => {
2498 self.print_pat(inner);
2500 PatKind::Ref(ref inner, mutbl) => {
2502 if mutbl == ast::Mutability::Mut {
2505 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2509 self.print_pat(inner);
2512 self.print_pat(inner);
2515 PatKind::Lit(ref e) => self.print_expr(&**e),
2516 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2517 if let Some(e) = begin {
2522 RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2523 RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2524 RangeEnd::Excluded => self.word(".."),
2526 if let Some(e) = end {
2530 PatKind::Slice(ref elts) => {
2532 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2535 PatKind::Rest => self.word(".."),
2536 PatKind::Paren(ref inner) => {
2538 self.print_pat(inner);
2541 PatKind::MacCall(ref m) => self.print_mac(m),
2543 self.ann.post(self, AnnNode::Pat(pat))
2546 fn print_arm(&mut self, arm: &ast::Arm) {
2547 // Note, I have no idea why this check is necessary, but here it is.
2548 if arm.attrs.is_empty() {
2551 self.cbox(INDENT_UNIT);
2553 self.maybe_print_comment(arm.pat.span.lo());
2554 self.print_outer_attributes(&arm.attrs);
2555 self.print_pat(&arm.pat);
2557 if let Some(ref e) = arm.guard {
2558 self.word_space("if");
2562 self.word_space("=>");
2564 match arm.body.kind {
2565 ast::ExprKind::Block(ref blk, opt_label) => {
2566 if let Some(label) = opt_label {
2567 self.print_ident(label.ident);
2568 self.word_space(":");
2571 // The block will close the pattern's ibox.
2572 self.print_block_unclosed_indent(blk);
2574 // If it is a user-provided unsafe block, print a comma after it.
2575 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2580 self.end(); // Close the ibox for the pattern.
2581 self.print_expr(&arm.body);
2585 self.end(); // Close enclosing cbox.
2588 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2589 match explicit_self.node {
2590 SelfKind::Value(m) => {
2591 self.print_mutability(m, false);
2594 SelfKind::Region(ref lt, m) => {
2596 self.print_opt_lifetime(lt);
2597 self.print_mutability(m, false);
2600 SelfKind::Explicit(ref typ, m) => {
2601 self.print_mutability(m, false);
2603 self.word_space(":");
2604 self.print_type(typ)
2613 generics: &ast::Generics,
2614 vis: &ast::Visibility,
2615 defaultness: ast::Defaultness,
2616 body: Option<&ast::Block>,
2617 attrs: &[ast::Attribute],
2622 self.print_visibility(vis);
2623 self.print_defaultness(defaultness);
2624 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2625 if let Some(body) = body {
2627 self.print_block_with_attrs(body, attrs);
2636 header: ast::FnHeader,
2637 name: Option<Ident>,
2638 generics: &ast::Generics,
2640 self.print_fn_header_info(header);
2641 if let Some(name) = name {
2643 self.print_ident(name);
2645 self.print_generic_params(&generics.params);
2646 self.print_fn_params_and_ret(decl, false);
2647 self.print_where_clause(&generics.where_clause)
2650 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2651 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2653 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2655 self.print_fn_ret_ty(&decl.output)
2658 crate fn print_movability(&mut self, movability: ast::Movability) {
2660 ast::Movability::Static => self.word_space("static"),
2661 ast::Movability::Movable => {}
2665 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2666 if asyncness.is_async() {
2667 self.word_nbsp("async");
2671 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2672 match capture_clause {
2673 ast::CaptureBy::Value => self.word_space("move"),
2674 ast::CaptureBy::Ref => {}
2678 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2679 if !bounds.is_empty() {
2681 let mut first = true;
2682 for bound in bounds {
2683 if !(first && prefix.is_empty()) {
2689 self.word_space("+");
2693 GenericBound::Trait(tref, modifier) => {
2694 if modifier == &TraitBoundModifier::Maybe {
2697 self.print_poly_trait_ref(tref);
2699 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2705 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2706 self.print_name(lifetime.ident.name)
2709 crate fn print_lifetime_bounds(
2711 lifetime: ast::Lifetime,
2712 bounds: &ast::GenericBounds,
2714 self.print_lifetime(lifetime);
2715 if !bounds.is_empty() {
2717 for (i, bound) in bounds.iter().enumerate() {
2722 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2729 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2730 if generic_params.is_empty() {
2736 self.commasep(Inconsistent, &generic_params, |s, param| {
2737 s.print_outer_attributes_inline(¶m.attrs);
2740 ast::GenericParamKind::Lifetime => {
2741 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2742 s.print_lifetime_bounds(lt, ¶m.bounds)
2744 ast::GenericParamKind::Type { ref default } => {
2745 s.print_ident(param.ident);
2746 s.print_type_bounds(":", ¶m.bounds);
2747 if let Some(ref default) = default {
2750 s.print_type(default)
2753 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2754 s.word_space("const");
2755 s.print_ident(param.ident);
2759 s.print_type_bounds(":", ¶m.bounds);
2760 if let Some(ref default) = default {
2763 s.print_expr(&default.value);
2772 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2773 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2778 self.word_space("where");
2780 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2782 self.word_space(",");
2785 self.print_where_predicate(predicate);
2789 pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
2791 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2792 bound_generic_params,
2797 self.print_formal_generic_params(bound_generic_params);
2798 self.print_type(bounded_ty);
2799 self.print_type_bounds(":", bounds);
2801 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2806 self.print_lifetime_bounds(*lifetime, bounds);
2808 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => {
2809 self.print_type(lhs_ty);
2811 self.word_space("=");
2812 self.print_type(rhs_ty);
2817 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2819 ast::UseTreeKind::Simple(rename, ..) => {
2820 self.print_path(&tree.prefix, false, 0);
2821 if let Some(rename) = rename {
2823 self.word_space("as");
2824 self.print_ident(rename);
2827 ast::UseTreeKind::Glob => {
2828 if !tree.prefix.segments.is_empty() {
2829 self.print_path(&tree.prefix, false, 0);
2834 ast::UseTreeKind::Nested(ref items) => {
2835 if tree.prefix.segments.is_empty() {
2838 self.print_path(&tree.prefix, false, 0);
2841 self.commasep(Inconsistent, &items, |this, &(ref tree, _)| {
2842 this.print_use_tree(tree)
2849 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2851 ast::Mutability::Mut => self.word_nbsp("mut"),
2852 ast::Mutability::Not => {
2854 self.word_nbsp("const");
2860 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2861 self.print_mutability(mt.mutbl, print_const);
2862 self.print_type(&mt.ty)
2865 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2866 self.ibox(INDENT_UNIT);
2868 self.print_outer_attributes_inline(&input.attrs);
2870 match input.ty.kind {
2871 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2873 if let Some(eself) = input.to_self() {
2874 self.print_explicit_self(&eself);
2876 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2877 ident.name == kw::Empty
2882 self.print_pat(&input.pat);
2886 self.print_type(&input.ty);
2893 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2894 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2895 self.space_if_not_bol();
2896 self.ibox(INDENT_UNIT);
2897 self.word_space("->");
2898 self.print_type(ty);
2900 self.maybe_print_comment(ty.span.lo());
2904 crate fn print_ty_fn(
2907 unsafety: ast::Unsafe,
2909 name: Option<Ident>,
2910 generic_params: &[ast::GenericParam],
2912 self.ibox(INDENT_UNIT);
2913 self.print_formal_generic_params(generic_params);
2914 let generics = ast::Generics {
2916 where_clause: ast::WhereClause {
2917 has_where_token: false,
2918 predicates: Vec::new(),
2919 span: rustc_span::DUMMY_SP,
2921 span: rustc_span::DUMMY_SP,
2923 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2924 self.print_fn(decl, header, name, &generics);
2928 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2929 self.print_constness(header.constness);
2930 self.print_asyncness(header.asyncness);
2931 self.print_unsafety(header.unsafety);
2934 ast::Extern::None => {}
2935 ast::Extern::Implicit => {
2936 self.word_nbsp("extern");
2938 ast::Extern::Explicit(abi) => {
2939 self.word_nbsp("extern");
2940 self.print_literal(&abi.as_lit());
2948 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2950 ast::Unsafe::No => {}
2951 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2955 crate fn print_constness(&mut self, s: ast::Const) {
2957 ast::Const::No => {}
2958 ast::Const::Yes(_) => self.word_nbsp("const"),
2962 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2964 ast::IsAuto::Yes => self.word_nbsp("auto"),
2965 ast::IsAuto::No => {}