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};
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),
91 // If `true`, additional parenthesis (separate from `ExprKind::Paren`)
92 // are inserted to ensure that proper precedence is preserved
93 // in the pretty-printed output.
95 // This is usually `true`, except when performing the pretty-print/reparse
96 // check in `nt_to_tokenstream`
97 insert_extra_parens: bool,
100 crate const INDENT_UNIT: usize = 4;
102 /// Requires you to pass an input filename and reader so that
103 /// it can scan the input text for comments to copy forward.
104 pub fn print_crate<'a>(
112 has_injected_crate: bool,
116 comments: Some(Comments::new(sm, filename, input)),
119 insert_extra_parens: true,
122 if is_expanded && has_injected_crate {
123 // We need to print `#![no_std]` (and its feature gate) so that
124 // compiling pretty-printed source won't inject libstd again.
125 // However, we don't want these attributes in the AST because
126 // of the feature gate, so we fake them up here.
128 // `#![feature(prelude_import)]`
129 let pi_nested = attr::mk_nested_word_item(Ident::with_dummy_span(sym::prelude_import));
130 let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), vec![pi_nested]);
131 let fake_attr = attr::mk_attr_inner(list);
132 s.print_attribute(&fake_attr);
134 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
135 // root, so this is not needed, and actually breaks things.
136 if edition == Edition::Edition2015 {
138 let no_std_meta = attr::mk_word_item(Ident::with_dummy_span(sym::no_std));
139 let fake_attr = attr::mk_attr_inner(no_std_meta);
140 s.print_attribute(&fake_attr);
144 s.print_mod(&krate.module, &krate.attrs);
145 s.print_remaining_comments();
146 s.ann.post(&mut s, AnnNode::Crate(krate));
150 // This makes printed token streams look slightly nicer,
151 // and also addresses some specific regressions described in #63896 and #73345.
152 fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool {
153 if let TokenTree::Token(token) = prev {
154 if let token::DocComment(comment_kind, ..) = token.kind {
155 return comment_kind != CommentKind::Line;
159 TokenTree::Token(token) => token.kind != token::Comma,
160 TokenTree::Delimited(_, DelimToken::Paren, _) => {
161 !matches!(prev, TokenTree::Token(Token { kind: token::Ident(..), .. }))
163 TokenTree::Delimited(_, DelimToken::Bracket, _) => {
164 !matches!(prev, TokenTree::Token(Token { kind: token::Pound, .. }))
166 TokenTree::Delimited(..) => true,
170 fn binop_to_string(op: BinOpToken) -> &'static str {
176 token::Percent => "%",
185 fn doc_comment_to_string(
186 comment_kind: CommentKind,
187 attr_style: ast::AttrStyle,
190 match (comment_kind, attr_style) {
191 (CommentKind::Line, ast::AttrStyle::Outer) => format!("///{}", data),
192 (CommentKind::Line, ast::AttrStyle::Inner) => format!("//!{}", data),
193 (CommentKind::Block, ast::AttrStyle::Outer) => format!("/**{}*/", data),
194 (CommentKind::Block, ast::AttrStyle::Inner) => format!("/*!{}*/", data),
198 pub fn literal_to_string(lit: token::Lit) -> String {
199 let token::Lit { kind, symbol, suffix } = lit;
200 let mut out = match kind {
201 token::Byte => format!("b'{}'", symbol),
202 token::Char => format!("'{}'", symbol),
203 token::Str => format!("\"{}\"", symbol),
204 token::StrRaw(n) => {
205 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
207 token::ByteStr => format!("b\"{}\"", symbol),
208 token::ByteStrRaw(n) => {
209 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
211 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
214 if let Some(suffix) = suffix {
215 out.push_str(&suffix.as_str())
221 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
222 format!("{}{}", State::new().to_string(|s| s.print_visibility(vis)), s)
225 impl std::ops::Deref for State<'_> {
226 type Target = pp::Printer;
227 fn deref(&self) -> &Self::Target {
232 impl std::ops::DerefMut for State<'_> {
233 fn deref_mut(&mut self) -> &mut Self::Target {
238 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
239 fn insert_extra_parens(&self) -> bool;
240 fn comments(&mut self) -> &mut Option<Comments<'a>>;
241 fn print_ident(&mut self, ident: Ident);
242 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
252 F: FnMut(&mut Self, &T),
255 if let Some((first, rest)) = elts.split_first() {
261 self.word_space(sep);
268 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
270 F: FnMut(&mut Self, &T),
272 self.strsep(",", false, b, elts, op)
275 fn maybe_print_comment(&mut self, pos: BytePos) {
276 while let Some(ref cmnt) = self.next_comment() {
278 self.print_comment(cmnt);
285 fn print_comment(&mut self, cmnt: &Comment) {
287 CommentStyle::Mixed => {
288 if !self.is_beginning_of_line() {
291 if let Some((last, lines)) = cmnt.lines.split_last() {
295 self.word(line.clone());
299 self.word(last.clone());
306 CommentStyle::Isolated => {
307 self.hardbreak_if_not_bol();
308 for line in &cmnt.lines {
309 // Don't print empty lines because they will end up as trailing
311 if !line.is_empty() {
312 self.word(line.clone());
317 CommentStyle::Trailing => {
318 if !self.is_beginning_of_line() {
321 if cmnt.lines.len() == 1 {
322 self.word(cmnt.lines[0].clone());
326 for line in &cmnt.lines {
327 if !line.is_empty() {
328 self.word(line.clone());
335 CommentStyle::BlankLine => {
336 // We need to do at least one, possibly two hardbreaks.
337 let twice = match self.last_token() {
338 pp::Token::String(s) => ";" == s,
339 pp::Token::Begin(_) => true,
340 pp::Token::End => true,
349 if let Some(cmnts) = self.comments() {
354 fn next_comment(&mut self) -> Option<Comment> {
355 self.comments().as_mut().and_then(|c| c.next())
358 fn print_literal(&mut self, lit: &ast::Lit) {
359 self.maybe_print_comment(lit.span.lo());
360 self.word(lit.token.to_string())
363 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
364 let st = match style {
365 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
366 ast::StrStyle::Raw(n) => {
367 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
373 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
374 self.print_string(&sym.as_str(), style);
377 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
378 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
381 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
382 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
385 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
386 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
389 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
390 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
393 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
394 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
397 fn print_either_attributes(
399 attrs: &[ast::Attribute],
400 kind: ast::AttrStyle,
402 trailing_hardbreak: bool,
406 if attr.style == kind {
407 self.print_attribute_inline(attr, is_inline);
414 if count > 0 && trailing_hardbreak && !is_inline {
415 self.hardbreak_if_not_bol();
419 fn print_attribute(&mut self, attr: &ast::Attribute) {
420 self.print_attribute_inline(attr, false)
423 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
425 self.hardbreak_if_not_bol();
427 self.maybe_print_comment(attr.span.lo());
429 ast::AttrKind::Normal(ref item, _) => {
431 ast::AttrStyle::Inner => self.word("#!["),
432 ast::AttrStyle::Outer => self.word("#["),
434 self.print_attr_item(&item, attr.span);
437 ast::AttrKind::DocComment(comment_kind, data) => {
438 self.word(doc_comment_to_string(comment_kind, attr.style, data));
444 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
447 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
448 Some(MacHeader::Path(&item.path)),
456 MacArgs::Empty | MacArgs::Eq(..) => {
457 self.print_path(&item.path, false, 0);
458 if let MacArgs::Eq(_, tokens) = &item.args {
460 self.word_space("=");
461 self.print_tts(tokens, true);
468 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
470 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
471 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
475 fn print_meta_item(&mut self, item: &ast::MetaItem) {
476 self.ibox(INDENT_UNIT);
478 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
479 ast::MetaItemKind::NameValue(ref value) => {
480 self.print_path(&item.path, false, 0);
482 self.word_space("=");
483 self.print_literal(value);
485 ast::MetaItemKind::List(ref items) => {
486 self.print_path(&item.path, false, 0);
488 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
495 /// This doesn't deserve to be called "pretty" printing, but it should be
496 /// meaning-preserving. A quick hack that might help would be to look at the
497 /// spans embedded in the TTs to decide where to put spaces and newlines.
498 /// But it'd be better to parse these according to the grammar of the
499 /// appropriate macro, transcribe back into the grammar we just parsed from,
500 /// and then pretty-print the resulting AST nodes (so, e.g., we print
501 /// expression arguments as expressions). It can be done! I think.
502 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
504 TokenTree::Token(token) => {
505 let token_str = self.token_to_string_ext(&token, convert_dollar_crate);
506 self.word(token_str);
507 if let token::DocComment(..) = token.kind {
511 TokenTree::Delimited(dspan, delim, tts) => {
512 self.print_mac_common(
518 convert_dollar_crate,
525 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
526 let mut iter = tts.trees().peekable();
527 while let Some(tt) = iter.next() {
528 self.print_tt(&tt, convert_dollar_crate);
529 if let Some(next) = iter.peek() {
530 if tt_prepend_space(next, &tt) {
539 header: Option<MacHeader<'_>>,
541 ident: Option<Ident>,
544 convert_dollar_crate: bool,
547 if delim == DelimToken::Brace {
548 self.cbox(INDENT_UNIT);
551 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
552 Some(MacHeader::Keyword(kw)) => self.word(kw),
558 if let Some(ident) = ident {
560 self.print_ident(ident);
563 DelimToken::Brace => {
564 if header.is_some() || has_bang || ident.is_some() {
573 let token_str = self.token_kind_to_string(&token::OpenDelim(delim));
578 self.print_tts(tts, convert_dollar_crate);
581 DelimToken::Brace => self.bclose(span),
583 let token_str = self.token_kind_to_string(&token::CloseDelim(delim));
589 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
590 self.maybe_print_comment(path.span.lo());
592 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
596 self.print_path_segment(segment, colons_before_params);
600 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
601 if segment.ident.name != kw::PathRoot {
602 self.print_ident(segment.ident);
603 if let Some(ref args) = segment.args {
604 self.print_generic_args(args, colons_before_params);
609 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
611 // Outer-box is consistent.
612 self.cbox(INDENT_UNIT);
613 // Head-box is inconsistent.
614 self.ibox(w.len() + 1);
615 // Keyword that starts the head.
621 fn bopen(&mut self) {
623 self.end(); // Close the head-box.
626 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
627 self.maybe_print_comment(span.hi());
628 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
631 self.end(); // Close the outer-box.
635 fn bclose(&mut self, span: rustc_span::Span) {
636 self.bclose_maybe_open(span, true)
639 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
640 if !self.is_beginning_of_line() {
641 self.break_offset(n, off)
642 } else if off != 0 && self.last_token().is_hardbreak_tok() {
643 // We do something pretty sketchy here: tuck the nonzero
644 // offset-adjustment we were going to deposit along with the
645 // break into the previous hardbreak.
646 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
650 fn nonterminal_to_string(&self, nt: &Nonterminal) -> String {
652 token::NtExpr(ref e) => self.expr_to_string(e),
653 token::NtMeta(ref e) => self.attr_item_to_string(e),
654 token::NtTy(ref e) => self.ty_to_string(e),
655 token::NtPath(ref e) => self.path_to_string(e),
656 token::NtItem(ref e) => self.item_to_string(e),
657 token::NtBlock(ref e) => self.block_to_string(e),
658 token::NtStmt(ref e) => self.stmt_to_string(e),
659 token::NtPat(ref e) => self.pat_to_string(e),
660 token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(),
661 token::NtLifetime(e) => e.to_string(),
662 token::NtLiteral(ref e) => self.expr_to_string(e),
663 token::NtTT(ref tree) => self.tt_to_string(tree),
664 token::NtVis(ref e) => self.vis_to_string(e),
668 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
669 fn token_kind_to_string(&self, tok: &TokenKind) -> String {
670 self.token_kind_to_string_ext(tok, None)
673 fn token_kind_to_string_ext(
676 convert_dollar_crate: Option<Span>,
679 token::Eq => "=".to_string(),
680 token::Lt => "<".to_string(),
681 token::Le => "<=".to_string(),
682 token::EqEq => "==".to_string(),
683 token::Ne => "!=".to_string(),
684 token::Ge => ">=".to_string(),
685 token::Gt => ">".to_string(),
686 token::Not => "!".to_string(),
687 token::Tilde => "~".to_string(),
688 token::OrOr => "||".to_string(),
689 token::AndAnd => "&&".to_string(),
690 token::BinOp(op) => binop_to_string(op).to_string(),
691 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
693 /* Structural symbols */
694 token::At => "@".to_string(),
695 token::Dot => ".".to_string(),
696 token::DotDot => "..".to_string(),
697 token::DotDotDot => "...".to_string(),
698 token::DotDotEq => "..=".to_string(),
699 token::Comma => ",".to_string(),
700 token::Semi => ";".to_string(),
701 token::Colon => ":".to_string(),
702 token::ModSep => "::".to_string(),
703 token::RArrow => "->".to_string(),
704 token::LArrow => "<-".to_string(),
705 token::FatArrow => "=>".to_string(),
706 token::OpenDelim(token::Paren) => "(".to_string(),
707 token::CloseDelim(token::Paren) => ")".to_string(),
708 token::OpenDelim(token::Bracket) => "[".to_string(),
709 token::CloseDelim(token::Bracket) => "]".to_string(),
710 token::OpenDelim(token::Brace) => "{".to_string(),
711 token::CloseDelim(token::Brace) => "}".to_string(),
712 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => "".to_string(),
713 token::Pound => "#".to_string(),
714 token::Dollar => "$".to_string(),
715 token::Question => "?".to_string(),
716 token::SingleQuote => "'".to_string(),
719 token::Literal(lit) => literal_to_string(lit),
721 /* Name components */
722 token::Ident(s, is_raw) => {
723 IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string()
725 token::Lifetime(s) => s.to_string(),
728 token::DocComment(comment_kind, attr_style, data) => {
729 doc_comment_to_string(comment_kind, attr_style, data)
731 token::Eof => "<eof>".to_string(),
733 token::Interpolated(ref nt) => self.nonterminal_to_string(nt),
737 /// Print the token precisely, without converting `$crate` into its respective crate name.
738 fn token_to_string(&self, token: &Token) -> String {
739 self.token_to_string_ext(token, false)
742 fn token_to_string_ext(&self, token: &Token, convert_dollar_crate: bool) -> String {
743 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
744 self.token_kind_to_string_ext(&token.kind, convert_dollar_crate)
747 fn ty_to_string(&self, ty: &ast::Ty) -> String {
748 self.to_string(|s| s.print_type(ty))
751 fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String {
752 self.to_string(|s| s.print_type_bounds("", bounds))
755 fn pat_to_string(&self, pat: &ast::Pat) -> String {
756 self.to_string(|s| s.print_pat(pat))
759 fn expr_to_string(&self, e: &ast::Expr) -> String {
760 self.to_string(|s| s.print_expr(e))
763 fn tt_to_string(&self, tt: &TokenTree) -> String {
764 self.to_string(|s| s.print_tt(tt, false))
767 fn tts_to_string(&self, tokens: &TokenStream) -> String {
768 self.to_string(|s| s.print_tts(tokens, false))
771 fn stmt_to_string(&self, stmt: &ast::Stmt) -> String {
772 self.to_string(|s| s.print_stmt(stmt))
775 fn item_to_string(&self, i: &ast::Item) -> String {
776 self.to_string(|s| s.print_item(i))
779 fn generic_params_to_string(&self, generic_params: &[ast::GenericParam]) -> String {
780 self.to_string(|s| s.print_generic_params(generic_params))
783 fn path_to_string(&self, p: &ast::Path) -> String {
784 self.to_string(|s| s.print_path(p, false, 0))
787 fn path_segment_to_string(&self, p: &ast::PathSegment) -> String {
788 self.to_string(|s| s.print_path_segment(p, false))
791 fn vis_to_string(&self, v: &ast::Visibility) -> String {
792 self.to_string(|s| s.print_visibility(v))
795 fn block_to_string(&self, blk: &ast::Block) -> String {
797 // Containing cbox, will be closed by `print_block` at `}`.
799 // Head-ibox, will be closed by `print_block` after `{`.
805 fn meta_list_item_to_string(&self, li: &ast::NestedMetaItem) -> String {
806 self.to_string(|s| s.print_meta_list_item(li))
809 fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String {
810 self.to_string(|s| s.print_attr_item(ai, ai.path.span))
813 fn attribute_to_string(&self, attr: &ast::Attribute) -> String {
814 self.to_string(|s| s.print_attribute(attr))
817 fn param_to_string(&self, arg: &ast::Param) -> String {
818 self.to_string(|s| s.print_param(arg, false))
821 fn to_string(&self, f: impl FnOnce(&mut State<'_>)) -> String {
822 let mut printer = State::new();
823 printer.insert_extra_parens = self.insert_extra_parens();
829 impl<'a> PrintState<'a> for State<'a> {
830 fn insert_extra_parens(&self) -> bool {
831 self.insert_extra_parens
833 fn comments(&mut self) -> &mut Option<Comments<'a>> {
837 fn print_ident(&mut self, ident: Ident) {
838 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
839 self.ann.post(self, AnnNode::Ident(&ident))
842 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
843 if colons_before_params {
848 ast::GenericArgs::AngleBracketed(ref data) => {
850 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
851 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
852 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
857 ast::GenericArgs::Parenthesized(ref data) => {
859 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
861 self.print_fn_ret_ty(&data.output);
868 pub fn new() -> State<'a> {
874 insert_extra_parens: true,
878 pub(super) fn without_insert_extra_parens() -> State<'a> {
879 State { insert_extra_parens: false, ..State::new() }
882 // Synthesizes a comment that was not textually present in the original source
884 pub fn synth_comment(&mut self, text: String) {
892 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
894 F: FnMut(&mut State<'_>, &T),
895 G: FnMut(&T) -> rustc_span::Span,
898 let len = elts.len();
901 self.maybe_print_comment(get_span(elt).hi());
906 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
907 self.space_if_not_bol();
913 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
914 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
917 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
918 self.print_inner_attributes(attrs);
919 for item in &_mod.items {
920 self.print_item(item);
924 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
925 self.print_inner_attributes(attrs);
926 for item in &nmod.items {
927 self.print_foreign_item(item);
931 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
932 if let Some(lt) = *lifetime {
933 self.print_lifetime(lt);
938 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
939 self.print_ident(constraint.ident);
941 match &constraint.kind {
942 ast::AssocTyConstraintKind::Equality { ty } => {
943 self.word_space("=");
946 ast::AssocTyConstraintKind::Bound { bounds } => {
947 self.print_type_bounds(":", &*bounds);
952 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
954 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
955 GenericArg::Type(ty) => self.print_type(ty),
956 GenericArg::Const(ct) => self.print_expr(&ct.value),
960 pub fn print_type(&mut self, ty: &ast::Ty) {
961 self.maybe_print_comment(ty.span.lo());
964 ast::TyKind::Slice(ref ty) => {
969 ast::TyKind::Ptr(ref mt) => {
971 self.print_mt(mt, true);
973 ast::TyKind::Rptr(ref lifetime, ref mt) => {
975 self.print_opt_lifetime(lifetime);
976 self.print_mt(mt, false);
978 ast::TyKind::Never => {
981 ast::TyKind::Tup(ref elts) => {
983 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
989 ast::TyKind::Paren(ref typ) => {
991 self.print_type(typ);
994 ast::TyKind::BareFn(ref f) => {
995 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
997 ast::TyKind::Path(None, ref path) => {
998 self.print_path(path, false, 0);
1000 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
1001 ast::TyKind::TraitObject(ref bounds, syntax) => {
1002 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1003 self.print_type_bounds(prefix, &bounds[..]);
1005 ast::TyKind::ImplTrait(_, ref bounds) => {
1006 self.print_type_bounds("impl", &bounds[..]);
1008 ast::TyKind::Array(ref ty, ref length) => {
1010 self.print_type(ty);
1012 self.print_expr(&length.value);
1015 ast::TyKind::Typeof(ref e) => {
1016 self.s.word("typeof(");
1017 self.print_expr(&e.value);
1020 ast::TyKind::Infer => {
1023 ast::TyKind::Err => {
1025 self.s.word("/*ERROR*/");
1028 ast::TyKind::ImplicitSelf => {
1029 self.s.word("Self");
1031 ast::TyKind::MacCall(ref m) => {
1034 ast::TyKind::CVarArgs => {
1041 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1042 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1043 self.ann.pre(self, AnnNode::SubItem(id));
1044 self.hardbreak_if_not_bol();
1045 self.maybe_print_comment(span.lo());
1046 self.print_outer_attributes(attrs);
1048 ast::ForeignItemKind::Fn(def, sig, gen, body) => {
1049 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1051 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1052 let def = ast::Defaultness::Final;
1053 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1055 ast::ForeignItemKind::TyAlias(def, generics, bounds, ty) => {
1056 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1058 ast::ForeignItemKind::MacCall(m) => {
1060 if m.args.need_semicolon() {
1065 self.ann.post(self, AnnNode::SubItem(id))
1068 fn print_item_const(
1071 mutbl: Option<ast::Mutability>,
1073 body: Option<&ast::Expr>,
1074 vis: &ast::Visibility,
1075 defaultness: ast::Defaultness,
1078 self.print_visibility(vis);
1079 self.print_defaultness(defaultness);
1080 let leading = match mutbl {
1082 Some(ast::Mutability::Not) => "static",
1083 Some(ast::Mutability::Mut) => "static mut",
1085 self.word_space(leading);
1086 self.print_ident(ident);
1087 self.word_space(":");
1088 self.print_type(ty);
1090 self.end(); // end the head-ibox
1091 if let Some(body) = body {
1092 self.word_space("=");
1093 self.print_expr(body);
1096 self.end(); // end the outer cbox
1099 fn print_associated_type(
1102 generics: &ast::Generics,
1103 bounds: &ast::GenericBounds,
1104 ty: Option<&ast::Ty>,
1105 vis: &ast::Visibility,
1106 defaultness: ast::Defaultness,
1109 self.print_visibility(vis);
1110 self.print_defaultness(defaultness);
1111 self.word_space("type");
1112 self.print_ident(ident);
1113 self.print_generic_params(&generics.params);
1114 self.print_type_bounds(":", bounds);
1115 self.print_where_clause(&generics.where_clause);
1116 if let Some(ty) = ty {
1118 self.word_space("=");
1119 self.print_type(ty);
1122 self.end(); // end inner head-block
1123 self.end(); // end outer head-block
1126 /// Pretty-prints an item.
1127 crate fn print_item(&mut self, item: &ast::Item) {
1128 self.hardbreak_if_not_bol();
1129 self.maybe_print_comment(item.span.lo());
1130 self.print_outer_attributes(&item.attrs);
1131 self.ann.pre(self, AnnNode::Item(item));
1133 ast::ItemKind::ExternCrate(orig_name) => {
1134 self.head(visibility_qualified(&item.vis, "extern crate"));
1135 if let Some(orig_name) = orig_name {
1136 self.print_name(orig_name);
1141 self.print_ident(item.ident);
1143 self.end(); // end inner head-block
1144 self.end(); // end outer head-block
1146 ast::ItemKind::Use(ref tree) => {
1147 self.head(visibility_qualified(&item.vis, "use"));
1148 self.print_use_tree(tree);
1150 self.end(); // end inner head-block
1151 self.end(); // end outer head-block
1153 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1154 let def = ast::Defaultness::Final;
1155 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1157 ast::ItemKind::Const(def, ref ty, ref body) => {
1158 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1160 ast::ItemKind::Fn(def, ref sig, ref gen, ref body) => {
1161 let body = body.as_deref();
1162 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1164 ast::ItemKind::Mod(ref _mod) => {
1165 self.head(self.to_string(|s| {
1166 s.print_visibility(&item.vis);
1167 s.print_unsafety(_mod.unsafety);
1170 self.print_ident(item.ident);
1172 if _mod.inline || self.is_expanded {
1175 self.print_mod(_mod, &item.attrs);
1176 self.bclose(item.span);
1179 self.end(); // end inner head-block
1180 self.end(); // end outer head-block
1183 ast::ItemKind::ForeignMod(ref nmod) => {
1184 self.head(self.to_string(|s| {
1185 s.print_unsafety(nmod.unsafety);
1188 if let Some(abi) = nmod.abi {
1189 self.print_literal(&abi.as_lit());
1193 self.print_foreign_mod(nmod, &item.attrs);
1194 self.bclose(item.span);
1196 ast::ItemKind::GlobalAsm(ref ga) => {
1197 self.head(visibility_qualified(&item.vis, "global_asm!"));
1198 self.s.word(ga.asm.to_string());
1201 ast::ItemKind::TyAlias(def, ref generics, ref bounds, ref ty) => {
1202 let ty = ty.as_deref();
1203 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1205 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1206 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1208 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1209 self.head(visibility_qualified(&item.vis, "struct"));
1210 self.print_struct(struct_def, generics, item.ident, item.span, true);
1212 ast::ItemKind::Union(ref struct_def, ref generics) => {
1213 self.head(visibility_qualified(&item.vis, "union"));
1214 self.print_struct(struct_def, generics, item.ident, item.span, true);
1216 ast::ItemKind::Impl {
1227 self.print_visibility(&item.vis);
1228 self.print_defaultness(defaultness);
1229 self.print_unsafety(unsafety);
1230 self.word_nbsp("impl");
1231 self.print_constness(constness);
1233 if !generics.params.is_empty() {
1234 self.print_generic_params(&generics.params);
1238 if let ast::ImplPolarity::Negative(_) = polarity {
1242 if let Some(ref t) = *of_trait {
1243 self.print_trait_ref(t);
1245 self.word_space("for");
1248 self.print_type(self_ty);
1249 self.print_where_clause(&generics.where_clause);
1253 self.print_inner_attributes(&item.attrs);
1254 for impl_item in items {
1255 self.print_assoc_item(impl_item);
1257 self.bclose(item.span);
1259 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1261 self.print_visibility(&item.vis);
1262 self.print_unsafety(unsafety);
1263 self.print_is_auto(is_auto);
1264 self.word_nbsp("trait");
1265 self.print_ident(item.ident);
1266 self.print_generic_params(&generics.params);
1267 let mut real_bounds = Vec::with_capacity(bounds.len());
1268 for b in bounds.iter() {
1269 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1271 self.word_space("for ?");
1272 self.print_trait_ref(&ptr.trait_ref);
1274 real_bounds.push(b.clone());
1277 self.print_type_bounds(":", &real_bounds[..]);
1278 self.print_where_clause(&generics.where_clause);
1281 self.print_inner_attributes(&item.attrs);
1282 for trait_item in trait_items {
1283 self.print_assoc_item(trait_item);
1285 self.bclose(item.span);
1287 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1289 self.print_visibility(&item.vis);
1290 self.word_nbsp("trait");
1291 self.print_ident(item.ident);
1292 self.print_generic_params(&generics.params);
1293 let mut real_bounds = Vec::with_capacity(bounds.len());
1294 // FIXME(durka) this seems to be some quite outdated syntax
1295 for b in bounds.iter() {
1296 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1298 self.word_space("for ?");
1299 self.print_trait_ref(&ptr.trait_ref);
1301 real_bounds.push(b.clone());
1305 self.print_type_bounds("=", &real_bounds[..]);
1306 self.print_where_clause(&generics.where_clause);
1309 ast::ItemKind::MacCall(ref mac) => {
1310 self.print_mac(mac);
1311 if mac.args.need_semicolon() {
1315 ast::ItemKind::MacroDef(ref macro_def) => {
1316 let (kw, has_bang) = if macro_def.macro_rules {
1317 ("macro_rules", true)
1319 self.print_visibility(&item.vis);
1322 self.print_mac_common(
1323 Some(MacHeader::Keyword(kw)),
1326 macro_def.body.delim(),
1327 ¯o_def.body.inner_tokens(),
1333 self.ann.post(self, AnnNode::Item(item))
1336 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1337 self.print_path(&t.path, false, 0)
1340 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1341 if !generic_params.is_empty() {
1343 self.print_generic_params(generic_params);
1348 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1349 self.print_formal_generic_params(&t.bound_generic_params);
1350 self.print_trait_ref(&t.trait_ref)
1353 crate fn print_enum_def(
1355 enum_definition: &ast::EnumDef,
1356 generics: &ast::Generics,
1358 span: rustc_span::Span,
1359 visibility: &ast::Visibility,
1361 self.head(visibility_qualified(visibility, "enum"));
1362 self.print_ident(ident);
1363 self.print_generic_params(&generics.params);
1364 self.print_where_clause(&generics.where_clause);
1366 self.print_variants(&enum_definition.variants, span)
1369 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1372 self.space_if_not_bol();
1373 self.maybe_print_comment(v.span.lo());
1374 self.print_outer_attributes(&v.attrs);
1375 self.ibox(INDENT_UNIT);
1376 self.print_variant(v);
1379 self.maybe_print_trailing_comment(v.span, None);
1384 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1386 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1387 ast::VisibilityKind::Crate(sugar) => match sugar {
1388 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1389 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1391 ast::VisibilityKind::Restricted { ref path, .. } => {
1392 let path = self.to_string(|s| s.print_path(path, false, 0));
1393 if path == "self" || path == "super" {
1394 self.word_nbsp(format!("pub({})", path))
1396 self.word_nbsp(format!("pub(in {})", path))
1399 ast::VisibilityKind::Inherited => {}
1403 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1404 if let ast::Defaultness::Default(_) = defaultness {
1405 self.word_nbsp("default");
1409 crate fn print_struct(
1411 struct_def: &ast::VariantData,
1412 generics: &ast::Generics,
1414 span: rustc_span::Span,
1415 print_finalizer: bool,
1417 self.print_ident(ident);
1418 self.print_generic_params(&generics.params);
1420 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1421 if let ast::VariantData::Tuple(..) = struct_def {
1423 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1424 s.maybe_print_comment(field.span.lo());
1425 s.print_outer_attributes(&field.attrs);
1426 s.print_visibility(&field.vis);
1427 s.print_type(&field.ty)
1431 self.print_where_clause(&generics.where_clause);
1432 if print_finalizer {
1436 self.end(); // Close the outer-box.
1438 ast::VariantData::Struct(..) => {
1439 self.print_where_clause(&generics.where_clause);
1442 self.hardbreak_if_not_bol();
1444 for field in struct_def.fields() {
1445 self.hardbreak_if_not_bol();
1446 self.maybe_print_comment(field.span.lo());
1447 self.print_outer_attributes(&field.attrs);
1448 self.print_visibility(&field.vis);
1449 self.print_ident(field.ident.unwrap());
1450 self.word_nbsp(":");
1451 self.print_type(&field.ty);
1460 crate fn print_variant(&mut self, v: &ast::Variant) {
1462 self.print_visibility(&v.vis);
1463 let generics = ast::Generics::default();
1464 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1465 if let Some(ref d) = v.disr_expr {
1467 self.word_space("=");
1468 self.print_expr(&d.value)
1472 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1473 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1474 self.ann.pre(self, AnnNode::SubItem(id));
1475 self.hardbreak_if_not_bol();
1476 self.maybe_print_comment(span.lo());
1477 self.print_outer_attributes(attrs);
1479 ast::AssocItemKind::Fn(def, sig, gen, body) => {
1480 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1482 ast::AssocItemKind::Const(def, ty, body) => {
1483 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1485 ast::AssocItemKind::TyAlias(def, generics, bounds, ty) => {
1486 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1488 ast::AssocItemKind::MacCall(m) => {
1490 if m.args.need_semicolon() {
1495 self.ann.post(self, AnnNode::SubItem(id))
1498 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1499 self.maybe_print_comment(st.span.lo());
1501 ast::StmtKind::Local(ref loc) => {
1502 self.print_outer_attributes(&loc.attrs);
1503 self.space_if_not_bol();
1504 self.ibox(INDENT_UNIT);
1505 self.word_nbsp("let");
1507 self.ibox(INDENT_UNIT);
1508 self.print_local_decl(loc);
1510 if let Some(ref init) = loc.init {
1512 self.word_space("=");
1513 self.print_expr(init);
1518 ast::StmtKind::Item(ref item) => self.print_item(item),
1519 ast::StmtKind::Expr(ref expr) => {
1520 self.space_if_not_bol();
1521 self.print_expr_outer_attr_style(expr, false);
1522 if classify::expr_requires_semi_to_be_stmt(expr) {
1526 ast::StmtKind::Semi(ref expr) => {
1527 self.space_if_not_bol();
1528 self.print_expr_outer_attr_style(expr, false);
1531 ast::StmtKind::Empty => {
1532 self.space_if_not_bol();
1535 ast::StmtKind::MacCall(ref mac) => {
1536 self.space_if_not_bol();
1537 self.print_outer_attributes(&mac.attrs);
1538 self.print_mac(&mac.mac);
1539 if mac.style == ast::MacStmtStyle::Semicolon {
1544 self.maybe_print_trailing_comment(st.span, None)
1547 crate fn print_block(&mut self, blk: &ast::Block) {
1548 self.print_block_with_attrs(blk, &[])
1551 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1552 self.print_block_maybe_unclosed(blk, &[], false)
1555 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1556 self.print_block_maybe_unclosed(blk, attrs, true)
1559 crate fn print_block_maybe_unclosed(
1562 attrs: &[ast::Attribute],
1566 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1567 BlockCheckMode::Default => (),
1569 self.maybe_print_comment(blk.span.lo());
1570 self.ann.pre(self, AnnNode::Block(blk));
1573 self.print_inner_attributes(attrs);
1575 for (i, st) in blk.stmts.iter().enumerate() {
1577 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1578 self.maybe_print_comment(st.span.lo());
1579 self.space_if_not_bol();
1580 self.print_expr_outer_attr_style(expr, false);
1581 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1583 _ => self.print_stmt(st),
1587 self.bclose_maybe_open(blk.span, close_box);
1588 self.ann.post(self, AnnNode::Block(blk))
1591 /// Print a `let pat = scrutinee` expression.
1592 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1593 self.s.word("let ");
1595 self.print_pat(pat);
1598 self.word_space("=");
1599 self.print_expr_cond_paren(
1601 Self::cond_needs_par(scrutinee)
1602 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1606 fn print_else(&mut self, els: Option<&ast::Expr>) {
1607 if let Some(_else) = els {
1609 // Another `else if` block.
1610 ast::ExprKind::If(ref i, ref then, ref e) => {
1611 self.cbox(INDENT_UNIT - 1);
1613 self.s.word(" else if ");
1614 self.print_expr_as_cond(i);
1616 self.print_block(then);
1617 self.print_else(e.as_deref())
1619 // Final `else` block.
1620 ast::ExprKind::Block(ref b, _) => {
1621 self.cbox(INDENT_UNIT - 1);
1623 self.s.word(" else ");
1626 // Constraints would be great here!
1628 panic!("print_if saw if with weird alternative");
1634 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1637 self.print_expr_as_cond(test);
1640 self.print_block(blk);
1641 self.print_else(elseopt)
1644 crate fn print_mac(&mut self, m: &ast::MacCall) {
1645 self.print_mac_common(
1646 Some(MacHeader::Path(&m.path)),
1650 &m.args.inner_tokens(),
1656 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1658 self.commasep_exprs(Inconsistent, args);
1662 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1663 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1666 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1667 /// `if cond { ... }`.
1668 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1669 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1672 /// Does `expr` need parenthesis when printed in a condition position?
1673 fn cond_needs_par(expr: &ast::Expr) -> bool {
1675 // These cases need parens due to the parse error observed in #26461: `if return {}`
1676 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1677 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1679 _ => parser::contains_exterior_struct_lit(expr),
1683 /// Prints `expr` or `(expr)` when `needs_par` holds.
1684 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, mut needs_par: bool) {
1685 needs_par &= self.insert_extra_parens;
1689 self.print_expr(expr);
1695 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[ast::Attribute]) {
1696 self.ibox(INDENT_UNIT);
1698 self.print_inner_attributes_inline(attrs);
1699 self.commasep_exprs(Inconsistent, &exprs[..]);
1704 fn print_expr_anon_const(&mut self, expr: &ast::AnonConst, attrs: &[ast::Attribute]) {
1705 self.ibox(INDENT_UNIT);
1706 self.s.word("const");
1707 self.print_inner_attributes_inline(attrs);
1708 self.print_expr(&expr.value);
1712 fn print_expr_repeat(
1714 element: &ast::Expr,
1715 count: &ast::AnonConst,
1716 attrs: &[ast::Attribute],
1718 self.ibox(INDENT_UNIT);
1720 self.print_inner_attributes_inline(attrs);
1721 self.print_expr(element);
1722 self.word_space(";");
1723 self.print_expr(&count.value);
1728 fn print_expr_struct(
1731 fields: &[ast::Field],
1732 rest: &ast::StructRest,
1733 attrs: &[ast::Attribute],
1735 self.print_path(path, true, 0);
1737 self.print_inner_attributes_inline(attrs);
1742 s.print_outer_attributes(&field.attrs);
1743 s.ibox(INDENT_UNIT);
1744 if !field.is_shorthand {
1745 s.print_ident(field.ident);
1748 s.print_expr(&field.expr);
1754 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1755 self.ibox(INDENT_UNIT);
1756 if !fields.is_empty() {
1761 if let ast::StructRest::Base(ref expr) = *rest {
1762 self.print_expr(expr);
1766 ast::StructRest::None if !fields.is_empty() => self.s.word(","),
1772 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[ast::Attribute]) {
1774 self.print_inner_attributes_inline(attrs);
1775 self.commasep_exprs(Inconsistent, &exprs[..]);
1776 if exprs.len() == 1 {
1782 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1783 let prec = match func.kind {
1784 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1785 _ => parser::PREC_POSTFIX,
1788 self.print_expr_maybe_paren(func, prec);
1789 self.print_call_post(args)
1792 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1793 let base_args = &args[1..];
1794 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1796 self.print_ident(segment.ident);
1797 if let Some(ref args) = segment.args {
1798 self.print_generic_args(args, true);
1800 self.print_call_post(base_args)
1803 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1804 let assoc_op = AssocOp::from_ast_binop(op.node);
1805 let prec = assoc_op.precedence() as i8;
1806 let fixity = assoc_op.fixity();
1808 let (left_prec, right_prec) = match fixity {
1809 Fixity::Left => (prec, prec + 1),
1810 Fixity::Right => (prec + 1, prec),
1811 Fixity::None => (prec + 1, prec + 1),
1814 let left_prec = match (&lhs.kind, op.node) {
1815 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1816 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1817 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1818 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1819 parser::PREC_FORCE_PAREN
1821 // We are given `(let _ = a) OP b`.
1823 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1824 // as the parser will interpret this as `(let _ = a) OP b`.
1826 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1827 // parens are required since the parser would interpret `let a = b < c` as
1828 // `let a = (b < c)`. To achieve this, we force parens.
1829 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1830 parser::PREC_FORCE_PAREN
1835 self.print_expr_maybe_paren(lhs, left_prec);
1837 self.word_space(op.node.to_string());
1838 self.print_expr_maybe_paren(rhs, right_prec)
1841 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1842 self.s.word(ast::UnOp::to_string(op));
1843 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1846 fn print_expr_addr_of(
1848 kind: ast::BorrowKind,
1849 mutability: ast::Mutability,
1854 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1855 ast::BorrowKind::Raw => {
1856 self.word_nbsp("raw");
1857 self.print_mutability(mutability, true);
1860 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1863 pub fn print_expr(&mut self, expr: &ast::Expr) {
1864 self.print_expr_outer_attr_style(expr, true)
1867 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1868 self.maybe_print_comment(expr.span.lo());
1870 let attrs = &expr.attrs;
1872 self.print_outer_attributes_inline(attrs);
1874 self.print_outer_attributes(attrs);
1877 self.ibox(INDENT_UNIT);
1878 self.ann.pre(self, AnnNode::Expr(expr));
1880 ast::ExprKind::Box(ref expr) => {
1881 self.word_space("box");
1882 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1884 ast::ExprKind::Array(ref exprs) => {
1885 self.print_expr_vec(&exprs[..], attrs);
1887 ast::ExprKind::ConstBlock(ref anon_const) => {
1888 self.print_expr_anon_const(anon_const, attrs);
1890 ast::ExprKind::Repeat(ref element, ref count) => {
1891 self.print_expr_repeat(element, count, attrs);
1893 ast::ExprKind::Struct(ref path, ref fields, ref rest) => {
1894 self.print_expr_struct(path, &fields[..], rest, attrs);
1896 ast::ExprKind::Tup(ref exprs) => {
1897 self.print_expr_tup(&exprs[..], attrs);
1899 ast::ExprKind::Call(ref func, ref args) => {
1900 self.print_expr_call(func, &args[..]);
1902 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1903 self.print_expr_method_call(segment, &args[..]);
1905 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1906 self.print_expr_binary(op, lhs, rhs);
1908 ast::ExprKind::Unary(op, ref expr) => {
1909 self.print_expr_unary(op, expr);
1911 ast::ExprKind::AddrOf(k, m, ref expr) => {
1912 self.print_expr_addr_of(k, m, expr);
1914 ast::ExprKind::Lit(ref lit) => {
1915 self.print_literal(lit);
1917 ast::ExprKind::Cast(ref expr, ref ty) => {
1918 let prec = AssocOp::As.precedence() as i8;
1919 self.print_expr_maybe_paren(expr, prec);
1921 self.word_space("as");
1922 self.print_type(ty);
1924 ast::ExprKind::Type(ref expr, ref ty) => {
1925 let prec = AssocOp::Colon.precedence() as i8;
1926 self.print_expr_maybe_paren(expr, prec);
1927 self.word_space(":");
1928 self.print_type(ty);
1930 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1931 self.print_let(pat, scrutinee);
1933 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1934 self.print_if(test, blk, elseopt.as_deref())
1936 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1937 if let Some(label) = opt_label {
1938 self.print_ident(label.ident);
1939 self.word_space(":");
1942 self.print_expr_as_cond(test);
1944 self.print_block_with_attrs(blk, attrs);
1946 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1947 if let Some(label) = opt_label {
1948 self.print_ident(label.ident);
1949 self.word_space(":");
1952 self.print_pat(pat);
1954 self.word_space("in");
1955 self.print_expr_as_cond(iter);
1957 self.print_block_with_attrs(blk, attrs);
1959 ast::ExprKind::Loop(ref blk, opt_label) => {
1960 if let Some(label) = opt_label {
1961 self.print_ident(label.ident);
1962 self.word_space(":");
1966 self.print_block_with_attrs(blk, attrs);
1968 ast::ExprKind::Match(ref expr, ref arms) => {
1969 self.cbox(INDENT_UNIT);
1970 self.ibox(INDENT_UNIT);
1971 self.word_nbsp("match");
1972 self.print_expr_as_cond(expr);
1975 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1977 self.print_arm(arm);
1979 self.bclose(expr.span);
1981 ast::ExprKind::Closure(
1989 self.print_movability(movability);
1990 self.print_asyncness(asyncness);
1991 self.print_capture_clause(capture_clause);
1993 self.print_fn_params_and_ret(decl, true);
1995 self.print_expr(body);
1996 self.end(); // need to close a box
1998 // a box will be closed by print_expr, but we didn't want an overall
1999 // wrapper so we closed the corresponding opening. so create an
2000 // empty box to satisfy the close.
2003 ast::ExprKind::Block(ref blk, opt_label) => {
2004 if let Some(label) = opt_label {
2005 self.print_ident(label.ident);
2006 self.word_space(":");
2008 // containing cbox, will be closed by print-block at }
2009 self.cbox(INDENT_UNIT);
2010 // head-box, will be closed by print-block after {
2012 self.print_block_with_attrs(blk, attrs);
2014 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2015 self.word_nbsp("async");
2016 self.print_capture_clause(capture_clause);
2018 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2019 self.cbox(INDENT_UNIT);
2021 self.print_block_with_attrs(blk, attrs);
2023 ast::ExprKind::Await(ref expr) => {
2024 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2025 self.s.word(".await");
2027 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2028 let prec = AssocOp::Assign.precedence() as i8;
2029 self.print_expr_maybe_paren(lhs, prec + 1);
2031 self.word_space("=");
2032 self.print_expr_maybe_paren(rhs, prec);
2034 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2035 let prec = AssocOp::Assign.precedence() as i8;
2036 self.print_expr_maybe_paren(lhs, prec + 1);
2038 self.s.word(op.node.to_string());
2039 self.word_space("=");
2040 self.print_expr_maybe_paren(rhs, prec);
2042 ast::ExprKind::Field(ref expr, ident) => {
2043 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2045 self.print_ident(ident);
2047 ast::ExprKind::Index(ref expr, ref index) => {
2048 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2050 self.print_expr(index);
2053 ast::ExprKind::Range(ref start, ref end, limits) => {
2054 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2055 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2056 // Here we use a fake precedence value so that any child with lower precedence than
2057 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2058 let fake_prec = AssocOp::LOr.precedence() as i8;
2059 if let Some(ref e) = *start {
2060 self.print_expr_maybe_paren(e, fake_prec);
2062 if limits == ast::RangeLimits::HalfOpen {
2067 if let Some(ref e) = *end {
2068 self.print_expr_maybe_paren(e, fake_prec);
2071 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2072 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2073 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2074 self.s.word("break");
2076 if let Some(label) = opt_label {
2077 self.print_ident(label.ident);
2080 if let Some(ref expr) = *opt_expr {
2081 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2085 ast::ExprKind::Continue(opt_label) => {
2086 self.s.word("continue");
2088 if let Some(label) = opt_label {
2089 self.print_ident(label.ident);
2093 ast::ExprKind::Ret(ref result) => {
2094 self.s.word("return");
2095 if let Some(ref expr) = *result {
2097 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2100 ast::ExprKind::InlineAsm(ref a) => {
2103 Operand(&'a InlineAsmOperand),
2104 Options(InlineAsmOptions),
2107 let mut args = vec![];
2108 args.push(AsmArg::Template(InlineAsmTemplatePiece::to_string(&a.template)));
2109 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2110 if !a.options.is_empty() {
2111 args.push(AsmArg::Options(a.options));
2116 self.commasep(Consistent, &args, |s, arg| match arg {
2117 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2118 AsmArg::Operand(op) => {
2119 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r
2121 InlineAsmRegOrRegClass::Reg(r) => {
2122 s.print_symbol(*r, ast::StrStyle::Cooked)
2124 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2127 InlineAsmOperand::In { reg, expr } => {
2130 print_reg_or_class(s, reg);
2135 InlineAsmOperand::Out { reg, late, expr } => {
2136 s.word(if *late { "lateout" } else { "out" });
2138 print_reg_or_class(s, reg);
2142 Some(expr) => s.print_expr(expr),
2143 None => s.word("_"),
2146 InlineAsmOperand::InOut { reg, late, expr } => {
2147 s.word(if *late { "inlateout" } else { "inout" });
2149 print_reg_or_class(s, reg);
2154 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2155 s.word(if *late { "inlateout" } else { "inout" });
2157 print_reg_or_class(s, reg);
2160 s.print_expr(in_expr);
2164 Some(out_expr) => s.print_expr(out_expr),
2165 None => s.word("_"),
2168 InlineAsmOperand::Const { expr } => {
2173 InlineAsmOperand::Sym { expr } => {
2180 AsmArg::Options(opts) => {
2183 let mut options = vec![];
2184 if opts.contains(InlineAsmOptions::PURE) {
2185 options.push("pure");
2187 if opts.contains(InlineAsmOptions::NOMEM) {
2188 options.push("nomem");
2190 if opts.contains(InlineAsmOptions::READONLY) {
2191 options.push("readonly");
2193 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2194 options.push("preserves_flags");
2196 if opts.contains(InlineAsmOptions::NORETURN) {
2197 options.push("noreturn");
2199 if opts.contains(InlineAsmOptions::NOSTACK) {
2200 options.push("nostack");
2202 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2203 options.push("att_syntax");
2205 s.commasep(Inconsistent, &options, |s, &opt| {
2213 ast::ExprKind::LlvmInlineAsm(ref a) => {
2214 self.s.word("llvm_asm!");
2216 self.print_symbol(a.asm, a.asm_str_style);
2217 self.word_space(":");
2219 self.commasep(Inconsistent, &a.outputs, |s, out| {
2220 let constraint = out.constraint.as_str();
2221 let mut ch = constraint.chars();
2223 Some('=') if out.is_rw => {
2224 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2226 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2229 s.print_expr(&out.expr);
2233 self.word_space(":");
2235 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2236 s.print_symbol(co, ast::StrStyle::Cooked);
2242 self.word_space(":");
2244 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2245 s.print_symbol(co, ast::StrStyle::Cooked);
2248 let mut options = vec![];
2250 options.push("volatile");
2253 options.push("alignstack");
2255 if a.dialect == ast::LlvmAsmDialect::Intel {
2256 options.push("intel");
2259 if !options.is_empty() {
2261 self.word_space(":");
2262 self.commasep(Inconsistent, &options, |s, &co| {
2263 s.print_string(co, ast::StrStyle::Cooked);
2269 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2270 ast::ExprKind::Paren(ref e) => {
2272 self.print_inner_attributes_inline(attrs);
2276 ast::ExprKind::Yield(ref e) => {
2277 self.s.word("yield");
2279 if let Some(ref expr) = *e {
2281 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2284 ast::ExprKind::Try(ref e) => {
2285 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2288 ast::ExprKind::TryBlock(ref blk) => {
2291 self.print_block_with_attrs(blk, attrs)
2293 ast::ExprKind::Err => {
2295 self.s.word("/*ERROR*/");
2299 self.ann.post(self, AnnNode::Expr(expr));
2303 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2304 self.print_pat(&loc.pat);
2305 if let Some(ref ty) = loc.ty {
2306 self.word_space(":");
2307 self.print_type(ty);
2311 pub fn print_usize(&mut self, i: usize) {
2312 self.s.word(i.to_string())
2315 crate fn print_name(&mut self, name: Symbol) {
2316 self.s.word(name.to_string());
2317 self.ann.post(self, AnnNode::Name(&name))
2320 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2322 self.print_type(&qself.ty);
2323 if qself.position > 0 {
2325 self.word_space("as");
2326 let depth = path.segments.len() - qself.position;
2327 self.print_path(path, false, depth);
2331 let item_segment = path.segments.last().unwrap();
2332 self.print_ident(item_segment.ident);
2333 if let Some(ref args) = item_segment.args {
2334 self.print_generic_args(args, colons_before_params)
2338 crate fn print_pat(&mut self, pat: &ast::Pat) {
2339 self.maybe_print_comment(pat.span.lo());
2340 self.ann.pre(self, AnnNode::Pat(pat));
2341 /* Pat isn't normalized, but the beauty of it
2342 is that it doesn't matter */
2344 PatKind::Wild => self.s.word("_"),
2345 PatKind::Ident(binding_mode, ident, ref sub) => {
2346 match binding_mode {
2347 ast::BindingMode::ByRef(mutbl) => {
2348 self.word_nbsp("ref");
2349 self.print_mutability(mutbl, false);
2351 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2352 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2353 self.word_nbsp("mut");
2356 self.print_ident(ident);
2357 if let Some(ref p) = *sub {
2359 self.s.word_space("@");
2363 PatKind::TupleStruct(ref path, ref elts) => {
2364 self.print_path(path, true, 0);
2366 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2369 PatKind::Or(ref pats) => {
2370 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2372 PatKind::Path(None, ref path) => {
2373 self.print_path(path, true, 0);
2375 PatKind::Path(Some(ref qself), ref path) => {
2376 self.print_qpath(path, qself, false);
2378 PatKind::Struct(ref path, ref fields, etc) => {
2379 self.print_path(path, true, 0);
2381 self.word_space("{");
2386 s.cbox(INDENT_UNIT);
2387 if !f.is_shorthand {
2388 s.print_ident(f.ident);
2391 s.print_pat(&f.pat);
2397 if !fields.is_empty() {
2398 self.word_space(",");
2405 PatKind::Tuple(ref elts) => {
2407 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2408 if elts.len() == 1 {
2413 PatKind::Box(ref inner) => {
2414 self.s.word("box ");
2415 self.print_pat(inner);
2417 PatKind::Ref(ref inner, mutbl) => {
2419 if mutbl == ast::Mutability::Mut {
2420 self.s.word("mut ");
2422 self.print_pat(inner);
2424 PatKind::Lit(ref e) => self.print_expr(&**e),
2425 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2426 if let Some(e) = begin {
2431 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2432 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2433 RangeEnd::Excluded => self.s.word(".."),
2435 if let Some(e) = end {
2439 PatKind::Slice(ref elts) => {
2441 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2444 PatKind::Rest => self.s.word(".."),
2445 PatKind::Paren(ref inner) => {
2447 self.print_pat(inner);
2450 PatKind::MacCall(ref m) => self.print_mac(m),
2452 self.ann.post(self, AnnNode::Pat(pat))
2455 fn print_arm(&mut self, arm: &ast::Arm) {
2456 // Note, I have no idea why this check is necessary, but here it is.
2457 if arm.attrs.is_empty() {
2460 self.cbox(INDENT_UNIT);
2462 self.maybe_print_comment(arm.pat.span.lo());
2463 self.print_outer_attributes(&arm.attrs);
2464 self.print_pat(&arm.pat);
2466 if let Some(ref e) = arm.guard {
2467 self.word_space("if");
2471 self.word_space("=>");
2473 match arm.body.kind {
2474 ast::ExprKind::Block(ref blk, opt_label) => {
2475 if let Some(label) = opt_label {
2476 self.print_ident(label.ident);
2477 self.word_space(":");
2480 // The block will close the pattern's ibox.
2481 self.print_block_unclosed_indent(blk);
2483 // If it is a user-provided unsafe block, print a comma after it.
2484 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2489 self.end(); // Close the ibox for the pattern.
2490 self.print_expr(&arm.body);
2494 self.end(); // Close enclosing cbox.
2497 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2498 match explicit_self.node {
2499 SelfKind::Value(m) => {
2500 self.print_mutability(m, false);
2503 SelfKind::Region(ref lt, m) => {
2505 self.print_opt_lifetime(lt);
2506 self.print_mutability(m, false);
2509 SelfKind::Explicit(ref typ, m) => {
2510 self.print_mutability(m, false);
2511 self.s.word("self");
2512 self.word_space(":");
2513 self.print_type(typ)
2522 generics: &ast::Generics,
2523 vis: &ast::Visibility,
2524 defaultness: ast::Defaultness,
2525 body: Option<&ast::Block>,
2526 attrs: &[ast::Attribute],
2531 self.print_visibility(vis);
2532 self.print_defaultness(defaultness);
2533 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2534 if let Some(body) = body {
2536 self.print_block_with_attrs(body, attrs);
2545 header: ast::FnHeader,
2546 name: Option<Ident>,
2547 generics: &ast::Generics,
2549 self.print_fn_header_info(header);
2550 if let Some(name) = name {
2552 self.print_ident(name);
2554 self.print_generic_params(&generics.params);
2555 self.print_fn_params_and_ret(decl, false);
2556 self.print_where_clause(&generics.where_clause)
2559 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2560 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2562 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2564 self.print_fn_ret_ty(&decl.output)
2567 crate fn print_movability(&mut self, movability: ast::Movability) {
2569 ast::Movability::Static => self.word_space("static"),
2570 ast::Movability::Movable => {}
2574 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2575 if asyncness.is_async() {
2576 self.word_nbsp("async");
2580 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2581 match capture_clause {
2582 ast::CaptureBy::Value => self.word_space("move"),
2583 ast::CaptureBy::Ref => {}
2587 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2588 if !bounds.is_empty() {
2589 self.s.word(prefix);
2590 let mut first = true;
2591 for bound in bounds {
2592 if !(first && prefix.is_empty()) {
2598 self.word_space("+");
2602 GenericBound::Trait(tref, modifier) => {
2603 if modifier == &TraitBoundModifier::Maybe {
2606 self.print_poly_trait_ref(tref);
2608 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2614 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2615 self.print_name(lifetime.ident.name)
2618 crate fn print_lifetime_bounds(
2620 lifetime: ast::Lifetime,
2621 bounds: &ast::GenericBounds,
2623 self.print_lifetime(lifetime);
2624 if !bounds.is_empty() {
2626 for (i, bound) in bounds.iter().enumerate() {
2631 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2638 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2639 if generic_params.is_empty() {
2645 self.commasep(Inconsistent, &generic_params, |s, param| {
2646 s.print_outer_attributes_inline(¶m.attrs);
2649 ast::GenericParamKind::Lifetime => {
2650 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2651 s.print_lifetime_bounds(lt, ¶m.bounds)
2653 ast::GenericParamKind::Type { ref default } => {
2654 s.print_ident(param.ident);
2655 s.print_type_bounds(":", ¶m.bounds);
2656 if let Some(ref default) = default {
2659 s.print_type(default)
2662 ast::GenericParamKind::Const { ref ty, kw_span: _ } => {
2663 s.word_space("const");
2664 s.print_ident(param.ident);
2668 s.print_type_bounds(":", ¶m.bounds)
2676 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2677 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2682 self.word_space("where");
2684 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2686 self.word_space(",");
2690 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2691 ref bound_generic_params,
2696 self.print_formal_generic_params(bound_generic_params);
2697 self.print_type(bounded_ty);
2698 self.print_type_bounds(":", bounds);
2700 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2705 self.print_lifetime_bounds(*lifetime, bounds);
2707 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2712 self.print_type(lhs_ty);
2714 self.word_space("=");
2715 self.print_type(rhs_ty);
2721 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2723 ast::UseTreeKind::Simple(rename, ..) => {
2724 self.print_path(&tree.prefix, false, 0);
2725 if let Some(rename) = rename {
2727 self.word_space("as");
2728 self.print_ident(rename);
2731 ast::UseTreeKind::Glob => {
2732 if !tree.prefix.segments.is_empty() {
2733 self.print_path(&tree.prefix, false, 0);
2738 ast::UseTreeKind::Nested(ref items) => {
2739 if tree.prefix.segments.is_empty() {
2742 self.print_path(&tree.prefix, false, 0);
2745 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2746 this.print_use_tree(tree)
2753 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2755 ast::Mutability::Mut => self.word_nbsp("mut"),
2756 ast::Mutability::Not => {
2758 self.word_nbsp("const");
2764 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2765 self.print_mutability(mt.mutbl, print_const);
2766 self.print_type(&mt.ty)
2769 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2770 self.ibox(INDENT_UNIT);
2772 self.print_outer_attributes_inline(&input.attrs);
2774 match input.ty.kind {
2775 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2777 if let Some(eself) = input.to_self() {
2778 self.print_explicit_self(&eself);
2780 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2781 ident.name == kw::Invalid
2786 self.print_pat(&input.pat);
2790 self.print_type(&input.ty);
2797 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2798 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2799 self.space_if_not_bol();
2800 self.ibox(INDENT_UNIT);
2801 self.word_space("->");
2802 self.print_type(ty);
2804 self.maybe_print_comment(ty.span.lo());
2808 crate fn print_ty_fn(
2811 unsafety: ast::Unsafe,
2813 name: Option<Ident>,
2814 generic_params: &[ast::GenericParam],
2816 self.ibox(INDENT_UNIT);
2817 if !generic_params.is_empty() {
2819 self.print_generic_params(generic_params);
2821 let generics = ast::Generics {
2823 where_clause: ast::WhereClause {
2824 has_where_token: false,
2825 predicates: Vec::new(),
2826 span: rustc_span::DUMMY_SP,
2828 span: rustc_span::DUMMY_SP,
2830 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2831 self.print_fn(decl, header, name, &generics);
2835 crate fn maybe_print_trailing_comment(
2837 span: rustc_span::Span,
2838 next_pos: Option<BytePos>,
2840 if let Some(cmnts) = self.comments() {
2841 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2842 self.print_comment(&cmnt);
2847 crate fn print_remaining_comments(&mut self) {
2848 // If there aren't any remaining comments, then we need to manually
2849 // make sure there is a line break at the end.
2850 if self.next_comment().is_none() {
2853 while let Some(ref cmnt) = self.next_comment() {
2854 self.print_comment(cmnt);
2858 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2859 self.print_constness(header.constness);
2860 self.print_asyncness(header.asyncness);
2861 self.print_unsafety(header.unsafety);
2864 ast::Extern::None => {}
2865 ast::Extern::Implicit => {
2866 self.word_nbsp("extern");
2868 ast::Extern::Explicit(abi) => {
2869 self.word_nbsp("extern");
2870 self.print_literal(&abi.as_lit());
2878 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2880 ast::Unsafe::No => {}
2881 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2885 crate fn print_constness(&mut self, s: ast::Const) {
2887 ast::Const::No => {}
2888 ast::Const::Yes(_) => self.word_nbsp("const"),
2892 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2894 ast::IsAuto::Yes => self.word_nbsp("auto"),
2895 ast::IsAuto::No => {}