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::Paren(ref typ) => {
990 self.print_type(typ);
993 ast::TyKind::BareFn(ref f) => {
994 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
996 ast::TyKind::Path(None, ref path) => {
997 self.print_path(path, false, 0);
999 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
1000 ast::TyKind::TraitObject(ref bounds, syntax) => {
1001 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1002 self.print_type_bounds(prefix, &bounds[..]);
1004 ast::TyKind::ImplTrait(_, ref bounds) => {
1005 self.print_type_bounds("impl", &bounds[..]);
1007 ast::TyKind::Array(ref ty, ref length) => {
1009 self.print_type(ty);
1011 self.print_expr(&length.value);
1014 ast::TyKind::Typeof(ref e) => {
1015 self.s.word("typeof(");
1016 self.print_expr(&e.value);
1019 ast::TyKind::Infer => {
1022 ast::TyKind::Err => {
1024 self.s.word("/*ERROR*/");
1027 ast::TyKind::ImplicitSelf => {
1028 self.s.word("Self");
1030 ast::TyKind::MacCall(ref m) => {
1033 ast::TyKind::CVarArgs => {
1040 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1041 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1042 self.ann.pre(self, AnnNode::SubItem(id));
1043 self.hardbreak_if_not_bol();
1044 self.maybe_print_comment(span.lo());
1045 self.print_outer_attributes(attrs);
1047 ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1048 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1050 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1051 let def = ast::Defaultness::Final;
1052 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1054 ast::ForeignItemKind::TyAlias(box ast::TyAlias {
1060 self.print_associated_type(
1069 ast::ForeignItemKind::MacCall(m) => {
1071 if m.args.need_semicolon() {
1076 self.ann.post(self, AnnNode::SubItem(id))
1079 fn print_item_const(
1082 mutbl: Option<ast::Mutability>,
1084 body: Option<&ast::Expr>,
1085 vis: &ast::Visibility,
1086 defaultness: ast::Defaultness,
1089 self.print_visibility(vis);
1090 self.print_defaultness(defaultness);
1091 let leading = match mutbl {
1093 Some(ast::Mutability::Not) => "static",
1094 Some(ast::Mutability::Mut) => "static mut",
1096 self.word_space(leading);
1097 self.print_ident(ident);
1098 self.word_space(":");
1099 self.print_type(ty);
1101 self.end(); // end the head-ibox
1102 if let Some(body) = body {
1103 self.word_space("=");
1104 self.print_expr(body);
1107 self.end(); // end the outer cbox
1110 fn print_associated_type(
1113 generics: &ast::Generics,
1114 bounds: &ast::GenericBounds,
1115 ty: Option<&ast::Ty>,
1116 vis: &ast::Visibility,
1117 defaultness: ast::Defaultness,
1120 self.print_visibility(vis);
1121 self.print_defaultness(defaultness);
1122 self.word_space("type");
1123 self.print_ident(ident);
1124 self.print_generic_params(&generics.params);
1125 self.print_type_bounds(":", bounds);
1126 self.print_where_clause(&generics.where_clause);
1127 if let Some(ty) = ty {
1129 self.word_space("=");
1130 self.print_type(ty);
1133 self.end(); // end inner head-block
1134 self.end(); // end outer head-block
1137 /// Pretty-prints an item.
1138 crate fn print_item(&mut self, item: &ast::Item) {
1139 self.hardbreak_if_not_bol();
1140 self.maybe_print_comment(item.span.lo());
1141 self.print_outer_attributes(&item.attrs);
1142 self.ann.pre(self, AnnNode::Item(item));
1144 ast::ItemKind::ExternCrate(orig_name) => {
1145 self.head(visibility_qualified(&item.vis, "extern crate"));
1146 if let Some(orig_name) = orig_name {
1147 self.print_name(orig_name);
1152 self.print_ident(item.ident);
1154 self.end(); // end inner head-block
1155 self.end(); // end outer head-block
1157 ast::ItemKind::Use(ref tree) => {
1158 self.head(visibility_qualified(&item.vis, "use"));
1159 self.print_use_tree(tree);
1161 self.end(); // end inner head-block
1162 self.end(); // end outer head-block
1164 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1165 let def = ast::Defaultness::Final;
1166 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1168 ast::ItemKind::Const(def, ref ty, ref body) => {
1169 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1171 ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => {
1172 let body = body.as_deref();
1183 ast::ItemKind::Mod(unsafety, ref mod_kind) => {
1184 self.head(self.to_string(|s| {
1185 s.print_visibility(&item.vis);
1186 s.print_unsafety(unsafety);
1189 self.print_ident(item.ident);
1192 ModKind::Loaded(items, ..) => {
1195 self.print_inner_attributes(&item.attrs);
1197 self.print_item(item);
1199 self.bclose(item.span);
1201 ModKind::Unloaded => {
1203 self.end(); // end inner head-block
1204 self.end(); // end outer head-block
1208 ast::ItemKind::ForeignMod(ref nmod) => {
1209 self.head(self.to_string(|s| {
1210 s.print_unsafety(nmod.unsafety);
1213 if let Some(abi) = nmod.abi {
1214 self.print_literal(&abi.as_lit());
1218 self.print_foreign_mod(nmod, &item.attrs);
1219 self.bclose(item.span);
1221 ast::ItemKind::GlobalAsm(ref asm) => {
1222 self.head(visibility_qualified(&item.vis, "global_asm!"));
1223 self.print_inline_asm(asm);
1226 ast::ItemKind::TyAlias(box ast::TyAlias {
1232 let ty = ty.as_deref();
1233 self.print_associated_type(
1242 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1243 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1245 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1246 self.head(visibility_qualified(&item.vis, "struct"));
1247 self.print_struct(struct_def, generics, item.ident, item.span, true);
1249 ast::ItemKind::Union(ref struct_def, ref generics) => {
1250 self.head(visibility_qualified(&item.vis, "union"));
1251 self.print_struct(struct_def, generics, item.ident, item.span, true);
1253 ast::ItemKind::Impl(box ast::Impl {
1264 self.print_visibility(&item.vis);
1265 self.print_defaultness(defaultness);
1266 self.print_unsafety(unsafety);
1267 self.word_nbsp("impl");
1268 self.print_constness(constness);
1270 if !generics.params.is_empty() {
1271 self.print_generic_params(&generics.params);
1275 if let ast::ImplPolarity::Negative(_) = polarity {
1279 if let Some(ref t) = *of_trait {
1280 self.print_trait_ref(t);
1282 self.word_space("for");
1285 self.print_type(self_ty);
1286 self.print_where_clause(&generics.where_clause);
1290 self.print_inner_attributes(&item.attrs);
1291 for impl_item in items {
1292 self.print_assoc_item(impl_item);
1294 self.bclose(item.span);
1296 ast::ItemKind::Trait(box ast::Trait {
1305 self.print_visibility(&item.vis);
1306 self.print_unsafety(unsafety);
1307 self.print_is_auto(is_auto);
1308 self.word_nbsp("trait");
1309 self.print_ident(item.ident);
1310 self.print_generic_params(&generics.params);
1311 let mut real_bounds = Vec::with_capacity(bounds.len());
1312 for b in bounds.iter() {
1313 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1315 self.word_space("for ?");
1316 self.print_trait_ref(&ptr.trait_ref);
1318 real_bounds.push(b.clone());
1321 self.print_type_bounds(":", &real_bounds[..]);
1322 self.print_where_clause(&generics.where_clause);
1325 self.print_inner_attributes(&item.attrs);
1326 for trait_item in items {
1327 self.print_assoc_item(trait_item);
1329 self.bclose(item.span);
1331 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1333 self.print_visibility(&item.vis);
1334 self.word_nbsp("trait");
1335 self.print_ident(item.ident);
1336 self.print_generic_params(&generics.params);
1337 let mut real_bounds = Vec::with_capacity(bounds.len());
1338 // FIXME(durka) this seems to be some quite outdated syntax
1339 for b in bounds.iter() {
1340 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1342 self.word_space("for ?");
1343 self.print_trait_ref(&ptr.trait_ref);
1345 real_bounds.push(b.clone());
1349 self.print_type_bounds("=", &real_bounds[..]);
1350 self.print_where_clause(&generics.where_clause);
1353 ast::ItemKind::MacCall(ref mac) => {
1354 self.print_mac(mac);
1355 if mac.args.need_semicolon() {
1359 ast::ItemKind::MacroDef(ref macro_def) => {
1360 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1361 state.print_visibility(&item.vis)
1365 self.ann.post(self, AnnNode::Item(item))
1368 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1369 self.print_path(&t.path, false, 0)
1372 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1373 if !generic_params.is_empty() {
1375 self.print_generic_params(generic_params);
1380 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1381 self.print_formal_generic_params(&t.bound_generic_params);
1382 self.print_trait_ref(&t.trait_ref)
1385 crate fn print_enum_def(
1387 enum_definition: &ast::EnumDef,
1388 generics: &ast::Generics,
1390 span: rustc_span::Span,
1391 visibility: &ast::Visibility,
1393 self.head(visibility_qualified(visibility, "enum"));
1394 self.print_ident(ident);
1395 self.print_generic_params(&generics.params);
1396 self.print_where_clause(&generics.where_clause);
1398 self.print_variants(&enum_definition.variants, span)
1401 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1404 self.space_if_not_bol();
1405 self.maybe_print_comment(v.span.lo());
1406 self.print_outer_attributes(&v.attrs);
1407 self.ibox(INDENT_UNIT);
1408 self.print_variant(v);
1411 self.maybe_print_trailing_comment(v.span, None);
1416 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1418 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1419 ast::VisibilityKind::Crate(sugar) => match sugar {
1420 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1421 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1423 ast::VisibilityKind::Restricted { ref path, .. } => {
1424 let path = self.to_string(|s| s.print_path(path, false, 0));
1425 if path == "self" || path == "super" {
1426 self.word_nbsp(format!("pub({})", path))
1428 self.word_nbsp(format!("pub(in {})", path))
1431 ast::VisibilityKind::Inherited => {}
1435 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1436 if let ast::Defaultness::Default(_) = defaultness {
1437 self.word_nbsp("default");
1441 crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1444 self.hardbreak_if_not_bol();
1446 for field in fields {
1447 self.hardbreak_if_not_bol();
1448 self.maybe_print_comment(field.span.lo());
1449 self.print_outer_attributes(&field.attrs);
1450 self.print_visibility(&field.vis);
1451 self.print_ident(field.ident.unwrap());
1452 self.word_nbsp(":");
1453 self.print_type(&field.ty);
1460 crate fn print_struct(
1462 struct_def: &ast::VariantData,
1463 generics: &ast::Generics,
1465 span: rustc_span::Span,
1466 print_finalizer: bool,
1468 self.print_ident(ident);
1469 self.print_generic_params(&generics.params);
1471 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1472 if let ast::VariantData::Tuple(..) = struct_def {
1474 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1475 s.maybe_print_comment(field.span.lo());
1476 s.print_outer_attributes(&field.attrs);
1477 s.print_visibility(&field.vis);
1478 s.print_type(&field.ty)
1482 self.print_where_clause(&generics.where_clause);
1483 if print_finalizer {
1487 self.end(); // Close the outer-box.
1489 ast::VariantData::Struct(ref fields, ..) => {
1490 self.print_where_clause(&generics.where_clause);
1491 self.print_record_struct_body(fields, span);
1496 crate fn print_variant(&mut self, v: &ast::Variant) {
1498 self.print_visibility(&v.vis);
1499 let generics = ast::Generics::default();
1500 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1501 if let Some(ref d) = v.disr_expr {
1503 self.word_space("=");
1504 self.print_expr(&d.value)
1508 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1509 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1510 self.ann.pre(self, AnnNode::SubItem(id));
1511 self.hardbreak_if_not_bol();
1512 self.maybe_print_comment(span.lo());
1513 self.print_outer_attributes(attrs);
1515 ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1516 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1518 ast::AssocItemKind::Const(def, ty, body) => {
1519 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1521 ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
1522 self.print_associated_type(
1531 ast::AssocItemKind::MacCall(m) => {
1533 if m.args.need_semicolon() {
1538 self.ann.post(self, AnnNode::SubItem(id))
1541 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1542 self.maybe_print_comment(st.span.lo());
1544 ast::StmtKind::Local(ref loc) => {
1545 self.print_outer_attributes(&loc.attrs);
1546 self.space_if_not_bol();
1547 self.ibox(INDENT_UNIT);
1548 self.word_nbsp("let");
1550 self.ibox(INDENT_UNIT);
1551 self.print_local_decl(loc);
1553 if let Some((init, els)) = loc.kind.init_else_opt() {
1555 self.word_space("=");
1556 self.print_expr(init);
1557 if let Some(els) = els {
1558 self.cbox(INDENT_UNIT);
1559 self.ibox(INDENT_UNIT);
1560 self.s.word(" else ");
1561 self.print_block(els);
1565 self.end(); // `let` ibox
1567 ast::StmtKind::Item(ref item) => self.print_item(item),
1568 ast::StmtKind::Expr(ref expr) => {
1569 self.space_if_not_bol();
1570 self.print_expr_outer_attr_style(expr, false);
1571 if classify::expr_requires_semi_to_be_stmt(expr) {
1575 ast::StmtKind::Semi(ref expr) => {
1576 self.space_if_not_bol();
1577 self.print_expr_outer_attr_style(expr, false);
1580 ast::StmtKind::Empty => {
1581 self.space_if_not_bol();
1584 ast::StmtKind::MacCall(ref mac) => {
1585 self.space_if_not_bol();
1586 self.print_outer_attributes(&mac.attrs);
1587 self.print_mac(&mac.mac);
1588 if mac.style == ast::MacStmtStyle::Semicolon {
1593 self.maybe_print_trailing_comment(st.span, None)
1596 crate fn print_block(&mut self, blk: &ast::Block) {
1597 self.print_block_with_attrs(blk, &[])
1600 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1601 self.print_block_maybe_unclosed(blk, &[], false)
1604 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1605 self.print_block_maybe_unclosed(blk, attrs, true)
1608 crate fn print_block_maybe_unclosed(
1611 attrs: &[ast::Attribute],
1615 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1616 BlockCheckMode::Default => (),
1618 self.maybe_print_comment(blk.span.lo());
1619 self.ann.pre(self, AnnNode::Block(blk));
1622 self.print_inner_attributes(attrs);
1624 for (i, st) in blk.stmts.iter().enumerate() {
1626 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1627 self.maybe_print_comment(st.span.lo());
1628 self.space_if_not_bol();
1629 self.print_expr_outer_attr_style(expr, false);
1630 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1632 _ => self.print_stmt(st),
1636 self.bclose_maybe_open(blk.span, close_box);
1637 self.ann.post(self, AnnNode::Block(blk))
1640 /// Print a `let pat = expr` expression.
1641 crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1642 self.s.word("let ");
1643 self.print_pat(pat);
1645 self.word_space("=");
1646 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1647 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1650 fn print_else(&mut self, els: Option<&ast::Expr>) {
1651 if let Some(_else) = els {
1653 // Another `else if` block.
1654 ast::ExprKind::If(ref i, ref then, ref e) => {
1655 self.cbox(INDENT_UNIT - 1);
1657 self.s.word(" else if ");
1658 self.print_expr_as_cond(i);
1660 self.print_block(then);
1661 self.print_else(e.as_deref())
1663 // Final `else` block.
1664 ast::ExprKind::Block(ref b, _) => {
1665 self.cbox(INDENT_UNIT - 1);
1667 self.s.word(" else ");
1670 // Constraints would be great here!
1672 panic!("print_if saw if with weird alternative");
1678 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1680 self.print_expr_as_cond(test);
1682 self.print_block(blk);
1683 self.print_else(elseopt)
1686 crate fn print_mac(&mut self, m: &ast::MacCall) {
1687 self.print_mac_common(
1688 Some(MacHeader::Path(&m.path)),
1692 &m.args.inner_tokens(),
1698 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1700 self.commasep_exprs(Inconsistent, args);
1704 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1705 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1708 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1709 /// `if cond { ... }`.
1710 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1711 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1714 // Does `expr` need parentheses when printed in a condition position?
1716 // These cases need parens due to the parse error observed in #26461: `if return {}`
1717 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1718 fn cond_needs_par(expr: &ast::Expr) -> bool {
1720 ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1721 _ => parser::contains_exterior_struct_lit(expr),
1725 /// Prints `expr` or `(expr)` when `needs_par` holds.
1726 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1730 self.print_expr(expr);
1736 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1737 self.ibox(INDENT_UNIT);
1739 self.commasep_exprs(Inconsistent, exprs);
1744 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1745 self.ibox(INDENT_UNIT);
1746 self.s.word("const");
1747 self.print_expr(&expr.value);
1751 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1752 self.ibox(INDENT_UNIT);
1754 self.print_expr(element);
1755 self.word_space(";");
1756 self.print_expr(&count.value);
1761 fn print_expr_struct(
1763 qself: &Option<ast::QSelf>,
1765 fields: &[ast::ExprField],
1766 rest: &ast::StructRest,
1768 if let Some(qself) = qself {
1769 self.print_qpath(path, qself, true);
1771 self.print_path(path, true, 0);
1778 s.print_outer_attributes(&field.attrs);
1779 s.ibox(INDENT_UNIT);
1780 if !field.is_shorthand {
1781 s.print_ident(field.ident);
1784 s.print_expr(&field.expr);
1790 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1791 self.ibox(INDENT_UNIT);
1792 if !fields.is_empty() {
1797 if let ast::StructRest::Base(ref expr) = *rest {
1798 self.print_expr(expr);
1802 ast::StructRest::None if !fields.is_empty() => self.s.word(","),
1808 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1810 self.commasep_exprs(Inconsistent, exprs);
1811 if exprs.len() == 1 {
1817 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1818 let prec = match func.kind {
1819 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1820 _ => parser::PREC_POSTFIX,
1823 self.print_expr_maybe_paren(func, prec);
1824 self.print_call_post(args)
1827 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1828 let base_args = &args[1..];
1829 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1831 self.print_ident(segment.ident);
1832 if let Some(ref args) = segment.args {
1833 self.print_generic_args(args, true);
1835 self.print_call_post(base_args)
1838 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1839 let assoc_op = AssocOp::from_ast_binop(op.node);
1840 let prec = assoc_op.precedence() as i8;
1841 let fixity = assoc_op.fixity();
1843 let (left_prec, right_prec) = match fixity {
1844 Fixity::Left => (prec, prec + 1),
1845 Fixity::Right => (prec + 1, prec),
1846 Fixity::None => (prec + 1, prec + 1),
1849 let left_prec = match (&lhs.kind, op.node) {
1850 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1851 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1852 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1853 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1854 parser::PREC_FORCE_PAREN
1856 // We are given `(let _ = a) OP b`.
1858 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1859 // as the parser will interpret this as `(let _ = a) OP b`.
1861 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1862 // parens are required since the parser would interpret `let a = b < c` as
1863 // `let a = (b < c)`. To achieve this, we force parens.
1864 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1865 parser::PREC_FORCE_PAREN
1870 self.print_expr_maybe_paren(lhs, left_prec);
1872 self.word_space(op.node.to_string());
1873 self.print_expr_maybe_paren(rhs, right_prec)
1876 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1877 self.s.word(ast::UnOp::to_string(op));
1878 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1881 fn print_expr_addr_of(
1883 kind: ast::BorrowKind,
1884 mutability: ast::Mutability,
1889 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1890 ast::BorrowKind::Raw => {
1891 self.word_nbsp("raw");
1892 self.print_mutability(mutability, true);
1895 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1898 pub fn print_expr(&mut self, expr: &ast::Expr) {
1899 self.print_expr_outer_attr_style(expr, true)
1902 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1903 self.maybe_print_comment(expr.span.lo());
1905 let attrs = &expr.attrs;
1907 self.print_outer_attributes_inline(attrs);
1909 self.print_outer_attributes(attrs);
1912 self.ibox(INDENT_UNIT);
1913 self.ann.pre(self, AnnNode::Expr(expr));
1915 ast::ExprKind::Box(ref expr) => {
1916 self.word_space("box");
1917 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1919 ast::ExprKind::Array(ref exprs) => {
1920 self.print_expr_vec(exprs);
1922 ast::ExprKind::ConstBlock(ref anon_const) => {
1923 self.print_expr_anon_const(anon_const);
1925 ast::ExprKind::Repeat(ref element, ref count) => {
1926 self.print_expr_repeat(element, count);
1928 ast::ExprKind::Struct(ref se) => {
1929 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1931 ast::ExprKind::Tup(ref exprs) => {
1932 self.print_expr_tup(exprs);
1934 ast::ExprKind::Call(ref func, ref args) => {
1935 self.print_expr_call(func, &args[..]);
1937 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1938 self.print_expr_method_call(segment, &args[..]);
1940 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1941 self.print_expr_binary(op, lhs, rhs);
1943 ast::ExprKind::Unary(op, ref expr) => {
1944 self.print_expr_unary(op, expr);
1946 ast::ExprKind::AddrOf(k, m, ref expr) => {
1947 self.print_expr_addr_of(k, m, expr);
1949 ast::ExprKind::Lit(ref lit) => {
1950 self.print_literal(lit);
1952 ast::ExprKind::Cast(ref expr, ref ty) => {
1953 let prec = AssocOp::As.precedence() as i8;
1954 self.print_expr_maybe_paren(expr, prec);
1956 self.word_space("as");
1957 self.print_type(ty);
1959 ast::ExprKind::Type(ref expr, ref ty) => {
1960 let prec = AssocOp::Colon.precedence() as i8;
1961 self.print_expr_maybe_paren(expr, prec);
1962 self.word_space(":");
1963 self.print_type(ty);
1965 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
1966 self.print_let(pat, scrutinee);
1968 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1969 self.print_if(test, blk, elseopt.as_deref())
1971 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1972 if let Some(label) = opt_label {
1973 self.print_ident(label.ident);
1974 self.word_space(":");
1977 self.print_expr_as_cond(test);
1979 self.print_block_with_attrs(blk, attrs);
1981 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1982 if let Some(label) = opt_label {
1983 self.print_ident(label.ident);
1984 self.word_space(":");
1987 self.print_pat(pat);
1989 self.word_space("in");
1990 self.print_expr_as_cond(iter);
1992 self.print_block_with_attrs(blk, attrs);
1994 ast::ExprKind::Loop(ref blk, opt_label) => {
1995 if let Some(label) = opt_label {
1996 self.print_ident(label.ident);
1997 self.word_space(":");
2000 self.print_block_with_attrs(blk, attrs);
2002 ast::ExprKind::Match(ref expr, ref arms) => {
2003 self.cbox(INDENT_UNIT);
2004 self.ibox(INDENT_UNIT);
2005 self.word_nbsp("match");
2006 self.print_expr_as_cond(expr);
2009 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2011 self.print_arm(arm);
2013 self.bclose(expr.span);
2015 ast::ExprKind::Closure(
2023 self.print_movability(movability);
2024 self.print_asyncness(asyncness);
2025 self.print_capture_clause(capture_clause);
2027 self.print_fn_params_and_ret(decl, true);
2029 self.print_expr(body);
2030 self.end(); // need to close a box
2032 // a box will be closed by print_expr, but we didn't want an overall
2033 // wrapper so we closed the corresponding opening. so create an
2034 // empty box to satisfy the close.
2037 ast::ExprKind::Block(ref blk, opt_label) => {
2038 if let Some(label) = opt_label {
2039 self.print_ident(label.ident);
2040 self.word_space(":");
2042 // containing cbox, will be closed by print-block at }
2043 self.cbox(INDENT_UNIT);
2044 // head-box, will be closed by print-block after {
2046 self.print_block_with_attrs(blk, attrs);
2048 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2049 self.word_nbsp("async");
2050 self.print_capture_clause(capture_clause);
2052 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2053 self.cbox(INDENT_UNIT);
2055 self.print_block_with_attrs(blk, attrs);
2057 ast::ExprKind::Await(ref expr) => {
2058 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2059 self.s.word(".await");
2061 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2062 let prec = AssocOp::Assign.precedence() as i8;
2063 self.print_expr_maybe_paren(lhs, prec + 1);
2065 self.word_space("=");
2066 self.print_expr_maybe_paren(rhs, prec);
2068 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2069 let prec = AssocOp::Assign.precedence() as i8;
2070 self.print_expr_maybe_paren(lhs, prec + 1);
2072 self.s.word(op.node.to_string());
2073 self.word_space("=");
2074 self.print_expr_maybe_paren(rhs, prec);
2076 ast::ExprKind::Field(ref expr, ident) => {
2077 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2079 self.print_ident(ident);
2081 ast::ExprKind::Index(ref expr, ref index) => {
2082 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2084 self.print_expr(index);
2087 ast::ExprKind::Range(ref start, ref end, limits) => {
2088 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2089 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2090 // Here we use a fake precedence value so that any child with lower precedence than
2091 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2092 let fake_prec = AssocOp::LOr.precedence() as i8;
2093 if let Some(ref e) = *start {
2094 self.print_expr_maybe_paren(e, fake_prec);
2096 if limits == ast::RangeLimits::HalfOpen {
2101 if let Some(ref e) = *end {
2102 self.print_expr_maybe_paren(e, fake_prec);
2105 ast::ExprKind::Underscore => self.s.word("_"),
2106 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2107 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2108 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2109 self.s.word("break");
2111 if let Some(label) = opt_label {
2112 self.print_ident(label.ident);
2115 if let Some(ref expr) = *opt_expr {
2116 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2120 ast::ExprKind::Continue(opt_label) => {
2121 self.s.word("continue");
2123 if let Some(label) = opt_label {
2124 self.print_ident(label.ident);
2128 ast::ExprKind::Ret(ref result) => {
2129 self.s.word("return");
2130 if let Some(ref expr) = *result {
2132 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2135 ast::ExprKind::InlineAsm(ref a) => {
2137 self.print_inline_asm(a);
2139 ast::ExprKind::LlvmInlineAsm(ref a) => {
2140 self.s.word("llvm_asm!");
2142 self.print_symbol(a.asm, a.asm_str_style);
2143 self.word_space(":");
2145 self.commasep(Inconsistent, &a.outputs, |s, out| {
2146 let constraint = out.constraint.as_str();
2147 let mut ch = constraint.chars();
2149 Some('=') if out.is_rw => {
2150 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2152 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2155 s.print_expr(&out.expr);
2159 self.word_space(":");
2161 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2162 s.print_symbol(co, ast::StrStyle::Cooked);
2168 self.word_space(":");
2170 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2171 s.print_symbol(co, ast::StrStyle::Cooked);
2174 let mut options = vec![];
2176 options.push("volatile");
2179 options.push("alignstack");
2181 if a.dialect == ast::LlvmAsmDialect::Intel {
2182 options.push("intel");
2185 if !options.is_empty() {
2187 self.word_space(":");
2188 self.commasep(Inconsistent, &options, |s, &co| {
2189 s.print_string(co, ast::StrStyle::Cooked);
2195 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2196 ast::ExprKind::Paren(ref e) => {
2201 ast::ExprKind::Yield(ref e) => {
2202 self.s.word("yield");
2204 if let Some(ref expr) = *e {
2206 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2209 ast::ExprKind::Try(ref e) => {
2210 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2213 ast::ExprKind::TryBlock(ref blk) => {
2216 self.print_block_with_attrs(blk, attrs)
2218 ast::ExprKind::Err => {
2220 self.s.word("/*ERROR*/");
2224 self.ann.post(self, AnnNode::Expr(expr));
2228 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2231 Operand(&'a InlineAsmOperand),
2233 Options(InlineAsmOptions),
2236 let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2237 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2238 for (abi, _) in &asm.clobber_abis {
2239 args.push(AsmArg::ClobberAbi(*abi));
2241 if !asm.options.is_empty() {
2242 args.push(AsmArg::Options(asm.options));
2246 self.commasep(Consistent, &args, |s, arg| match arg {
2247 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2248 AsmArg::Operand(op) => {
2249 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2250 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2251 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2254 InlineAsmOperand::In { reg, expr } => {
2257 print_reg_or_class(s, reg);
2262 InlineAsmOperand::Out { reg, late, expr } => {
2263 s.word(if *late { "lateout" } else { "out" });
2265 print_reg_or_class(s, reg);
2269 Some(expr) => s.print_expr(expr),
2270 None => s.word("_"),
2273 InlineAsmOperand::InOut { reg, late, expr } => {
2274 s.word(if *late { "inlateout" } else { "inout" });
2276 print_reg_or_class(s, reg);
2281 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2282 s.word(if *late { "inlateout" } else { "inout" });
2284 print_reg_or_class(s, reg);
2287 s.print_expr(in_expr);
2291 Some(out_expr) => s.print_expr(out_expr),
2292 None => s.word("_"),
2295 InlineAsmOperand::Const { anon_const } => {
2298 s.print_expr(&anon_const.value);
2300 InlineAsmOperand::Sym { expr } => {
2307 AsmArg::ClobberAbi(abi) => {
2308 s.word("clobber_abi");
2310 s.print_symbol(*abi, ast::StrStyle::Cooked);
2313 AsmArg::Options(opts) => {
2316 let mut options = vec![];
2317 if opts.contains(InlineAsmOptions::PURE) {
2318 options.push("pure");
2320 if opts.contains(InlineAsmOptions::NOMEM) {
2321 options.push("nomem");
2323 if opts.contains(InlineAsmOptions::READONLY) {
2324 options.push("readonly");
2326 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2327 options.push("preserves_flags");
2329 if opts.contains(InlineAsmOptions::NORETURN) {
2330 options.push("noreturn");
2332 if opts.contains(InlineAsmOptions::NOSTACK) {
2333 options.push("nostack");
2335 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2336 options.push("att_syntax");
2338 if opts.contains(InlineAsmOptions::RAW) {
2339 options.push("raw");
2341 s.commasep(Inconsistent, &options, |s, &opt| {
2350 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2351 self.print_pat(&loc.pat);
2352 if let Some(ref ty) = loc.ty {
2353 self.word_space(":");
2354 self.print_type(ty);
2358 crate fn print_name(&mut self, name: Symbol) {
2359 self.s.word(name.to_string());
2360 self.ann.post(self, AnnNode::Name(&name))
2363 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2365 self.print_type(&qself.ty);
2366 if qself.position > 0 {
2368 self.word_space("as");
2369 let depth = path.segments.len() - qself.position;
2370 self.print_path(path, false, depth);
2373 for item_segment in &path.segments[qself.position..] {
2375 self.print_ident(item_segment.ident);
2376 if let Some(ref args) = item_segment.args {
2377 self.print_generic_args(args, colons_before_params)
2382 crate fn print_pat(&mut self, pat: &ast::Pat) {
2383 self.maybe_print_comment(pat.span.lo());
2384 self.ann.pre(self, AnnNode::Pat(pat));
2385 /* Pat isn't normalized, but the beauty of it
2386 is that it doesn't matter */
2388 PatKind::Wild => self.s.word("_"),
2389 PatKind::Ident(binding_mode, ident, ref sub) => {
2390 match binding_mode {
2391 ast::BindingMode::ByRef(mutbl) => {
2392 self.word_nbsp("ref");
2393 self.print_mutability(mutbl, false);
2395 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2396 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2397 self.word_nbsp("mut");
2400 self.print_ident(ident);
2401 if let Some(ref p) = *sub {
2403 self.s.word_space("@");
2407 PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2408 if let Some(qself) = qself {
2409 self.print_qpath(path, qself, true);
2411 self.print_path(path, true, 0);
2414 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2417 PatKind::Or(ref pats) => {
2418 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2420 PatKind::Path(None, ref path) => {
2421 self.print_path(path, true, 0);
2423 PatKind::Path(Some(ref qself), ref path) => {
2424 self.print_qpath(path, qself, false);
2426 PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2427 if let Some(qself) = qself {
2428 self.print_qpath(path, qself, true);
2430 self.print_path(path, true, 0);
2433 self.word_space("{");
2438 s.cbox(INDENT_UNIT);
2439 if !f.is_shorthand {
2440 s.print_ident(f.ident);
2443 s.print_pat(&f.pat);
2449 if !fields.is_empty() {
2450 self.word_space(",");
2457 PatKind::Tuple(ref elts) => {
2459 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2460 if elts.len() == 1 {
2465 PatKind::Box(ref inner) => {
2466 self.s.word("box ");
2467 self.print_pat(inner);
2469 PatKind::Ref(ref inner, mutbl) => {
2471 if mutbl == ast::Mutability::Mut {
2472 self.s.word("mut ");
2474 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2478 self.print_pat(inner);
2481 self.print_pat(inner);
2484 PatKind::Lit(ref e) => self.print_expr(&**e),
2485 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2486 if let Some(e) = begin {
2491 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2492 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2493 RangeEnd::Excluded => self.s.word(".."),
2495 if let Some(e) = end {
2499 PatKind::Slice(ref elts) => {
2501 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2504 PatKind::Rest => self.s.word(".."),
2505 PatKind::Paren(ref inner) => {
2507 self.print_pat(inner);
2510 PatKind::MacCall(ref m) => self.print_mac(m),
2512 self.ann.post(self, AnnNode::Pat(pat))
2515 fn print_arm(&mut self, arm: &ast::Arm) {
2516 // Note, I have no idea why this check is necessary, but here it is.
2517 if arm.attrs.is_empty() {
2520 self.cbox(INDENT_UNIT);
2522 self.maybe_print_comment(arm.pat.span.lo());
2523 self.print_outer_attributes(&arm.attrs);
2524 self.print_pat(&arm.pat);
2526 if let Some(ref e) = arm.guard {
2527 self.word_space("if");
2531 self.word_space("=>");
2533 match arm.body.kind {
2534 ast::ExprKind::Block(ref blk, opt_label) => {
2535 if let Some(label) = opt_label {
2536 self.print_ident(label.ident);
2537 self.word_space(":");
2540 // The block will close the pattern's ibox.
2541 self.print_block_unclosed_indent(blk);
2543 // If it is a user-provided unsafe block, print a comma after it.
2544 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2549 self.end(); // Close the ibox for the pattern.
2550 self.print_expr(&arm.body);
2554 self.end(); // Close enclosing cbox.
2557 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2558 match explicit_self.node {
2559 SelfKind::Value(m) => {
2560 self.print_mutability(m, false);
2563 SelfKind::Region(ref lt, m) => {
2565 self.print_opt_lifetime(lt);
2566 self.print_mutability(m, false);
2569 SelfKind::Explicit(ref typ, m) => {
2570 self.print_mutability(m, false);
2571 self.s.word("self");
2572 self.word_space(":");
2573 self.print_type(typ)
2582 generics: &ast::Generics,
2583 vis: &ast::Visibility,
2584 defaultness: ast::Defaultness,
2585 body: Option<&ast::Block>,
2586 attrs: &[ast::Attribute],
2591 self.print_visibility(vis);
2592 self.print_defaultness(defaultness);
2593 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2594 if let Some(body) = body {
2596 self.print_block_with_attrs(body, attrs);
2605 header: ast::FnHeader,
2606 name: Option<Ident>,
2607 generics: &ast::Generics,
2609 self.print_fn_header_info(header);
2610 if let Some(name) = name {
2612 self.print_ident(name);
2614 self.print_generic_params(&generics.params);
2615 self.print_fn_params_and_ret(decl, false);
2616 self.print_where_clause(&generics.where_clause)
2619 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2620 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2622 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2624 self.print_fn_ret_ty(&decl.output)
2627 crate fn print_movability(&mut self, movability: ast::Movability) {
2629 ast::Movability::Static => self.word_space("static"),
2630 ast::Movability::Movable => {}
2634 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2635 if asyncness.is_async() {
2636 self.word_nbsp("async");
2640 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2641 match capture_clause {
2642 ast::CaptureBy::Value => self.word_space("move"),
2643 ast::CaptureBy::Ref => {}
2647 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2648 if !bounds.is_empty() {
2649 self.s.word(prefix);
2650 let mut first = true;
2651 for bound in bounds {
2652 if !(first && prefix.is_empty()) {
2658 self.word_space("+");
2662 GenericBound::Trait(tref, modifier) => {
2663 if modifier == &TraitBoundModifier::Maybe {
2666 self.print_poly_trait_ref(tref);
2668 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2674 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2675 self.print_name(lifetime.ident.name)
2678 crate fn print_lifetime_bounds(
2680 lifetime: ast::Lifetime,
2681 bounds: &ast::GenericBounds,
2683 self.print_lifetime(lifetime);
2684 if !bounds.is_empty() {
2686 for (i, bound) in bounds.iter().enumerate() {
2691 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2698 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2699 if generic_params.is_empty() {
2705 self.commasep(Inconsistent, &generic_params, |s, param| {
2706 s.print_outer_attributes_inline(¶m.attrs);
2709 ast::GenericParamKind::Lifetime => {
2710 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2711 s.print_lifetime_bounds(lt, ¶m.bounds)
2713 ast::GenericParamKind::Type { ref default } => {
2714 s.print_ident(param.ident);
2715 s.print_type_bounds(":", ¶m.bounds);
2716 if let Some(ref default) = default {
2719 s.print_type(default)
2722 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2723 s.word_space("const");
2724 s.print_ident(param.ident);
2728 s.print_type_bounds(":", ¶m.bounds);
2729 if let Some(ref default) = default {
2732 s.print_expr(&default.value);
2741 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2742 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2747 self.word_space("where");
2749 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2751 self.word_space(",");
2755 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2756 ref bound_generic_params,
2761 self.print_formal_generic_params(bound_generic_params);
2762 self.print_type(bounded_ty);
2763 self.print_type_bounds(":", bounds);
2765 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2770 self.print_lifetime_bounds(*lifetime, bounds);
2772 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2777 self.print_type(lhs_ty);
2779 self.word_space("=");
2780 self.print_type(rhs_ty);
2786 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2788 ast::UseTreeKind::Simple(rename, ..) => {
2789 self.print_path(&tree.prefix, false, 0);
2790 if let Some(rename) = rename {
2792 self.word_space("as");
2793 self.print_ident(rename);
2796 ast::UseTreeKind::Glob => {
2797 if !tree.prefix.segments.is_empty() {
2798 self.print_path(&tree.prefix, false, 0);
2803 ast::UseTreeKind::Nested(ref items) => {
2804 if tree.prefix.segments.is_empty() {
2807 self.print_path(&tree.prefix, false, 0);
2810 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2811 this.print_use_tree(tree)
2818 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2820 ast::Mutability::Mut => self.word_nbsp("mut"),
2821 ast::Mutability::Not => {
2823 self.word_nbsp("const");
2829 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2830 self.print_mutability(mt.mutbl, print_const);
2831 self.print_type(&mt.ty)
2834 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2835 self.ibox(INDENT_UNIT);
2837 self.print_outer_attributes_inline(&input.attrs);
2839 match input.ty.kind {
2840 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2842 if let Some(eself) = input.to_self() {
2843 self.print_explicit_self(&eself);
2845 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2846 ident.name == kw::Empty
2851 self.print_pat(&input.pat);
2855 self.print_type(&input.ty);
2862 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2863 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2864 self.space_if_not_bol();
2865 self.ibox(INDENT_UNIT);
2866 self.word_space("->");
2867 self.print_type(ty);
2869 self.maybe_print_comment(ty.span.lo());
2873 crate fn print_ty_fn(
2876 unsafety: ast::Unsafe,
2878 name: Option<Ident>,
2879 generic_params: &[ast::GenericParam],
2881 self.ibox(INDENT_UNIT);
2882 if !generic_params.is_empty() {
2884 self.print_generic_params(generic_params);
2886 let generics = ast::Generics {
2888 where_clause: ast::WhereClause {
2889 has_where_token: false,
2890 predicates: Vec::new(),
2891 span: rustc_span::DUMMY_SP,
2893 span: rustc_span::DUMMY_SP,
2895 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2896 self.print_fn(decl, header, name, &generics);
2900 crate fn maybe_print_trailing_comment(
2902 span: rustc_span::Span,
2903 next_pos: Option<BytePos>,
2905 if let Some(cmnts) = self.comments() {
2906 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2907 self.print_comment(&cmnt);
2912 crate fn print_remaining_comments(&mut self) {
2913 // If there aren't any remaining comments, then we need to manually
2914 // make sure there is a line break at the end.
2915 if self.next_comment().is_none() {
2918 while let Some(ref cmnt) = self.next_comment() {
2919 self.print_comment(cmnt);
2923 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2924 self.print_constness(header.constness);
2925 self.print_asyncness(header.asyncness);
2926 self.print_unsafety(header.unsafety);
2929 ast::Extern::None => {}
2930 ast::Extern::Implicit => {
2931 self.word_nbsp("extern");
2933 ast::Extern::Explicit(abi) => {
2934 self.word_nbsp("extern");
2935 self.print_literal(&abi.as_lit());
2943 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2945 ast::Unsafe::No => {}
2946 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2950 crate fn print_constness(&mut self, s: ast::Const) {
2952 ast::Const::No => {}
2953 ast::Const::Yes(_) => self.word_nbsp("const"),
2957 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2959 ast::IsAuto::Yes => self.word_nbsp("auto"),
2960 ast::IsAuto::No => {}