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) {
267 while let Some(ref cmnt) = self.next_comment() {
269 self.print_comment(cmnt);
276 fn print_comment(&mut self, cmnt: &Comment) {
278 CommentStyle::Mixed => {
279 if !self.is_beginning_of_line() {
282 if let Some((last, lines)) = cmnt.lines.split_last() {
286 self.word(line.clone());
290 self.word(last.clone());
297 CommentStyle::Isolated => {
298 self.hardbreak_if_not_bol();
299 for line in &cmnt.lines {
300 // Don't print empty lines because they will end up as trailing
302 if !line.is_empty() {
303 self.word(line.clone());
308 CommentStyle::Trailing => {
309 if !self.is_beginning_of_line() {
312 if cmnt.lines.len() == 1 {
313 self.word(cmnt.lines[0].clone());
317 for line in &cmnt.lines {
318 if !line.is_empty() {
319 self.word(line.clone());
326 CommentStyle::BlankLine => {
327 // We need to do at least one, possibly two hardbreaks.
328 let twice = match self.last_token() {
329 pp::Token::String(s) => ";" == s,
330 pp::Token::Begin(_) => true,
331 pp::Token::End => true,
340 if let Some(cmnts) = self.comments() {
345 fn next_comment(&mut self) -> Option<Comment> {
346 self.comments().as_mut().and_then(|c| c.next())
349 fn print_literal(&mut self, lit: &ast::Lit) {
350 self.maybe_print_comment(lit.span.lo());
351 self.word(lit.token.to_string())
354 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
355 let st = match style {
356 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
357 ast::StrStyle::Raw(n) => {
358 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
364 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
365 self.print_string(&sym.as_str(), style);
368 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
369 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
372 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
373 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
376 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
377 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
380 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
381 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
384 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
385 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
388 fn print_either_attributes(
390 attrs: &[ast::Attribute],
391 kind: ast::AttrStyle,
393 trailing_hardbreak: bool,
397 if attr.style == kind {
398 self.print_attribute_inline(attr, is_inline);
405 if count > 0 && trailing_hardbreak && !is_inline {
406 self.hardbreak_if_not_bol();
410 fn print_attribute(&mut self, attr: &ast::Attribute) {
411 self.print_attribute_inline(attr, false)
414 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
416 self.hardbreak_if_not_bol();
418 self.maybe_print_comment(attr.span.lo());
420 ast::AttrKind::Normal(ref item, _) => {
422 ast::AttrStyle::Inner => self.word("#!["),
423 ast::AttrStyle::Outer => self.word("#["),
425 self.print_attr_item(&item, attr.span);
428 ast::AttrKind::DocComment(comment_kind, data) => {
429 self.word(doc_comment_to_string(comment_kind, attr.style, data));
435 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
438 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
439 Some(MacHeader::Path(&item.path)),
447 MacArgs::Empty | MacArgs::Eq(..) => {
448 self.print_path(&item.path, false, 0);
449 if let MacArgs::Eq(_, token) = &item.args {
451 self.word_space("=");
452 let token_str = self.token_to_string_ext(token, true);
453 self.word(token_str);
460 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
462 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
463 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
467 fn print_meta_item(&mut self, item: &ast::MetaItem) {
468 self.ibox(INDENT_UNIT);
470 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
471 ast::MetaItemKind::NameValue(ref value) => {
472 self.print_path(&item.path, false, 0);
474 self.word_space("=");
475 self.print_literal(value);
477 ast::MetaItemKind::List(ref items) => {
478 self.print_path(&item.path, false, 0);
480 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
487 /// This doesn't deserve to be called "pretty" printing, but it should be
488 /// meaning-preserving. A quick hack that might help would be to look at the
489 /// spans embedded in the TTs to decide where to put spaces and newlines.
490 /// But it'd be better to parse these according to the grammar of the
491 /// appropriate macro, transcribe back into the grammar we just parsed from,
492 /// and then pretty-print the resulting AST nodes (so, e.g., we print
493 /// expression arguments as expressions). It can be done! I think.
494 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
496 TokenTree::Token(token) => {
497 let token_str = self.token_to_string_ext(&token, convert_dollar_crate);
498 self.word(token_str);
499 if let token::DocComment(..) = token.kind {
503 TokenTree::Delimited(dspan, delim, tts) => {
504 self.print_mac_common(
510 convert_dollar_crate,
517 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
518 let mut iter = tts.trees().peekable();
519 while let Some(tt) = iter.next() {
520 self.print_tt(&tt, convert_dollar_crate);
521 if let Some(next) = iter.peek() {
522 if tt_prepend_space(next, &tt) {
531 header: Option<MacHeader<'_>>,
533 ident: Option<Ident>,
536 convert_dollar_crate: bool,
539 if delim == DelimToken::Brace {
540 self.cbox(INDENT_UNIT);
543 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
544 Some(MacHeader::Keyword(kw)) => self.word(kw),
550 if let Some(ident) = ident {
552 self.print_ident(ident);
555 DelimToken::Brace => {
556 if header.is_some() || has_bang || ident.is_some() {
565 let token_str = self.token_kind_to_string(&token::OpenDelim(delim));
570 self.print_tts(tts, convert_dollar_crate);
573 DelimToken::Brace => self.bclose(span),
575 let token_str = self.token_kind_to_string(&token::CloseDelim(delim));
583 macro_def: &ast::MacroDef,
586 print_visibility: impl FnOnce(&mut Self),
588 let (kw, has_bang) = if macro_def.macro_rules {
589 ("macro_rules", true)
591 print_visibility(self);
594 self.print_mac_common(
595 Some(MacHeader::Keyword(kw)),
598 macro_def.body.delim(),
599 ¯o_def.body.inner_tokens(),
603 if macro_def.body.need_semicolon() {
608 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
609 self.maybe_print_comment(path.span.lo());
611 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
615 self.print_path_segment(segment, colons_before_params);
619 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
620 if segment.ident.name != kw::PathRoot {
621 self.print_ident(segment.ident);
622 if let Some(ref args) = segment.args {
623 self.print_generic_args(args, colons_before_params);
628 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
630 // Outer-box is consistent.
631 self.cbox(INDENT_UNIT);
632 // Head-box is inconsistent.
633 self.ibox(w.len() + 1);
634 // Keyword that starts the head.
640 fn bopen(&mut self) {
642 self.end(); // Close the head-box.
645 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
646 self.maybe_print_comment(span.hi());
647 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
650 self.end(); // Close the outer-box.
654 fn bclose(&mut self, span: rustc_span::Span) {
655 self.bclose_maybe_open(span, true)
658 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
659 if !self.is_beginning_of_line() {
660 self.break_offset(n, off)
661 } else if off != 0 && self.last_token().is_hardbreak_tok() {
662 // We do something pretty sketchy here: tuck the nonzero
663 // offset-adjustment we were going to deposit along with the
664 // break into the previous hardbreak.
665 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
669 fn nonterminal_to_string(&self, nt: &Nonterminal) -> String {
671 token::NtExpr(ref e) => self.expr_to_string(e),
672 token::NtMeta(ref e) => self.attr_item_to_string(e),
673 token::NtTy(ref e) => self.ty_to_string(e),
674 token::NtPath(ref e) => self.path_to_string(e),
675 token::NtItem(ref e) => self.item_to_string(e),
676 token::NtBlock(ref e) => self.block_to_string(e),
677 token::NtStmt(ref e) => self.stmt_to_string(e),
678 token::NtPat(ref e) => self.pat_to_string(e),
679 token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(),
680 token::NtLifetime(e) => e.to_string(),
681 token::NtLiteral(ref e) => self.expr_to_string(e),
682 token::NtTT(ref tree) => self.tt_to_string(tree),
683 token::NtVis(ref e) => self.vis_to_string(e),
687 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
688 fn token_kind_to_string(&self, tok: &TokenKind) -> Cow<'static, str> {
689 self.token_kind_to_string_ext(tok, None)
692 fn token_kind_to_string_ext(
695 convert_dollar_crate: Option<Span>,
696 ) -> Cow<'static, str> {
698 token::Eq => "=".into(),
699 token::Lt => "<".into(),
700 token::Le => "<=".into(),
701 token::EqEq => "==".into(),
702 token::Ne => "!=".into(),
703 token::Ge => ">=".into(),
704 token::Gt => ">".into(),
705 token::Not => "!".into(),
706 token::Tilde => "~".into(),
707 token::OrOr => "||".into(),
708 token::AndAnd => "&&".into(),
709 token::BinOp(op) => binop_to_string(op).into(),
710 token::BinOpEq(op) => format!("{}=", binop_to_string(op)).into(),
712 /* Structural symbols */
713 token::At => "@".into(),
714 token::Dot => ".".into(),
715 token::DotDot => "..".into(),
716 token::DotDotDot => "...".into(),
717 token::DotDotEq => "..=".into(),
718 token::Comma => ",".into(),
719 token::Semi => ";".into(),
720 token::Colon => ":".into(),
721 token::ModSep => "::".into(),
722 token::RArrow => "->".into(),
723 token::LArrow => "<-".into(),
724 token::FatArrow => "=>".into(),
725 token::OpenDelim(token::Paren) => "(".into(),
726 token::CloseDelim(token::Paren) => ")".into(),
727 token::OpenDelim(token::Bracket) => "[".into(),
728 token::CloseDelim(token::Bracket) => "]".into(),
729 token::OpenDelim(token::Brace) => "{".into(),
730 token::CloseDelim(token::Brace) => "}".into(),
731 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => "".into(),
732 token::Pound => "#".into(),
733 token::Dollar => "$".into(),
734 token::Question => "?".into(),
735 token::SingleQuote => "'".into(),
738 token::Literal(lit) => literal_to_string(lit).into(),
740 /* Name components */
741 token::Ident(s, is_raw) => {
742 IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string().into()
744 token::Lifetime(s) => s.to_string().into(),
747 token::DocComment(comment_kind, attr_style, data) => {
748 doc_comment_to_string(comment_kind, attr_style, data).into()
750 token::Eof => "<eof>".into(),
752 token::Interpolated(ref nt) => self.nonterminal_to_string(nt).into(),
756 /// Print the token precisely, without converting `$crate` into its respective crate name.
757 fn token_to_string(&self, token: &Token) -> Cow<'static, str> {
758 self.token_to_string_ext(token, false)
761 fn token_to_string_ext(&self, token: &Token, convert_dollar_crate: bool) -> Cow<'static, str> {
762 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
763 self.token_kind_to_string_ext(&token.kind, convert_dollar_crate)
766 fn ty_to_string(&self, ty: &ast::Ty) -> String {
767 self.to_string(|s| s.print_type(ty))
770 fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String {
771 self.to_string(|s| s.print_type_bounds("", bounds))
774 fn pat_to_string(&self, pat: &ast::Pat) -> String {
775 self.to_string(|s| s.print_pat(pat))
778 fn expr_to_string(&self, e: &ast::Expr) -> String {
779 self.to_string(|s| s.print_expr(e))
782 fn tt_to_string(&self, tt: &TokenTree) -> String {
783 self.to_string(|s| s.print_tt(tt, false))
786 fn tts_to_string(&self, tokens: &TokenStream) -> String {
787 self.to_string(|s| s.print_tts(tokens, false))
790 fn stmt_to_string(&self, stmt: &ast::Stmt) -> String {
791 self.to_string(|s| s.print_stmt(stmt))
794 fn item_to_string(&self, i: &ast::Item) -> String {
795 self.to_string(|s| s.print_item(i))
798 fn generic_params_to_string(&self, generic_params: &[ast::GenericParam]) -> String {
799 self.to_string(|s| s.print_generic_params(generic_params))
802 fn path_to_string(&self, p: &ast::Path) -> String {
803 self.to_string(|s| s.print_path(p, false, 0))
806 fn path_segment_to_string(&self, p: &ast::PathSegment) -> String {
807 self.to_string(|s| s.print_path_segment(p, false))
810 fn vis_to_string(&self, v: &ast::Visibility) -> String {
811 self.to_string(|s| s.print_visibility(v))
814 fn block_to_string(&self, blk: &ast::Block) -> String {
816 // Containing cbox, will be closed by `print_block` at `}`.
818 // Head-ibox, will be closed by `print_block` after `{`.
824 fn meta_list_item_to_string(&self, li: &ast::NestedMetaItem) -> String {
825 self.to_string(|s| s.print_meta_list_item(li))
828 fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String {
829 self.to_string(|s| s.print_attr_item(ai, ai.path.span))
832 fn attribute_to_string(&self, attr: &ast::Attribute) -> String {
833 self.to_string(|s| s.print_attribute(attr))
836 fn param_to_string(&self, arg: &ast::Param) -> String {
837 self.to_string(|s| s.print_param(arg, false))
840 fn to_string(&self, f: impl FnOnce(&mut State<'_>)) -> String {
841 let mut printer = State::new();
847 impl<'a> PrintState<'a> for State<'a> {
848 fn comments(&mut self) -> &mut Option<Comments<'a>> {
852 fn print_ident(&mut self, ident: Ident) {
853 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
854 self.ann.post(self, AnnNode::Ident(&ident))
857 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
858 if colons_before_params {
863 ast::GenericArgs::AngleBracketed(ref data) => {
865 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
866 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
867 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
872 ast::GenericArgs::Parenthesized(ref data) => {
874 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
876 self.print_fn_ret_ty(&data.output);
883 pub fn new() -> State<'a> {
884 State { s: pp::mk_printer(), comments: None, ann: &NoAnn }
887 // Synthesizes a comment that was not textually present in the original source
889 pub fn synth_comment(&mut self, text: String) {
897 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
899 F: FnMut(&mut State<'_>, &T),
900 G: FnMut(&T) -> rustc_span::Span,
903 let len = elts.len();
906 self.maybe_print_comment(get_span(elt).hi());
911 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
912 self.space_if_not_bol();
918 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
919 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
922 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
923 self.print_inner_attributes(attrs);
924 for item in &nmod.items {
925 self.print_foreign_item(item);
929 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
930 if let Some(lt) = *lifetime {
931 self.print_lifetime(lt);
936 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
937 self.print_ident(constraint.ident);
938 constraint.gen_args.as_ref().map(|args| self.print_generic_args(args, false));
940 match &constraint.kind {
941 ast::AssocTyConstraintKind::Equality { ty } => {
942 self.word_space("=");
945 ast::AssocTyConstraintKind::Bound { bounds } => {
946 self.print_type_bounds(":", &*bounds);
951 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
953 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
954 GenericArg::Type(ty) => self.print_type(ty),
955 GenericArg::Const(ct) => self.print_expr(&ct.value),
959 pub fn print_type(&mut self, ty: &ast::Ty) {
960 self.maybe_print_comment(ty.span.lo());
963 ast::TyKind::Slice(ref ty) => {
968 ast::TyKind::Ptr(ref mt) => {
970 self.print_mt(mt, true);
972 ast::TyKind::Rptr(ref lifetime, ref mt) => {
974 self.print_opt_lifetime(lifetime);
975 self.print_mt(mt, false);
977 ast::TyKind::Never => {
980 ast::TyKind::Tup(ref elts) => {
982 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
988 ast::TyKind::AnonymousStruct(ref fields, ..) => {
990 self.print_record_struct_body(&fields, ty.span);
992 ast::TyKind::AnonymousUnion(ref fields, ..) => {
994 self.print_record_struct_body(&fields, ty.span);
996 ast::TyKind::Paren(ref typ) => {
998 self.print_type(typ);
1001 ast::TyKind::BareFn(ref f) => {
1002 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
1004 ast::TyKind::Path(None, ref path) => {
1005 self.print_path(path, false, 0);
1007 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
1008 ast::TyKind::TraitObject(ref bounds, syntax) => {
1009 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1010 self.print_type_bounds(prefix, &bounds[..]);
1012 ast::TyKind::ImplTrait(_, ref bounds) => {
1013 self.print_type_bounds("impl", &bounds[..]);
1015 ast::TyKind::Array(ref ty, ref length) => {
1017 self.print_type(ty);
1019 self.print_expr(&length.value);
1022 ast::TyKind::Typeof(ref e) => {
1023 self.s.word("typeof(");
1024 self.print_expr(&e.value);
1027 ast::TyKind::Infer => {
1030 ast::TyKind::Err => {
1032 self.s.word("/*ERROR*/");
1035 ast::TyKind::ImplicitSelf => {
1036 self.s.word("Self");
1038 ast::TyKind::MacCall(ref m) => {
1041 ast::TyKind::CVarArgs => {
1048 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1049 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1050 self.ann.pre(self, AnnNode::SubItem(id));
1051 self.hardbreak_if_not_bol();
1052 self.maybe_print_comment(span.lo());
1053 self.print_outer_attributes(attrs);
1055 ast::ForeignItemKind::Fn(box ast::FnKind(def, sig, gen, body)) => {
1056 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1058 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1059 let def = ast::Defaultness::Final;
1060 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1062 ast::ForeignItemKind::TyAlias(box ast::TyAliasKind(def, generics, bounds, ty)) => {
1063 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1065 ast::ForeignItemKind::MacCall(m) => {
1067 if m.args.need_semicolon() {
1072 self.ann.post(self, AnnNode::SubItem(id))
1075 fn print_item_const(
1078 mutbl: Option<ast::Mutability>,
1080 body: Option<&ast::Expr>,
1081 vis: &ast::Visibility,
1082 defaultness: ast::Defaultness,
1085 self.print_visibility(vis);
1086 self.print_defaultness(defaultness);
1087 let leading = match mutbl {
1089 Some(ast::Mutability::Not) => "static",
1090 Some(ast::Mutability::Mut) => "static mut",
1092 self.word_space(leading);
1093 self.print_ident(ident);
1094 self.word_space(":");
1095 self.print_type(ty);
1097 self.end(); // end the head-ibox
1098 if let Some(body) = body {
1099 self.word_space("=");
1100 self.print_expr(body);
1103 self.end(); // end the outer cbox
1106 fn print_associated_type(
1109 generics: &ast::Generics,
1110 bounds: &ast::GenericBounds,
1111 ty: Option<&ast::Ty>,
1112 vis: &ast::Visibility,
1113 defaultness: ast::Defaultness,
1116 self.print_visibility(vis);
1117 self.print_defaultness(defaultness);
1118 self.word_space("type");
1119 self.print_ident(ident);
1120 self.print_generic_params(&generics.params);
1121 self.print_type_bounds(":", bounds);
1122 self.print_where_clause(&generics.where_clause);
1123 if let Some(ty) = ty {
1125 self.word_space("=");
1126 self.print_type(ty);
1129 self.end(); // end inner head-block
1130 self.end(); // end outer head-block
1133 /// Pretty-prints an item.
1134 crate fn print_item(&mut self, item: &ast::Item) {
1135 self.hardbreak_if_not_bol();
1136 self.maybe_print_comment(item.span.lo());
1137 self.print_outer_attributes(&item.attrs);
1138 self.ann.pre(self, AnnNode::Item(item));
1140 ast::ItemKind::ExternCrate(orig_name) => {
1141 self.head(visibility_qualified(&item.vis, "extern crate"));
1142 if let Some(orig_name) = orig_name {
1143 self.print_name(orig_name);
1148 self.print_ident(item.ident);
1150 self.end(); // end inner head-block
1151 self.end(); // end outer head-block
1153 ast::ItemKind::Use(ref tree) => {
1154 self.head(visibility_qualified(&item.vis, "use"));
1155 self.print_use_tree(tree);
1157 self.end(); // end inner head-block
1158 self.end(); // end outer head-block
1160 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1161 let def = ast::Defaultness::Final;
1162 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1164 ast::ItemKind::Const(def, ref ty, ref body) => {
1165 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1167 ast::ItemKind::Fn(box ast::FnKind(def, ref sig, ref gen, ref body)) => {
1168 let body = body.as_deref();
1169 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1171 ast::ItemKind::Mod(unsafety, ref mod_kind) => {
1172 self.head(self.to_string(|s| {
1173 s.print_visibility(&item.vis);
1174 s.print_unsafety(unsafety);
1177 self.print_ident(item.ident);
1180 ModKind::Loaded(items, ..) => {
1183 self.print_inner_attributes(&item.attrs);
1185 self.print_item(item);
1187 self.bclose(item.span);
1189 ModKind::Unloaded => {
1191 self.end(); // end inner head-block
1192 self.end(); // end outer head-block
1196 ast::ItemKind::ForeignMod(ref nmod) => {
1197 self.head(self.to_string(|s| {
1198 s.print_unsafety(nmod.unsafety);
1201 if let Some(abi) = nmod.abi {
1202 self.print_literal(&abi.as_lit());
1206 self.print_foreign_mod(nmod, &item.attrs);
1207 self.bclose(item.span);
1209 ast::ItemKind::GlobalAsm(ref asm) => {
1210 self.head(visibility_qualified(&item.vis, "global_asm!"));
1211 self.print_inline_asm(asm);
1214 ast::ItemKind::TyAlias(box ast::TyAliasKind(def, ref generics, ref bounds, ref ty)) => {
1215 let ty = ty.as_deref();
1216 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1218 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1219 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1221 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1222 self.head(visibility_qualified(&item.vis, "struct"));
1223 self.print_struct(struct_def, generics, item.ident, item.span, true);
1225 ast::ItemKind::Union(ref struct_def, ref generics) => {
1226 self.head(visibility_qualified(&item.vis, "union"));
1227 self.print_struct(struct_def, generics, item.ident, item.span, true);
1229 ast::ItemKind::Impl(box ast::ImplKind {
1240 self.print_visibility(&item.vis);
1241 self.print_defaultness(defaultness);
1242 self.print_unsafety(unsafety);
1243 self.word_nbsp("impl");
1244 self.print_constness(constness);
1246 if !generics.params.is_empty() {
1247 self.print_generic_params(&generics.params);
1251 if let ast::ImplPolarity::Negative(_) = polarity {
1255 if let Some(ref t) = *of_trait {
1256 self.print_trait_ref(t);
1258 self.word_space("for");
1261 self.print_type(self_ty);
1262 self.print_where_clause(&generics.where_clause);
1266 self.print_inner_attributes(&item.attrs);
1267 for impl_item in items {
1268 self.print_assoc_item(impl_item);
1270 self.bclose(item.span);
1272 ast::ItemKind::Trait(box ast::TraitKind(
1280 self.print_visibility(&item.vis);
1281 self.print_unsafety(unsafety);
1282 self.print_is_auto(is_auto);
1283 self.word_nbsp("trait");
1284 self.print_ident(item.ident);
1285 self.print_generic_params(&generics.params);
1286 let mut real_bounds = Vec::with_capacity(bounds.len());
1287 for b in bounds.iter() {
1288 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1290 self.word_space("for ?");
1291 self.print_trait_ref(&ptr.trait_ref);
1293 real_bounds.push(b.clone());
1296 self.print_type_bounds(":", &real_bounds[..]);
1297 self.print_where_clause(&generics.where_clause);
1300 self.print_inner_attributes(&item.attrs);
1301 for trait_item in trait_items {
1302 self.print_assoc_item(trait_item);
1304 self.bclose(item.span);
1306 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1308 self.print_visibility(&item.vis);
1309 self.word_nbsp("trait");
1310 self.print_ident(item.ident);
1311 self.print_generic_params(&generics.params);
1312 let mut real_bounds = Vec::with_capacity(bounds.len());
1313 // FIXME(durka) this seems to be some quite outdated syntax
1314 for b in bounds.iter() {
1315 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1317 self.word_space("for ?");
1318 self.print_trait_ref(&ptr.trait_ref);
1320 real_bounds.push(b.clone());
1324 self.print_type_bounds("=", &real_bounds[..]);
1325 self.print_where_clause(&generics.where_clause);
1328 ast::ItemKind::MacCall(ref mac) => {
1329 self.print_mac(mac);
1330 if mac.args.need_semicolon() {
1334 ast::ItemKind::MacroDef(ref macro_def) => {
1335 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1336 state.print_visibility(&item.vis)
1340 self.ann.post(self, AnnNode::Item(item))
1343 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1344 self.print_path(&t.path, false, 0)
1347 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1348 if !generic_params.is_empty() {
1350 self.print_generic_params(generic_params);
1355 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1356 self.print_formal_generic_params(&t.bound_generic_params);
1357 self.print_trait_ref(&t.trait_ref)
1360 crate fn print_enum_def(
1362 enum_definition: &ast::EnumDef,
1363 generics: &ast::Generics,
1365 span: rustc_span::Span,
1366 visibility: &ast::Visibility,
1368 self.head(visibility_qualified(visibility, "enum"));
1369 self.print_ident(ident);
1370 self.print_generic_params(&generics.params);
1371 self.print_where_clause(&generics.where_clause);
1373 self.print_variants(&enum_definition.variants, span)
1376 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1379 self.space_if_not_bol();
1380 self.maybe_print_comment(v.span.lo());
1381 self.print_outer_attributes(&v.attrs);
1382 self.ibox(INDENT_UNIT);
1383 self.print_variant(v);
1386 self.maybe_print_trailing_comment(v.span, None);
1391 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1393 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1394 ast::VisibilityKind::Crate(sugar) => match sugar {
1395 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1396 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1398 ast::VisibilityKind::Restricted { ref path, .. } => {
1399 let path = self.to_string(|s| s.print_path(path, false, 0));
1400 if path == "self" || path == "super" {
1401 self.word_nbsp(format!("pub({})", path))
1403 self.word_nbsp(format!("pub(in {})", path))
1406 ast::VisibilityKind::Inherited => {}
1410 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1411 if let ast::Defaultness::Default(_) = defaultness {
1412 self.word_nbsp("default");
1416 crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1418 self.hardbreak_if_not_bol();
1420 for field in fields {
1421 self.hardbreak_if_not_bol();
1422 self.maybe_print_comment(field.span.lo());
1423 self.print_outer_attributes(&field.attrs);
1424 self.print_visibility(&field.vis);
1425 self.print_ident(field.ident.unwrap());
1426 self.word_nbsp(":");
1427 self.print_type(&field.ty);
1434 crate fn print_struct(
1436 struct_def: &ast::VariantData,
1437 generics: &ast::Generics,
1439 span: rustc_span::Span,
1440 print_finalizer: bool,
1442 self.print_ident(ident);
1443 self.print_generic_params(&generics.params);
1445 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1446 if let ast::VariantData::Tuple(..) = struct_def {
1448 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1449 s.maybe_print_comment(field.span.lo());
1450 s.print_outer_attributes(&field.attrs);
1451 s.print_visibility(&field.vis);
1452 s.print_type(&field.ty)
1456 self.print_where_clause(&generics.where_clause);
1457 if print_finalizer {
1461 self.end(); // Close the outer-box.
1463 ast::VariantData::Struct(ref fields, ..) => {
1464 self.print_where_clause(&generics.where_clause);
1466 self.print_record_struct_body(fields, span);
1471 crate fn print_variant(&mut self, v: &ast::Variant) {
1473 self.print_visibility(&v.vis);
1474 let generics = ast::Generics::default();
1475 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1476 if let Some(ref d) = v.disr_expr {
1478 self.word_space("=");
1479 self.print_expr(&d.value)
1483 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1484 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1485 self.ann.pre(self, AnnNode::SubItem(id));
1486 self.hardbreak_if_not_bol();
1487 self.maybe_print_comment(span.lo());
1488 self.print_outer_attributes(attrs);
1490 ast::AssocItemKind::Fn(box ast::FnKind(def, sig, gen, body)) => {
1491 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1493 ast::AssocItemKind::Const(def, ty, body) => {
1494 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1496 ast::AssocItemKind::TyAlias(box ast::TyAliasKind(def, generics, bounds, ty)) => {
1497 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1499 ast::AssocItemKind::MacCall(m) => {
1501 if m.args.need_semicolon() {
1506 self.ann.post(self, AnnNode::SubItem(id))
1509 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1510 self.maybe_print_comment(st.span.lo());
1512 ast::StmtKind::Local(ref loc) => {
1513 self.print_outer_attributes(&loc.attrs);
1514 self.space_if_not_bol();
1515 self.ibox(INDENT_UNIT);
1516 self.word_nbsp("let");
1518 self.ibox(INDENT_UNIT);
1519 self.print_local_decl(loc);
1521 if let Some((init, els)) = loc.kind.init_else_opt() {
1523 self.word_space("=");
1524 self.print_expr(init);
1525 if let Some(els) = els {
1526 self.cbox(INDENT_UNIT);
1527 self.ibox(INDENT_UNIT);
1528 self.s.word(" else ");
1529 self.print_block(els);
1533 self.end(); // `let` ibox
1535 ast::StmtKind::Item(ref item) => self.print_item(item),
1536 ast::StmtKind::Expr(ref expr) => {
1537 self.space_if_not_bol();
1538 self.print_expr_outer_attr_style(expr, false);
1539 if classify::expr_requires_semi_to_be_stmt(expr) {
1543 ast::StmtKind::Semi(ref expr) => {
1544 self.space_if_not_bol();
1545 self.print_expr_outer_attr_style(expr, false);
1548 ast::StmtKind::Empty => {
1549 self.space_if_not_bol();
1552 ast::StmtKind::MacCall(ref mac) => {
1553 self.space_if_not_bol();
1554 self.print_outer_attributes(&mac.attrs);
1555 self.print_mac(&mac.mac);
1556 if mac.style == ast::MacStmtStyle::Semicolon {
1561 self.maybe_print_trailing_comment(st.span, None)
1564 crate fn print_block(&mut self, blk: &ast::Block) {
1565 self.print_block_with_attrs(blk, &[])
1568 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1569 self.print_block_maybe_unclosed(blk, &[], false)
1572 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1573 self.print_block_maybe_unclosed(blk, attrs, true)
1576 crate fn print_block_maybe_unclosed(
1579 attrs: &[ast::Attribute],
1583 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1584 BlockCheckMode::Default => (),
1586 self.maybe_print_comment(blk.span.lo());
1587 self.ann.pre(self, AnnNode::Block(blk));
1590 self.print_inner_attributes(attrs);
1592 for (i, st) in blk.stmts.iter().enumerate() {
1594 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1595 self.maybe_print_comment(st.span.lo());
1596 self.space_if_not_bol();
1597 self.print_expr_outer_attr_style(expr, false);
1598 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1600 _ => self.print_stmt(st),
1604 self.bclose_maybe_open(blk.span, close_box);
1605 self.ann.post(self, AnnNode::Block(blk))
1608 /// Print a `let pat = expr` expression.
1609 crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1610 self.s.word("let ");
1611 self.print_pat(pat);
1613 self.word_space("=");
1614 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1615 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1618 fn print_else(&mut self, els: Option<&ast::Expr>) {
1619 if let Some(_else) = els {
1621 // Another `else if` block.
1622 ast::ExprKind::If(ref i, ref then, ref e) => {
1623 self.cbox(INDENT_UNIT - 1);
1625 self.s.word(" else if ");
1626 self.print_expr_as_cond(i);
1628 self.print_block(then);
1629 self.print_else(e.as_deref())
1631 // Final `else` block.
1632 ast::ExprKind::Block(ref b, _) => {
1633 self.cbox(INDENT_UNIT - 1);
1635 self.s.word(" else ");
1638 // Constraints would be great here!
1640 panic!("print_if saw if with weird alternative");
1646 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1648 self.print_expr_as_cond(test);
1650 self.print_block(blk);
1651 self.print_else(elseopt)
1654 crate fn print_mac(&mut self, m: &ast::MacCall) {
1655 self.print_mac_common(
1656 Some(MacHeader::Path(&m.path)),
1660 &m.args.inner_tokens(),
1666 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1668 self.commasep_exprs(Inconsistent, args);
1672 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1673 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1676 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1677 /// `if cond { ... }`.
1678 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1679 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1682 // Does `expr` need parenthesis when printed in a condition position?
1684 // These cases need parens due to the parse error observed in #26461: `if return {}`
1685 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1686 fn cond_needs_par(expr: &ast::Expr) -> bool {
1688 ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1689 _ => parser::contains_exterior_struct_lit(expr),
1693 /// Prints `expr` or `(expr)` when `needs_par` holds.
1694 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1698 self.print_expr(expr);
1704 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1705 self.ibox(INDENT_UNIT);
1707 self.commasep_exprs(Inconsistent, exprs);
1712 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1713 self.ibox(INDENT_UNIT);
1714 self.s.word("const");
1715 self.print_expr(&expr.value);
1719 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1720 self.ibox(INDENT_UNIT);
1722 self.print_expr(element);
1723 self.word_space(";");
1724 self.print_expr(&count.value);
1729 fn print_expr_struct(
1731 qself: &Option<ast::QSelf>,
1733 fields: &[ast::ExprField],
1734 rest: &ast::StructRest,
1736 if let Some(qself) = qself {
1737 self.print_qpath(path, qself, true);
1739 self.print_path(path, true, 0);
1746 s.print_outer_attributes(&field.attrs);
1747 s.ibox(INDENT_UNIT);
1748 if !field.is_shorthand {
1749 s.print_ident(field.ident);
1752 s.print_expr(&field.expr);
1758 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1759 self.ibox(INDENT_UNIT);
1760 if !fields.is_empty() {
1765 if let ast::StructRest::Base(ref expr) = *rest {
1766 self.print_expr(expr);
1770 ast::StructRest::None if !fields.is_empty() => self.s.word(","),
1776 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1778 self.commasep_exprs(Inconsistent, exprs);
1779 if exprs.len() == 1 {
1785 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1786 let prec = match func.kind {
1787 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1788 _ => parser::PREC_POSTFIX,
1791 self.print_expr_maybe_paren(func, prec);
1792 self.print_call_post(args)
1795 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1796 let base_args = &args[1..];
1797 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1799 self.print_ident(segment.ident);
1800 if let Some(ref args) = segment.args {
1801 self.print_generic_args(args, true);
1803 self.print_call_post(base_args)
1806 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1807 let assoc_op = AssocOp::from_ast_binop(op.node);
1808 let prec = assoc_op.precedence() as i8;
1809 let fixity = assoc_op.fixity();
1811 let (left_prec, right_prec) = match fixity {
1812 Fixity::Left => (prec, prec + 1),
1813 Fixity::Right => (prec + 1, prec),
1814 Fixity::None => (prec + 1, prec + 1),
1817 let left_prec = match (&lhs.kind, op.node) {
1818 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1819 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1820 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1821 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1822 parser::PREC_FORCE_PAREN
1824 // We are given `(let _ = a) OP b`.
1826 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1827 // as the parser will interpret this as `(let _ = a) OP b`.
1829 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1830 // parens are required since the parser would interpret `let a = b < c` as
1831 // `let a = (b < c)`. To achieve this, we force parens.
1832 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1833 parser::PREC_FORCE_PAREN
1838 self.print_expr_maybe_paren(lhs, left_prec);
1840 self.word_space(op.node.to_string());
1841 self.print_expr_maybe_paren(rhs, right_prec)
1844 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1845 self.s.word(ast::UnOp::to_string(op));
1846 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1849 fn print_expr_addr_of(
1851 kind: ast::BorrowKind,
1852 mutability: ast::Mutability,
1857 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1858 ast::BorrowKind::Raw => {
1859 self.word_nbsp("raw");
1860 self.print_mutability(mutability, true);
1863 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1866 pub fn print_expr(&mut self, expr: &ast::Expr) {
1867 self.print_expr_outer_attr_style(expr, true)
1870 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1871 self.maybe_print_comment(expr.span.lo());
1873 let attrs = &expr.attrs;
1875 self.print_outer_attributes_inline(attrs);
1877 self.print_outer_attributes(attrs);
1880 self.ibox(INDENT_UNIT);
1881 self.ann.pre(self, AnnNode::Expr(expr));
1883 ast::ExprKind::Box(ref expr) => {
1884 self.word_space("box");
1885 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1887 ast::ExprKind::Array(ref exprs) => {
1888 self.print_expr_vec(exprs);
1890 ast::ExprKind::ConstBlock(ref anon_const) => {
1891 self.print_expr_anon_const(anon_const);
1893 ast::ExprKind::Repeat(ref element, ref count) => {
1894 self.print_expr_repeat(element, count);
1896 ast::ExprKind::Struct(ref se) => {
1897 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1899 ast::ExprKind::Tup(ref exprs) => {
1900 self.print_expr_tup(exprs);
1902 ast::ExprKind::Call(ref func, ref args) => {
1903 self.print_expr_call(func, &args[..]);
1905 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1906 self.print_expr_method_call(segment, &args[..]);
1908 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1909 self.print_expr_binary(op, lhs, rhs);
1911 ast::ExprKind::Unary(op, ref expr) => {
1912 self.print_expr_unary(op, expr);
1914 ast::ExprKind::AddrOf(k, m, ref expr) => {
1915 self.print_expr_addr_of(k, m, expr);
1917 ast::ExprKind::Lit(ref lit) => {
1918 self.print_literal(lit);
1920 ast::ExprKind::Cast(ref expr, ref ty) => {
1921 let prec = AssocOp::As.precedence() as i8;
1922 self.print_expr_maybe_paren(expr, prec);
1924 self.word_space("as");
1925 self.print_type(ty);
1927 ast::ExprKind::Type(ref expr, ref ty) => {
1928 let prec = AssocOp::Colon.precedence() as i8;
1929 self.print_expr_maybe_paren(expr, prec);
1930 self.word_space(":");
1931 self.print_type(ty);
1933 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
1934 self.print_let(pat, scrutinee);
1936 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1937 self.print_if(test, blk, elseopt.as_deref())
1939 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1940 if let Some(label) = opt_label {
1941 self.print_ident(label.ident);
1942 self.word_space(":");
1945 self.print_expr_as_cond(test);
1947 self.print_block_with_attrs(blk, attrs);
1949 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1950 if let Some(label) = opt_label {
1951 self.print_ident(label.ident);
1952 self.word_space(":");
1955 self.print_pat(pat);
1957 self.word_space("in");
1958 self.print_expr_as_cond(iter);
1960 self.print_block_with_attrs(blk, attrs);
1962 ast::ExprKind::Loop(ref blk, opt_label) => {
1963 if let Some(label) = opt_label {
1964 self.print_ident(label.ident);
1965 self.word_space(":");
1968 self.print_block_with_attrs(blk, attrs);
1970 ast::ExprKind::Match(ref expr, ref arms) => {
1971 self.cbox(INDENT_UNIT);
1972 self.ibox(INDENT_UNIT);
1973 self.word_nbsp("match");
1974 self.print_expr_as_cond(expr);
1977 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1979 self.print_arm(arm);
1981 self.bclose(expr.span);
1983 ast::ExprKind::Closure(
1991 self.print_movability(movability);
1992 self.print_asyncness(asyncness);
1993 self.print_capture_clause(capture_clause);
1995 self.print_fn_params_and_ret(decl, true);
1997 self.print_expr(body);
1998 self.end(); // need to close a box
2000 // a box will be closed by print_expr, but we didn't want an overall
2001 // wrapper so we closed the corresponding opening. so create an
2002 // empty box to satisfy the close.
2005 ast::ExprKind::Block(ref blk, opt_label) => {
2006 if let Some(label) = opt_label {
2007 self.print_ident(label.ident);
2008 self.word_space(":");
2010 // containing cbox, will be closed by print-block at }
2011 self.cbox(INDENT_UNIT);
2012 // head-box, will be closed by print-block after {
2014 self.print_block_with_attrs(blk, attrs);
2016 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2017 self.word_nbsp("async");
2018 self.print_capture_clause(capture_clause);
2020 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2021 self.cbox(INDENT_UNIT);
2023 self.print_block_with_attrs(blk, attrs);
2025 ast::ExprKind::Await(ref expr) => {
2026 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2027 self.s.word(".await");
2029 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2030 let prec = AssocOp::Assign.precedence() as i8;
2031 self.print_expr_maybe_paren(lhs, prec + 1);
2033 self.word_space("=");
2034 self.print_expr_maybe_paren(rhs, prec);
2036 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2037 let prec = AssocOp::Assign.precedence() as i8;
2038 self.print_expr_maybe_paren(lhs, prec + 1);
2040 self.s.word(op.node.to_string());
2041 self.word_space("=");
2042 self.print_expr_maybe_paren(rhs, prec);
2044 ast::ExprKind::Field(ref expr, ident) => {
2045 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2047 self.print_ident(ident);
2049 ast::ExprKind::Index(ref expr, ref index) => {
2050 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2052 self.print_expr(index);
2055 ast::ExprKind::Range(ref start, ref end, limits) => {
2056 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2057 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2058 // Here we use a fake precedence value so that any child with lower precedence than
2059 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2060 let fake_prec = AssocOp::LOr.precedence() as i8;
2061 if let Some(ref e) = *start {
2062 self.print_expr_maybe_paren(e, fake_prec);
2064 if limits == ast::RangeLimits::HalfOpen {
2069 if let Some(ref e) = *end {
2070 self.print_expr_maybe_paren(e, fake_prec);
2073 ast::ExprKind::Underscore => self.s.word("_"),
2074 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2075 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2076 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2077 self.s.word("break");
2079 if let Some(label) = opt_label {
2080 self.print_ident(label.ident);
2083 if let Some(ref expr) = *opt_expr {
2084 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2088 ast::ExprKind::Continue(opt_label) => {
2089 self.s.word("continue");
2091 if let Some(label) = opt_label {
2092 self.print_ident(label.ident);
2096 ast::ExprKind::Ret(ref result) => {
2097 self.s.word("return");
2098 if let Some(ref expr) = *result {
2100 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2103 ast::ExprKind::InlineAsm(ref a) => {
2105 self.print_inline_asm(a);
2107 ast::ExprKind::LlvmInlineAsm(ref a) => {
2108 self.s.word("llvm_asm!");
2110 self.print_symbol(a.asm, a.asm_str_style);
2111 self.word_space(":");
2113 self.commasep(Inconsistent, &a.outputs, |s, out| {
2114 let constraint = out.constraint.as_str();
2115 let mut ch = constraint.chars();
2117 Some('=') if out.is_rw => {
2118 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2120 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2123 s.print_expr(&out.expr);
2127 self.word_space(":");
2129 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2130 s.print_symbol(co, ast::StrStyle::Cooked);
2136 self.word_space(":");
2138 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2139 s.print_symbol(co, ast::StrStyle::Cooked);
2142 let mut options = vec![];
2144 options.push("volatile");
2147 options.push("alignstack");
2149 if a.dialect == ast::LlvmAsmDialect::Intel {
2150 options.push("intel");
2153 if !options.is_empty() {
2155 self.word_space(":");
2156 self.commasep(Inconsistent, &options, |s, &co| {
2157 s.print_string(co, ast::StrStyle::Cooked);
2163 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2164 ast::ExprKind::Paren(ref e) => {
2169 ast::ExprKind::Yield(ref e) => {
2170 self.s.word("yield");
2172 if let Some(ref expr) = *e {
2174 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2177 ast::ExprKind::Try(ref e) => {
2178 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2181 ast::ExprKind::TryBlock(ref blk) => {
2184 self.print_block_with_attrs(blk, attrs)
2186 ast::ExprKind::Err => {
2188 self.s.word("/*ERROR*/");
2192 self.ann.post(self, AnnNode::Expr(expr));
2196 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2199 Operand(&'a InlineAsmOperand),
2201 Options(InlineAsmOptions),
2204 let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2205 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2206 if let Some((abi, _)) = asm.clobber_abi {
2207 args.push(AsmArg::ClobberAbi(abi));
2209 if !asm.options.is_empty() {
2210 args.push(AsmArg::Options(asm.options));
2214 self.commasep(Consistent, &args, |s, arg| match arg {
2215 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2216 AsmArg::Operand(op) => {
2217 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2218 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2219 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2222 InlineAsmOperand::In { reg, expr } => {
2225 print_reg_or_class(s, reg);
2230 InlineAsmOperand::Out { reg, late, expr } => {
2231 s.word(if *late { "lateout" } else { "out" });
2233 print_reg_or_class(s, reg);
2237 Some(expr) => s.print_expr(expr),
2238 None => s.word("_"),
2241 InlineAsmOperand::InOut { reg, late, expr } => {
2242 s.word(if *late { "inlateout" } else { "inout" });
2244 print_reg_or_class(s, reg);
2249 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2250 s.word(if *late { "inlateout" } else { "inout" });
2252 print_reg_or_class(s, reg);
2255 s.print_expr(in_expr);
2259 Some(out_expr) => s.print_expr(out_expr),
2260 None => s.word("_"),
2263 InlineAsmOperand::Const { anon_const } => {
2266 s.print_expr(&anon_const.value);
2268 InlineAsmOperand::Sym { expr } => {
2275 AsmArg::ClobberAbi(abi) => {
2276 s.word("clobber_abi");
2278 s.print_symbol(*abi, ast::StrStyle::Cooked);
2281 AsmArg::Options(opts) => {
2284 let mut options = vec![];
2285 if opts.contains(InlineAsmOptions::PURE) {
2286 options.push("pure");
2288 if opts.contains(InlineAsmOptions::NOMEM) {
2289 options.push("nomem");
2291 if opts.contains(InlineAsmOptions::READONLY) {
2292 options.push("readonly");
2294 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2295 options.push("preserves_flags");
2297 if opts.contains(InlineAsmOptions::NORETURN) {
2298 options.push("noreturn");
2300 if opts.contains(InlineAsmOptions::NOSTACK) {
2301 options.push("nostack");
2303 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2304 options.push("att_syntax");
2306 if opts.contains(InlineAsmOptions::RAW) {
2307 options.push("raw");
2309 s.commasep(Inconsistent, &options, |s, &opt| {
2318 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2319 self.print_pat(&loc.pat);
2320 if let Some(ref ty) = loc.ty {
2321 self.word_space(":");
2322 self.print_type(ty);
2326 crate fn print_name(&mut self, name: Symbol) {
2327 self.s.word(name.to_string());
2328 self.ann.post(self, AnnNode::Name(&name))
2331 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2333 self.print_type(&qself.ty);
2334 if qself.position > 0 {
2336 self.word_space("as");
2337 let depth = path.segments.len() - qself.position;
2338 self.print_path(path, false, depth);
2341 for item_segment in &path.segments[qself.position..] {
2343 self.print_ident(item_segment.ident);
2344 if let Some(ref args) = item_segment.args {
2345 self.print_generic_args(args, colons_before_params)
2350 crate fn print_pat(&mut self, pat: &ast::Pat) {
2351 self.maybe_print_comment(pat.span.lo());
2352 self.ann.pre(self, AnnNode::Pat(pat));
2353 /* Pat isn't normalized, but the beauty of it
2354 is that it doesn't matter */
2356 PatKind::Wild => self.s.word("_"),
2357 PatKind::Ident(binding_mode, ident, ref sub) => {
2358 match binding_mode {
2359 ast::BindingMode::ByRef(mutbl) => {
2360 self.word_nbsp("ref");
2361 self.print_mutability(mutbl, false);
2363 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2364 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2365 self.word_nbsp("mut");
2368 self.print_ident(ident);
2369 if let Some(ref p) = *sub {
2371 self.s.word_space("@");
2375 PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2376 if let Some(qself) = qself {
2377 self.print_qpath(path, qself, true);
2379 self.print_path(path, true, 0);
2382 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2385 PatKind::Or(ref pats) => {
2386 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2388 PatKind::Path(None, ref path) => {
2389 self.print_path(path, true, 0);
2391 PatKind::Path(Some(ref qself), ref path) => {
2392 self.print_qpath(path, qself, false);
2394 PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2395 if let Some(qself) = qself {
2396 self.print_qpath(path, qself, true);
2398 self.print_path(path, true, 0);
2401 self.word_space("{");
2406 s.cbox(INDENT_UNIT);
2407 if !f.is_shorthand {
2408 s.print_ident(f.ident);
2411 s.print_pat(&f.pat);
2417 if !fields.is_empty() {
2418 self.word_space(",");
2425 PatKind::Tuple(ref elts) => {
2427 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2428 if elts.len() == 1 {
2433 PatKind::Box(ref inner) => {
2434 self.s.word("box ");
2435 self.print_pat(inner);
2437 PatKind::Ref(ref inner, mutbl) => {
2439 if mutbl == ast::Mutability::Mut {
2440 self.s.word("mut ");
2442 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2446 self.print_pat(inner);
2449 self.print_pat(inner);
2452 PatKind::Lit(ref e) => self.print_expr(&**e),
2453 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2454 if let Some(e) = begin {
2459 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2460 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2461 RangeEnd::Excluded => self.s.word(".."),
2463 if let Some(e) = end {
2467 PatKind::Slice(ref elts) => {
2469 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2472 PatKind::Rest => self.s.word(".."),
2473 PatKind::Paren(ref inner) => {
2475 self.print_pat(inner);
2478 PatKind::MacCall(ref m) => self.print_mac(m),
2480 self.ann.post(self, AnnNode::Pat(pat))
2483 fn print_arm(&mut self, arm: &ast::Arm) {
2484 // Note, I have no idea why this check is necessary, but here it is.
2485 if arm.attrs.is_empty() {
2488 self.cbox(INDENT_UNIT);
2490 self.maybe_print_comment(arm.pat.span.lo());
2491 self.print_outer_attributes(&arm.attrs);
2492 self.print_pat(&arm.pat);
2494 if let Some(ref e) = arm.guard {
2495 self.word_space("if");
2499 self.word_space("=>");
2501 match arm.body.kind {
2502 ast::ExprKind::Block(ref blk, opt_label) => {
2503 if let Some(label) = opt_label {
2504 self.print_ident(label.ident);
2505 self.word_space(":");
2508 // The block will close the pattern's ibox.
2509 self.print_block_unclosed_indent(blk);
2511 // If it is a user-provided unsafe block, print a comma after it.
2512 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2517 self.end(); // Close the ibox for the pattern.
2518 self.print_expr(&arm.body);
2522 self.end(); // Close enclosing cbox.
2525 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2526 match explicit_self.node {
2527 SelfKind::Value(m) => {
2528 self.print_mutability(m, false);
2531 SelfKind::Region(ref lt, m) => {
2533 self.print_opt_lifetime(lt);
2534 self.print_mutability(m, false);
2537 SelfKind::Explicit(ref typ, m) => {
2538 self.print_mutability(m, false);
2539 self.s.word("self");
2540 self.word_space(":");
2541 self.print_type(typ)
2550 generics: &ast::Generics,
2551 vis: &ast::Visibility,
2552 defaultness: ast::Defaultness,
2553 body: Option<&ast::Block>,
2554 attrs: &[ast::Attribute],
2559 self.print_visibility(vis);
2560 self.print_defaultness(defaultness);
2561 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2562 if let Some(body) = body {
2564 self.print_block_with_attrs(body, attrs);
2573 header: ast::FnHeader,
2574 name: Option<Ident>,
2575 generics: &ast::Generics,
2577 self.print_fn_header_info(header);
2578 if let Some(name) = name {
2580 self.print_ident(name);
2582 self.print_generic_params(&generics.params);
2583 self.print_fn_params_and_ret(decl, false);
2584 self.print_where_clause(&generics.where_clause)
2587 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2588 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2590 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2592 self.print_fn_ret_ty(&decl.output)
2595 crate fn print_movability(&mut self, movability: ast::Movability) {
2597 ast::Movability::Static => self.word_space("static"),
2598 ast::Movability::Movable => {}
2602 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2603 if asyncness.is_async() {
2604 self.word_nbsp("async");
2608 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2609 match capture_clause {
2610 ast::CaptureBy::Value => self.word_space("move"),
2611 ast::CaptureBy::Ref => {}
2615 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2616 if !bounds.is_empty() {
2617 self.s.word(prefix);
2618 let mut first = true;
2619 for bound in bounds {
2620 if !(first && prefix.is_empty()) {
2626 self.word_space("+");
2630 GenericBound::Trait(tref, modifier) => {
2631 if modifier == &TraitBoundModifier::Maybe {
2634 self.print_poly_trait_ref(tref);
2636 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2642 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2643 self.print_name(lifetime.ident.name)
2646 crate fn print_lifetime_bounds(
2648 lifetime: ast::Lifetime,
2649 bounds: &ast::GenericBounds,
2651 self.print_lifetime(lifetime);
2652 if !bounds.is_empty() {
2654 for (i, bound) in bounds.iter().enumerate() {
2659 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2666 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2667 if generic_params.is_empty() {
2673 self.commasep(Inconsistent, &generic_params, |s, param| {
2674 s.print_outer_attributes_inline(¶m.attrs);
2677 ast::GenericParamKind::Lifetime => {
2678 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2679 s.print_lifetime_bounds(lt, ¶m.bounds)
2681 ast::GenericParamKind::Type { ref default } => {
2682 s.print_ident(param.ident);
2683 s.print_type_bounds(":", ¶m.bounds);
2684 if let Some(ref default) = default {
2687 s.print_type(default)
2690 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2691 s.word_space("const");
2692 s.print_ident(param.ident);
2696 s.print_type_bounds(":", ¶m.bounds);
2697 if let Some(ref default) = default {
2700 s.print_expr(&default.value);
2709 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2710 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2715 self.word_space("where");
2717 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2719 self.word_space(",");
2723 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2724 ref bound_generic_params,
2729 self.print_formal_generic_params(bound_generic_params);
2730 self.print_type(bounded_ty);
2731 self.print_type_bounds(":", bounds);
2733 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2738 self.print_lifetime_bounds(*lifetime, bounds);
2740 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2745 self.print_type(lhs_ty);
2747 self.word_space("=");
2748 self.print_type(rhs_ty);
2754 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2756 ast::UseTreeKind::Simple(rename, ..) => {
2757 self.print_path(&tree.prefix, false, 0);
2758 if let Some(rename) = rename {
2760 self.word_space("as");
2761 self.print_ident(rename);
2764 ast::UseTreeKind::Glob => {
2765 if !tree.prefix.segments.is_empty() {
2766 self.print_path(&tree.prefix, false, 0);
2771 ast::UseTreeKind::Nested(ref items) => {
2772 if tree.prefix.segments.is_empty() {
2775 self.print_path(&tree.prefix, false, 0);
2778 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2779 this.print_use_tree(tree)
2786 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2788 ast::Mutability::Mut => self.word_nbsp("mut"),
2789 ast::Mutability::Not => {
2791 self.word_nbsp("const");
2797 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2798 self.print_mutability(mt.mutbl, print_const);
2799 self.print_type(&mt.ty)
2802 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2803 self.ibox(INDENT_UNIT);
2805 self.print_outer_attributes_inline(&input.attrs);
2807 match input.ty.kind {
2808 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2810 if let Some(eself) = input.to_self() {
2811 self.print_explicit_self(&eself);
2813 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2814 ident.name == kw::Empty
2819 self.print_pat(&input.pat);
2823 self.print_type(&input.ty);
2830 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2831 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2832 self.space_if_not_bol();
2833 self.ibox(INDENT_UNIT);
2834 self.word_space("->");
2835 self.print_type(ty);
2837 self.maybe_print_comment(ty.span.lo());
2841 crate fn print_ty_fn(
2844 unsafety: ast::Unsafe,
2846 name: Option<Ident>,
2847 generic_params: &[ast::GenericParam],
2849 self.ibox(INDENT_UNIT);
2850 if !generic_params.is_empty() {
2852 self.print_generic_params(generic_params);
2854 let generics = ast::Generics {
2856 where_clause: ast::WhereClause {
2857 has_where_token: false,
2858 predicates: Vec::new(),
2859 span: rustc_span::DUMMY_SP,
2861 span: rustc_span::DUMMY_SP,
2863 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2864 self.print_fn(decl, header, name, &generics);
2868 crate fn maybe_print_trailing_comment(
2870 span: rustc_span::Span,
2871 next_pos: Option<BytePos>,
2873 if let Some(cmnts) = self.comments() {
2874 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2875 self.print_comment(&cmnt);
2880 crate fn print_remaining_comments(&mut self) {
2881 // If there aren't any remaining comments, then we need to manually
2882 // make sure there is a line break at the end.
2883 if self.next_comment().is_none() {
2886 while let Some(ref cmnt) = self.next_comment() {
2887 self.print_comment(cmnt);
2891 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2892 self.print_constness(header.constness);
2893 self.print_asyncness(header.asyncness);
2894 self.print_unsafety(header.unsafety);
2897 ast::Extern::None => {}
2898 ast::Extern::Implicit => {
2899 self.word_nbsp("extern");
2901 ast::Extern::Explicit(abi) => {
2902 self.word_nbsp("extern");
2903 self.print_literal(&abi.as_lit());
2911 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2913 ast::Unsafe::No => {}
2914 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2918 crate fn print_constness(&mut self, s: ast::Const) {
2920 ast::Const::No => {}
2921 ast::Const::Yes(_) => self.word_nbsp("const"),
2925 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2927 ast::IsAuto::Yes => self.word_nbsp("auto"),
2928 ast::IsAuto::No => {}