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);
1120 self.end(); // end the head-ibox
1121 if let Some(body) = body {
1122 self.word_space("=");
1123 self.print_expr(body);
1126 self.end(); // end the outer cbox
1129 fn print_associated_type(
1132 generics: &ast::Generics,
1133 bounds: &ast::GenericBounds,
1134 ty: Option<&ast::Ty>,
1135 vis: &ast::Visibility,
1136 defaultness: ast::Defaultness,
1139 self.print_visibility(vis);
1140 self.print_defaultness(defaultness);
1141 self.word_space("type");
1142 self.print_ident(ident);
1143 self.print_generic_params(&generics.params);
1144 self.print_type_bounds(":", bounds);
1145 self.print_where_clause(&generics.where_clause);
1146 if let Some(ty) = ty {
1148 self.word_space("=");
1149 self.print_type(ty);
1152 self.end(); // end inner head-block
1153 self.end(); // end outer head-block
1156 /// Pretty-prints an item.
1157 crate fn print_item(&mut self, item: &ast::Item) {
1158 self.hardbreak_if_not_bol();
1159 self.maybe_print_comment(item.span.lo());
1160 self.print_outer_attributes(&item.attrs);
1161 self.ann.pre(self, AnnNode::Item(item));
1163 ast::ItemKind::ExternCrate(orig_name) => {
1164 self.head(visibility_qualified(&item.vis, "extern crate"));
1165 if let Some(orig_name) = orig_name {
1166 self.print_name(orig_name);
1171 self.print_ident(item.ident);
1173 self.end(); // end inner head-block
1174 self.end(); // end outer head-block
1176 ast::ItemKind::Use(ref tree) => {
1177 self.head(visibility_qualified(&item.vis, "use"));
1178 self.print_use_tree(tree);
1180 self.end(); // end inner head-block
1181 self.end(); // end outer head-block
1183 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1184 let def = ast::Defaultness::Final;
1185 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1187 ast::ItemKind::Const(def, ref ty, ref body) => {
1188 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1190 ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => {
1191 let body = body.as_deref();
1202 ast::ItemKind::Mod(unsafety, ref mod_kind) => {
1203 self.head(self.to_string(|s| {
1204 s.print_visibility(&item.vis);
1205 s.print_unsafety(unsafety);
1208 self.print_ident(item.ident);
1211 ModKind::Loaded(items, ..) => {
1214 self.print_inner_attributes(&item.attrs);
1216 self.print_item(item);
1218 let empty = item.attrs.is_empty() && items.is_empty();
1219 self.bclose(item.span, empty);
1221 ModKind::Unloaded => {
1223 self.end(); // end inner head-block
1224 self.end(); // end outer head-block
1228 ast::ItemKind::ForeignMod(ref nmod) => {
1229 self.head(self.to_string(|s| {
1230 s.print_unsafety(nmod.unsafety);
1233 if let Some(abi) = nmod.abi {
1234 self.print_literal(&abi.as_lit());
1238 self.print_foreign_mod(nmod, &item.attrs);
1239 let empty = item.attrs.is_empty() && nmod.items.is_empty();
1240 self.bclose(item.span, empty);
1242 ast::ItemKind::GlobalAsm(ref asm) => {
1243 self.head(visibility_qualified(&item.vis, "global_asm!"));
1244 self.print_inline_asm(asm);
1247 ast::ItemKind::TyAlias(box ast::TyAlias {
1253 let ty = ty.as_deref();
1254 self.print_associated_type(
1263 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1264 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1266 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1267 self.head(visibility_qualified(&item.vis, "struct"));
1268 self.print_struct(struct_def, generics, item.ident, item.span, true);
1270 ast::ItemKind::Union(ref struct_def, ref generics) => {
1271 self.head(visibility_qualified(&item.vis, "union"));
1272 self.print_struct(struct_def, generics, item.ident, item.span, true);
1274 ast::ItemKind::Impl(box ast::Impl {
1285 self.print_visibility(&item.vis);
1286 self.print_defaultness(defaultness);
1287 self.print_unsafety(unsafety);
1288 self.word_nbsp("impl");
1289 self.print_constness(constness);
1291 if !generics.params.is_empty() {
1292 self.print_generic_params(&generics.params);
1296 if let ast::ImplPolarity::Negative(_) = polarity {
1300 if let Some(ref t) = *of_trait {
1301 self.print_trait_ref(t);
1303 self.word_space("for");
1306 self.print_type(self_ty);
1307 self.print_where_clause(&generics.where_clause);
1311 self.print_inner_attributes(&item.attrs);
1312 for impl_item in items {
1313 self.print_assoc_item(impl_item);
1315 let empty = item.attrs.is_empty() && items.is_empty();
1316 self.bclose(item.span, empty);
1318 ast::ItemKind::Trait(box ast::Trait {
1327 self.print_visibility(&item.vis);
1328 self.print_unsafety(unsafety);
1329 self.print_is_auto(is_auto);
1330 self.word_nbsp("trait");
1331 self.print_ident(item.ident);
1332 self.print_generic_params(&generics.params);
1333 let mut real_bounds = Vec::with_capacity(bounds.len());
1334 for b in bounds.iter() {
1335 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1337 self.word_space("for ?");
1338 self.print_trait_ref(&ptr.trait_ref);
1340 real_bounds.push(b.clone());
1343 self.print_type_bounds(":", &real_bounds);
1344 self.print_where_clause(&generics.where_clause);
1347 self.print_inner_attributes(&item.attrs);
1348 for trait_item in items {
1349 self.print_assoc_item(trait_item);
1351 let empty = item.attrs.is_empty() && items.is_empty();
1352 self.bclose(item.span, empty);
1354 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1356 self.print_visibility(&item.vis);
1357 self.word_nbsp("trait");
1358 self.print_ident(item.ident);
1359 self.print_generic_params(&generics.params);
1360 let mut real_bounds = Vec::with_capacity(bounds.len());
1361 // FIXME(durka) this seems to be some quite outdated syntax
1362 for b in bounds.iter() {
1363 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1365 self.word_space("for ?");
1366 self.print_trait_ref(&ptr.trait_ref);
1368 real_bounds.push(b.clone());
1372 self.print_type_bounds("=", &real_bounds);
1373 self.print_where_clause(&generics.where_clause);
1376 ast::ItemKind::MacCall(ref mac) => {
1377 self.print_mac(mac);
1378 if mac.args.need_semicolon() {
1382 ast::ItemKind::MacroDef(ref macro_def) => {
1383 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1384 state.print_visibility(&item.vis)
1388 self.ann.post(self, AnnNode::Item(item))
1391 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1392 self.print_path(&t.path, false, 0)
1395 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1396 if !generic_params.is_empty() {
1398 self.print_generic_params(generic_params);
1403 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1404 self.print_formal_generic_params(&t.bound_generic_params);
1405 self.print_trait_ref(&t.trait_ref)
1408 crate fn print_enum_def(
1410 enum_definition: &ast::EnumDef,
1411 generics: &ast::Generics,
1413 span: rustc_span::Span,
1414 visibility: &ast::Visibility,
1416 self.head(visibility_qualified(visibility, "enum"));
1417 self.print_ident(ident);
1418 self.print_generic_params(&generics.params);
1419 self.print_where_clause(&generics.where_clause);
1421 self.print_variants(&enum_definition.variants, span)
1424 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1427 self.space_if_not_bol();
1428 self.maybe_print_comment(v.span.lo());
1429 self.print_outer_attributes(&v.attrs);
1430 self.ibox(INDENT_UNIT);
1431 self.print_variant(v);
1434 self.maybe_print_trailing_comment(v.span, None);
1436 let empty = variants.is_empty();
1437 self.bclose(span, empty)
1440 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1442 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1443 ast::VisibilityKind::Crate(sugar) => match sugar {
1444 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1445 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1447 ast::VisibilityKind::Restricted { ref path, .. } => {
1448 let path = self.to_string(|s| s.print_path(path, false, 0));
1449 if path == "self" || path == "super" {
1450 self.word_nbsp(format!("pub({})", path))
1452 self.word_nbsp(format!("pub(in {})", path))
1455 ast::VisibilityKind::Inherited => {}
1459 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1460 if let ast::Defaultness::Default(_) = defaultness {
1461 self.word_nbsp("default");
1465 crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1469 let empty = fields.is_empty();
1471 self.hardbreak_if_not_bol();
1473 for field in fields {
1474 self.hardbreak_if_not_bol();
1475 self.maybe_print_comment(field.span.lo());
1476 self.print_outer_attributes(&field.attrs);
1477 self.print_visibility(&field.vis);
1478 self.print_ident(field.ident.unwrap());
1479 self.word_nbsp(":");
1480 self.print_type(&field.ty);
1485 self.bclose(span, empty);
1488 crate fn print_struct(
1490 struct_def: &ast::VariantData,
1491 generics: &ast::Generics,
1493 span: rustc_span::Span,
1494 print_finalizer: bool,
1496 self.print_ident(ident);
1497 self.print_generic_params(&generics.params);
1499 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1500 if let ast::VariantData::Tuple(..) = struct_def {
1502 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1503 s.maybe_print_comment(field.span.lo());
1504 s.print_outer_attributes(&field.attrs);
1505 s.print_visibility(&field.vis);
1506 s.print_type(&field.ty)
1510 self.print_where_clause(&generics.where_clause);
1511 if print_finalizer {
1515 self.end(); // Close the outer-box.
1517 ast::VariantData::Struct(ref fields, ..) => {
1518 self.print_where_clause(&generics.where_clause);
1519 self.print_record_struct_body(fields, span);
1524 crate fn print_variant(&mut self, v: &ast::Variant) {
1526 self.print_visibility(&v.vis);
1527 let generics = ast::Generics::default();
1528 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1529 if let Some(ref d) = v.disr_expr {
1531 self.word_space("=");
1532 self.print_expr(&d.value)
1536 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1537 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1538 self.ann.pre(self, AnnNode::SubItem(id));
1539 self.hardbreak_if_not_bol();
1540 self.maybe_print_comment(span.lo());
1541 self.print_outer_attributes(attrs);
1543 ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1544 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1546 ast::AssocItemKind::Const(def, ty, body) => {
1547 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1549 ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
1550 self.print_associated_type(
1559 ast::AssocItemKind::MacCall(m) => {
1561 if m.args.need_semicolon() {
1566 self.ann.post(self, AnnNode::SubItem(id))
1569 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1570 self.maybe_print_comment(st.span.lo());
1572 ast::StmtKind::Local(ref loc) => {
1573 self.print_outer_attributes(&loc.attrs);
1574 self.space_if_not_bol();
1575 self.ibox(INDENT_UNIT);
1576 self.word_nbsp("let");
1578 self.ibox(INDENT_UNIT);
1579 self.print_local_decl(loc);
1581 if let Some((init, els)) = loc.kind.init_else_opt() {
1583 self.word_space("=");
1584 self.print_expr(init);
1585 if let Some(els) = els {
1586 self.cbox(INDENT_UNIT);
1587 self.ibox(INDENT_UNIT);
1588 self.word(" else ");
1589 self.print_block(els);
1593 self.end(); // `let` ibox
1595 ast::StmtKind::Item(ref item) => self.print_item(item),
1596 ast::StmtKind::Expr(ref expr) => {
1597 self.space_if_not_bol();
1598 self.print_expr_outer_attr_style(expr, false);
1599 if classify::expr_requires_semi_to_be_stmt(expr) {
1603 ast::StmtKind::Semi(ref expr) => {
1604 self.space_if_not_bol();
1605 self.print_expr_outer_attr_style(expr, false);
1608 ast::StmtKind::Empty => {
1609 self.space_if_not_bol();
1612 ast::StmtKind::MacCall(ref mac) => {
1613 self.space_if_not_bol();
1614 self.print_outer_attributes(&mac.attrs);
1615 self.print_mac(&mac.mac);
1616 if mac.style == ast::MacStmtStyle::Semicolon {
1621 self.maybe_print_trailing_comment(st.span, None)
1624 crate fn print_block(&mut self, blk: &ast::Block) {
1625 self.print_block_with_attrs(blk, &[])
1628 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1629 self.print_block_maybe_unclosed(blk, &[], false)
1632 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1633 self.print_block_maybe_unclosed(blk, attrs, true)
1636 crate fn print_block_maybe_unclosed(
1639 attrs: &[ast::Attribute],
1643 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1644 BlockCheckMode::Default => (),
1646 self.maybe_print_comment(blk.span.lo());
1647 self.ann.pre(self, AnnNode::Block(blk));
1650 let has_attrs = self.print_inner_attributes(attrs);
1652 for (i, st) in blk.stmts.iter().enumerate() {
1654 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1655 self.maybe_print_comment(st.span.lo());
1656 self.space_if_not_bol();
1657 self.print_expr_outer_attr_style(expr, false);
1658 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1660 _ => self.print_stmt(st),
1664 let empty = !has_attrs && blk.stmts.is_empty();
1665 self.bclose_maybe_open(blk.span, empty, close_box);
1666 self.ann.post(self, AnnNode::Block(blk))
1669 /// Print a `let pat = expr` expression.
1670 crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1672 self.print_pat(pat);
1674 self.word_space("=");
1675 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1676 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1679 fn print_else(&mut self, els: Option<&ast::Expr>) {
1680 if let Some(_else) = els {
1682 // Another `else if` block.
1683 ast::ExprKind::If(ref i, ref then, ref e) => {
1684 self.cbox(INDENT_UNIT - 1);
1686 self.word(" else if ");
1687 self.print_expr_as_cond(i);
1689 self.print_block(then);
1690 self.print_else(e.as_deref())
1692 // Final `else` block.
1693 ast::ExprKind::Block(ref b, _) => {
1694 self.cbox(INDENT_UNIT - 1);
1696 self.word(" else ");
1699 // Constraints would be great here!
1701 panic!("print_if saw if with weird alternative");
1707 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1709 self.print_expr_as_cond(test);
1711 self.print_block(blk);
1712 self.print_else(elseopt)
1715 crate fn print_mac(&mut self, m: &ast::MacCall) {
1716 self.print_mac_common(
1717 Some(MacHeader::Path(&m.path)),
1721 &m.args.inner_tokens(),
1727 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1729 self.commasep_exprs(Inconsistent, args);
1733 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1734 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1737 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1738 /// `if cond { ... }`.
1739 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1740 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1743 // Does `expr` need parentheses when printed in a condition position?
1745 // These cases need parens due to the parse error observed in #26461: `if return {}`
1746 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1747 fn cond_needs_par(expr: &ast::Expr) -> bool {
1749 ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1750 _ => parser::contains_exterior_struct_lit(expr),
1754 /// Prints `expr` or `(expr)` when `needs_par` holds.
1755 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1759 self.print_expr(expr);
1765 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1766 self.ibox(INDENT_UNIT);
1768 self.commasep_exprs(Inconsistent, exprs);
1773 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1774 self.ibox(INDENT_UNIT);
1776 self.print_expr(&expr.value);
1780 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1781 self.ibox(INDENT_UNIT);
1783 self.print_expr(element);
1784 self.word_space(";");
1785 self.print_expr(&count.value);
1790 fn print_expr_struct(
1792 qself: &Option<ast::QSelf>,
1794 fields: &[ast::ExprField],
1795 rest: &ast::StructRest,
1797 if let Some(qself) = qself {
1798 self.print_qpath(path, qself, true);
1800 self.print_path(path, true, 0);
1807 s.print_outer_attributes(&field.attrs);
1808 s.ibox(INDENT_UNIT);
1809 if !field.is_shorthand {
1810 s.print_ident(field.ident);
1813 s.print_expr(&field.expr);
1819 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1820 self.ibox(INDENT_UNIT);
1821 if !fields.is_empty() {
1826 if let ast::StructRest::Base(ref expr) = *rest {
1827 self.print_expr(expr);
1831 ast::StructRest::None if !fields.is_empty() => self.word(","),
1837 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1839 self.commasep_exprs(Inconsistent, exprs);
1840 if exprs.len() == 1 {
1846 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1847 let prec = match func.kind {
1848 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1849 _ => parser::PREC_POSTFIX,
1852 self.print_expr_maybe_paren(func, prec);
1853 self.print_call_post(args)
1856 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1857 let base_args = &args[1..];
1858 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1860 self.print_ident(segment.ident);
1861 if let Some(ref args) = segment.args {
1862 self.print_generic_args(args, true);
1864 self.print_call_post(base_args)
1867 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1868 let assoc_op = AssocOp::from_ast_binop(op.node);
1869 let prec = assoc_op.precedence() as i8;
1870 let fixity = assoc_op.fixity();
1872 let (left_prec, right_prec) = match fixity {
1873 Fixity::Left => (prec, prec + 1),
1874 Fixity::Right => (prec + 1, prec),
1875 Fixity::None => (prec + 1, prec + 1),
1878 let left_prec = match (&lhs.kind, op.node) {
1879 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1880 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1881 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1882 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1883 parser::PREC_FORCE_PAREN
1885 // We are given `(let _ = a) OP b`.
1887 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1888 // as the parser will interpret this as `(let _ = a) OP b`.
1890 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1891 // parens are required since the parser would interpret `let a = b < c` as
1892 // `let a = (b < c)`. To achieve this, we force parens.
1893 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1894 parser::PREC_FORCE_PAREN
1899 self.print_expr_maybe_paren(lhs, left_prec);
1901 self.word_space(op.node.to_string());
1902 self.print_expr_maybe_paren(rhs, right_prec)
1905 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1906 self.word(ast::UnOp::to_string(op));
1907 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1910 fn print_expr_addr_of(
1912 kind: ast::BorrowKind,
1913 mutability: ast::Mutability,
1918 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1919 ast::BorrowKind::Raw => {
1920 self.word_nbsp("raw");
1921 self.print_mutability(mutability, true);
1924 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1927 pub fn print_expr(&mut self, expr: &ast::Expr) {
1928 self.print_expr_outer_attr_style(expr, true)
1931 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1932 self.maybe_print_comment(expr.span.lo());
1934 let attrs = &expr.attrs;
1936 self.print_outer_attributes_inline(attrs);
1938 self.print_outer_attributes(attrs);
1941 self.ibox(INDENT_UNIT);
1942 self.ann.pre(self, AnnNode::Expr(expr));
1944 ast::ExprKind::Box(ref expr) => {
1945 self.word_space("box");
1946 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1948 ast::ExprKind::Array(ref exprs) => {
1949 self.print_expr_vec(exprs);
1951 ast::ExprKind::ConstBlock(ref anon_const) => {
1952 self.print_expr_anon_const(anon_const);
1954 ast::ExprKind::Repeat(ref element, ref count) => {
1955 self.print_expr_repeat(element, count);
1957 ast::ExprKind::Struct(ref se) => {
1958 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1960 ast::ExprKind::Tup(ref exprs) => {
1961 self.print_expr_tup(exprs);
1963 ast::ExprKind::Call(ref func, ref args) => {
1964 self.print_expr_call(func, &args);
1966 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1967 self.print_expr_method_call(segment, &args);
1969 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1970 self.print_expr_binary(op, lhs, rhs);
1972 ast::ExprKind::Unary(op, ref expr) => {
1973 self.print_expr_unary(op, expr);
1975 ast::ExprKind::AddrOf(k, m, ref expr) => {
1976 self.print_expr_addr_of(k, m, expr);
1978 ast::ExprKind::Lit(ref lit) => {
1979 self.print_literal(lit);
1981 ast::ExprKind::Cast(ref expr, ref ty) => {
1982 let prec = AssocOp::As.precedence() as i8;
1983 self.print_expr_maybe_paren(expr, prec);
1985 self.word_space("as");
1986 self.print_type(ty);
1988 ast::ExprKind::Type(ref expr, ref ty) => {
1989 let prec = AssocOp::Colon.precedence() as i8;
1990 self.print_expr_maybe_paren(expr, prec);
1991 self.word_space(":");
1992 self.print_type(ty);
1994 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
1995 self.print_let(pat, scrutinee);
1997 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1998 self.print_if(test, blk, elseopt.as_deref())
2000 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2001 if let Some(label) = opt_label {
2002 self.print_ident(label.ident);
2003 self.word_space(":");
2006 self.print_expr_as_cond(test);
2008 self.print_block_with_attrs(blk, attrs);
2010 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2011 if let Some(label) = opt_label {
2012 self.print_ident(label.ident);
2013 self.word_space(":");
2016 self.print_pat(pat);
2018 self.word_space("in");
2019 self.print_expr_as_cond(iter);
2021 self.print_block_with_attrs(blk, attrs);
2023 ast::ExprKind::Loop(ref blk, opt_label) => {
2024 if let Some(label) = opt_label {
2025 self.print_ident(label.ident);
2026 self.word_space(":");
2029 self.print_block_with_attrs(blk, attrs);
2031 ast::ExprKind::Match(ref expr, ref arms) => {
2032 self.cbox(INDENT_UNIT);
2033 self.ibox(INDENT_UNIT);
2034 self.word_nbsp("match");
2035 self.print_expr_as_cond(expr);
2038 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2040 self.print_arm(arm);
2042 let empty = attrs.is_empty() && arms.is_empty();
2043 self.bclose(expr.span, empty);
2045 ast::ExprKind::Closure(
2053 self.print_movability(movability);
2054 self.print_asyncness(asyncness);
2055 self.print_capture_clause(capture_clause);
2057 self.print_fn_params_and_ret(decl, true);
2059 self.print_expr(body);
2060 self.end(); // need to close a box
2062 // a box will be closed by print_expr, but we didn't want an overall
2063 // wrapper so we closed the corresponding opening. so create an
2064 // empty box to satisfy the close.
2067 ast::ExprKind::Block(ref blk, opt_label) => {
2068 if let Some(label) = opt_label {
2069 self.print_ident(label.ident);
2070 self.word_space(":");
2072 // containing cbox, will be closed by print-block at }
2073 self.cbox(INDENT_UNIT);
2074 // head-box, will be closed by print-block after {
2076 self.print_block_with_attrs(blk, attrs);
2078 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2079 self.word_nbsp("async");
2080 self.print_capture_clause(capture_clause);
2081 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2082 self.cbox(INDENT_UNIT);
2084 self.print_block_with_attrs(blk, attrs);
2086 ast::ExprKind::Await(ref expr) => {
2087 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2088 self.word(".await");
2090 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2091 let prec = AssocOp::Assign.precedence() as i8;
2092 self.print_expr_maybe_paren(lhs, prec + 1);
2094 self.word_space("=");
2095 self.print_expr_maybe_paren(rhs, prec);
2097 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2098 let prec = AssocOp::Assign.precedence() as i8;
2099 self.print_expr_maybe_paren(lhs, prec + 1);
2101 self.word(op.node.to_string());
2102 self.word_space("=");
2103 self.print_expr_maybe_paren(rhs, prec);
2105 ast::ExprKind::Field(ref expr, ident) => {
2106 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2108 self.print_ident(ident);
2110 ast::ExprKind::Index(ref expr, ref index) => {
2111 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2113 self.print_expr(index);
2116 ast::ExprKind::Range(ref start, ref end, limits) => {
2117 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2118 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2119 // Here we use a fake precedence value so that any child with lower precedence than
2120 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2121 let fake_prec = AssocOp::LOr.precedence() as i8;
2122 if let Some(ref e) = *start {
2123 self.print_expr_maybe_paren(e, fake_prec);
2125 if limits == ast::RangeLimits::HalfOpen {
2130 if let Some(ref e) = *end {
2131 self.print_expr_maybe_paren(e, fake_prec);
2134 ast::ExprKind::Underscore => self.word("_"),
2135 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2136 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2137 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2139 if let Some(label) = opt_label {
2141 self.print_ident(label.ident);
2143 if let Some(ref expr) = *opt_expr {
2145 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2148 ast::ExprKind::Continue(opt_label) => {
2149 self.word("continue");
2150 if let Some(label) = opt_label {
2152 self.print_ident(label.ident);
2155 ast::ExprKind::Ret(ref result) => {
2156 self.word("return");
2157 if let Some(ref expr) = *result {
2159 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2162 ast::ExprKind::InlineAsm(ref a) => {
2164 self.print_inline_asm(a);
2166 ast::ExprKind::LlvmInlineAsm(ref a) => {
2167 self.word("llvm_asm!");
2169 self.print_symbol(a.asm, a.asm_str_style);
2170 self.word_space(":");
2172 self.commasep(Inconsistent, &a.outputs, |s, out| {
2173 let constraint = out.constraint.as_str();
2174 let mut ch = constraint.chars();
2176 Some('=') if out.is_rw => {
2177 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2179 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2182 s.print_expr(&out.expr);
2186 self.word_space(":");
2188 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2189 s.print_symbol(co, ast::StrStyle::Cooked);
2195 self.word_space(":");
2197 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2198 s.print_symbol(co, ast::StrStyle::Cooked);
2201 let mut options = vec![];
2203 options.push("volatile");
2206 options.push("alignstack");
2208 if a.dialect == ast::LlvmAsmDialect::Intel {
2209 options.push("intel");
2212 if !options.is_empty() {
2214 self.word_space(":");
2215 self.commasep(Inconsistent, &options, |s, &co| {
2216 s.print_string(co, ast::StrStyle::Cooked);
2222 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2223 ast::ExprKind::Paren(ref e) => {
2228 ast::ExprKind::Yield(ref e) => {
2231 if let Some(ref expr) = *e {
2233 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2236 ast::ExprKind::Try(ref e) => {
2237 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2240 ast::ExprKind::TryBlock(ref blk) => {
2243 self.print_block_with_attrs(blk, attrs)
2245 ast::ExprKind::Err => {
2247 self.word("/*ERROR*/");
2251 self.ann.post(self, AnnNode::Expr(expr));
2255 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2258 Operand(&'a InlineAsmOperand),
2260 Options(InlineAsmOptions),
2263 let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2264 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2265 for (abi, _) in &asm.clobber_abis {
2266 args.push(AsmArg::ClobberAbi(*abi));
2268 if !asm.options.is_empty() {
2269 args.push(AsmArg::Options(asm.options));
2273 self.commasep(Consistent, &args, |s, arg| match arg {
2274 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2275 AsmArg::Operand(op) => {
2276 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2277 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2278 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2281 InlineAsmOperand::In { reg, expr } => {
2284 print_reg_or_class(s, reg);
2289 InlineAsmOperand::Out { reg, late, expr } => {
2290 s.word(if *late { "lateout" } else { "out" });
2292 print_reg_or_class(s, reg);
2296 Some(expr) => s.print_expr(expr),
2297 None => s.word("_"),
2300 InlineAsmOperand::InOut { reg, late, expr } => {
2301 s.word(if *late { "inlateout" } else { "inout" });
2303 print_reg_or_class(s, reg);
2308 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2309 s.word(if *late { "inlateout" } else { "inout" });
2311 print_reg_or_class(s, reg);
2314 s.print_expr(in_expr);
2318 Some(out_expr) => s.print_expr(out_expr),
2319 None => s.word("_"),
2322 InlineAsmOperand::Const { anon_const } => {
2325 s.print_expr(&anon_const.value);
2327 InlineAsmOperand::Sym { expr } => {
2334 AsmArg::ClobberAbi(abi) => {
2335 s.word("clobber_abi");
2337 s.print_symbol(*abi, ast::StrStyle::Cooked);
2340 AsmArg::Options(opts) => {
2343 let mut options = vec![];
2344 if opts.contains(InlineAsmOptions::PURE) {
2345 options.push("pure");
2347 if opts.contains(InlineAsmOptions::NOMEM) {
2348 options.push("nomem");
2350 if opts.contains(InlineAsmOptions::READONLY) {
2351 options.push("readonly");
2353 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2354 options.push("preserves_flags");
2356 if opts.contains(InlineAsmOptions::NORETURN) {
2357 options.push("noreturn");
2359 if opts.contains(InlineAsmOptions::NOSTACK) {
2360 options.push("nostack");
2362 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2363 options.push("att_syntax");
2365 if opts.contains(InlineAsmOptions::RAW) {
2366 options.push("raw");
2368 if opts.contains(InlineAsmOptions::MAY_UNWIND) {
2369 options.push("may_unwind");
2371 s.commasep(Inconsistent, &options, |s, &opt| {
2380 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2381 self.print_pat(&loc.pat);
2382 if let Some(ref ty) = loc.ty {
2383 self.word_space(":");
2384 self.print_type(ty);
2388 crate fn print_name(&mut self, name: Symbol) {
2389 self.word(name.to_string());
2390 self.ann.post(self, AnnNode::Name(&name))
2393 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2395 self.print_type(&qself.ty);
2396 if qself.position > 0 {
2398 self.word_space("as");
2399 let depth = path.segments.len() - qself.position;
2400 self.print_path(path, false, depth);
2403 for item_segment in &path.segments[qself.position..] {
2405 self.print_ident(item_segment.ident);
2406 if let Some(ref args) = item_segment.args {
2407 self.print_generic_args(args, colons_before_params)
2412 crate fn print_pat(&mut self, pat: &ast::Pat) {
2413 self.maybe_print_comment(pat.span.lo());
2414 self.ann.pre(self, AnnNode::Pat(pat));
2415 /* Pat isn't normalized, but the beauty of it
2416 is that it doesn't matter */
2418 PatKind::Wild => self.word("_"),
2419 PatKind::Ident(binding_mode, ident, ref sub) => {
2420 match binding_mode {
2421 ast::BindingMode::ByRef(mutbl) => {
2422 self.word_nbsp("ref");
2423 self.print_mutability(mutbl, false);
2425 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2426 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2427 self.word_nbsp("mut");
2430 self.print_ident(ident);
2431 if let Some(ref p) = *sub {
2433 self.word_space("@");
2437 PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2438 if let Some(qself) = qself {
2439 self.print_qpath(path, qself, true);
2441 self.print_path(path, true, 0);
2444 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2447 PatKind::Or(ref pats) => {
2448 self.strsep("|", true, Inconsistent, &pats, |s, p| s.print_pat(p));
2450 PatKind::Path(None, ref path) => {
2451 self.print_path(path, true, 0);
2453 PatKind::Path(Some(ref qself), ref path) => {
2454 self.print_qpath(path, qself, false);
2456 PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2457 if let Some(qself) = qself {
2458 self.print_qpath(path, qself, true);
2460 self.print_path(path, true, 0);
2463 self.word_space("{");
2468 s.cbox(INDENT_UNIT);
2469 if !f.is_shorthand {
2470 s.print_ident(f.ident);
2473 s.print_pat(&f.pat);
2479 if !fields.is_empty() {
2480 self.word_space(",");
2487 PatKind::Tuple(ref elts) => {
2489 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2490 if elts.len() == 1 {
2495 PatKind::Box(ref inner) => {
2497 self.print_pat(inner);
2499 PatKind::Ref(ref inner, mutbl) => {
2501 if mutbl == ast::Mutability::Mut {
2504 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2508 self.print_pat(inner);
2511 self.print_pat(inner);
2514 PatKind::Lit(ref e) => self.print_expr(&**e),
2515 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2516 if let Some(e) = begin {
2521 RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2522 RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2523 RangeEnd::Excluded => self.word(".."),
2525 if let Some(e) = end {
2529 PatKind::Slice(ref elts) => {
2531 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2534 PatKind::Rest => self.word(".."),
2535 PatKind::Paren(ref inner) => {
2537 self.print_pat(inner);
2540 PatKind::MacCall(ref m) => self.print_mac(m),
2542 self.ann.post(self, AnnNode::Pat(pat))
2545 fn print_arm(&mut self, arm: &ast::Arm) {
2546 // Note, I have no idea why this check is necessary, but here it is.
2547 if arm.attrs.is_empty() {
2550 self.cbox(INDENT_UNIT);
2552 self.maybe_print_comment(arm.pat.span.lo());
2553 self.print_outer_attributes(&arm.attrs);
2554 self.print_pat(&arm.pat);
2556 if let Some(ref e) = arm.guard {
2557 self.word_space("if");
2561 self.word_space("=>");
2563 match arm.body.kind {
2564 ast::ExprKind::Block(ref blk, opt_label) => {
2565 if let Some(label) = opt_label {
2566 self.print_ident(label.ident);
2567 self.word_space(":");
2570 // The block will close the pattern's ibox.
2571 self.print_block_unclosed_indent(blk);
2573 // If it is a user-provided unsafe block, print a comma after it.
2574 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2579 self.end(); // Close the ibox for the pattern.
2580 self.print_expr(&arm.body);
2584 self.end(); // Close enclosing cbox.
2587 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2588 match explicit_self.node {
2589 SelfKind::Value(m) => {
2590 self.print_mutability(m, false);
2593 SelfKind::Region(ref lt, m) => {
2595 self.print_opt_lifetime(lt);
2596 self.print_mutability(m, false);
2599 SelfKind::Explicit(ref typ, m) => {
2600 self.print_mutability(m, false);
2602 self.word_space(":");
2603 self.print_type(typ)
2612 generics: &ast::Generics,
2613 vis: &ast::Visibility,
2614 defaultness: ast::Defaultness,
2615 body: Option<&ast::Block>,
2616 attrs: &[ast::Attribute],
2621 self.print_visibility(vis);
2622 self.print_defaultness(defaultness);
2623 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2624 if let Some(body) = body {
2626 self.print_block_with_attrs(body, attrs);
2635 header: ast::FnHeader,
2636 name: Option<Ident>,
2637 generics: &ast::Generics,
2639 self.print_fn_header_info(header);
2640 if let Some(name) = name {
2642 self.print_ident(name);
2644 self.print_generic_params(&generics.params);
2645 self.print_fn_params_and_ret(decl, false);
2646 self.print_where_clause(&generics.where_clause)
2649 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2650 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2652 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2654 self.print_fn_ret_ty(&decl.output)
2657 crate fn print_movability(&mut self, movability: ast::Movability) {
2659 ast::Movability::Static => self.word_space("static"),
2660 ast::Movability::Movable => {}
2664 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2665 if asyncness.is_async() {
2666 self.word_nbsp("async");
2670 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2671 match capture_clause {
2672 ast::CaptureBy::Value => self.word_space("move"),
2673 ast::CaptureBy::Ref => {}
2677 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2678 if !bounds.is_empty() {
2680 let mut first = true;
2681 for bound in bounds {
2682 if !(first && prefix.is_empty()) {
2688 self.word_space("+");
2692 GenericBound::Trait(tref, modifier) => {
2693 if modifier == &TraitBoundModifier::Maybe {
2696 self.print_poly_trait_ref(tref);
2698 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2704 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2705 self.print_name(lifetime.ident.name)
2708 crate fn print_lifetime_bounds(
2710 lifetime: ast::Lifetime,
2711 bounds: &ast::GenericBounds,
2713 self.print_lifetime(lifetime);
2714 if !bounds.is_empty() {
2716 for (i, bound) in bounds.iter().enumerate() {
2721 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2728 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2729 if generic_params.is_empty() {
2735 self.commasep(Inconsistent, &generic_params, |s, param| {
2736 s.print_outer_attributes_inline(¶m.attrs);
2739 ast::GenericParamKind::Lifetime => {
2740 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2741 s.print_lifetime_bounds(lt, ¶m.bounds)
2743 ast::GenericParamKind::Type { ref default } => {
2744 s.print_ident(param.ident);
2745 s.print_type_bounds(":", ¶m.bounds);
2746 if let Some(ref default) = default {
2749 s.print_type(default)
2752 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2753 s.word_space("const");
2754 s.print_ident(param.ident);
2758 s.print_type_bounds(":", ¶m.bounds);
2759 if let Some(ref default) = default {
2762 s.print_expr(&default.value);
2771 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2772 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2777 self.word_space("where");
2779 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2781 self.word_space(",");
2784 self.print_where_predicate(predicate);
2788 pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
2790 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2791 bound_generic_params,
2796 self.print_formal_generic_params(bound_generic_params);
2797 self.print_type(bounded_ty);
2798 self.print_type_bounds(":", bounds);
2800 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2805 self.print_lifetime_bounds(*lifetime, bounds);
2807 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => {
2808 self.print_type(lhs_ty);
2810 self.word_space("=");
2811 self.print_type(rhs_ty);
2816 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2818 ast::UseTreeKind::Simple(rename, ..) => {
2819 self.print_path(&tree.prefix, false, 0);
2820 if let Some(rename) = rename {
2822 self.word_space("as");
2823 self.print_ident(rename);
2826 ast::UseTreeKind::Glob => {
2827 if !tree.prefix.segments.is_empty() {
2828 self.print_path(&tree.prefix, false, 0);
2833 ast::UseTreeKind::Nested(ref items) => {
2834 if tree.prefix.segments.is_empty() {
2837 self.print_path(&tree.prefix, false, 0);
2840 self.commasep(Inconsistent, &items, |this, &(ref tree, _)| {
2841 this.print_use_tree(tree)
2848 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2850 ast::Mutability::Mut => self.word_nbsp("mut"),
2851 ast::Mutability::Not => {
2853 self.word_nbsp("const");
2859 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2860 self.print_mutability(mt.mutbl, print_const);
2861 self.print_type(&mt.ty)
2864 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2865 self.ibox(INDENT_UNIT);
2867 self.print_outer_attributes_inline(&input.attrs);
2869 match input.ty.kind {
2870 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2872 if let Some(eself) = input.to_self() {
2873 self.print_explicit_self(&eself);
2875 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2876 ident.name == kw::Empty
2881 self.print_pat(&input.pat);
2885 self.print_type(&input.ty);
2892 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2893 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2894 self.space_if_not_bol();
2895 self.ibox(INDENT_UNIT);
2896 self.word_space("->");
2897 self.print_type(ty);
2899 self.maybe_print_comment(ty.span.lo());
2903 crate fn print_ty_fn(
2906 unsafety: ast::Unsafe,
2908 name: Option<Ident>,
2909 generic_params: &[ast::GenericParam],
2911 self.ibox(INDENT_UNIT);
2912 self.print_formal_generic_params(generic_params);
2913 let generics = ast::Generics {
2915 where_clause: ast::WhereClause {
2916 has_where_token: false,
2917 predicates: Vec::new(),
2918 span: rustc_span::DUMMY_SP,
2920 span: rustc_span::DUMMY_SP,
2922 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2923 self.print_fn(decl, header, name, &generics);
2927 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2928 self.print_constness(header.constness);
2929 self.print_asyncness(header.asyncness);
2930 self.print_unsafety(header.unsafety);
2933 ast::Extern::None => {}
2934 ast::Extern::Implicit => {
2935 self.word_nbsp("extern");
2937 ast::Extern::Explicit(abi) => {
2938 self.word_nbsp("extern");
2939 self.print_literal(&abi.as_lit());
2947 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2949 ast::Unsafe::No => {}
2950 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2954 crate fn print_constness(&mut self, s: ast::Const) {
2956 ast::Const::No => {}
2957 ast::Const::Yes(_) => self.word_nbsp("const"),
2961 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2963 ast::IsAuto::Yes => self.word_nbsp("auto"),
2964 ast::IsAuto::No => {}