1 use crate::pp::Breaks::{Consistent, Inconsistent};
2 use crate::pp::{self, Breaks};
4 use rustc_ast::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
5 use rustc_ast::ast::{Attribute, GenericArg, MacArgs};
6 use rustc_ast::ast::{GenericBound, SelfKind, TraitBoundModifier};
7 use rustc_ast::ast::{InlineAsmOperand, InlineAsmRegOrRegClass};
8 use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
12 use rustc_ast::tokenstream::{TokenStream, TokenTree};
13 use rustc_ast::util::parser::{self, AssocOp, Fixity};
14 use rustc_ast::util::{classify, comments};
15 use rustc_span::edition::Edition;
16 use rustc_span::source_map::{SourceMap, Spanned};
17 use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol};
18 use rustc_span::{BytePos, FileName, Span};
25 pub enum MacHeader<'a> {
27 Keyword(&'static str),
30 pub enum AnnNode<'a> {
33 Block(&'a ast::Block),
38 Crate(&'a ast::Crate),
42 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
43 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 #[derive(Copy, Clone)]
49 impl PpAnn for NoAnn {}
51 pub struct Comments<'a> {
53 comments: Vec<comments::Comment>,
57 impl<'a> Comments<'a> {
58 pub fn new(sm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
59 let comments = comments::gather_comments(sm, filename, input);
60 Comments { sm, comments, current: 0 }
63 pub fn next(&self) -> Option<comments::Comment> {
64 self.comments.get(self.current).cloned()
67 pub fn trailing_comment(
69 span: rustc_span::Span,
70 next_pos: Option<BytePos>,
71 ) -> Option<comments::Comment> {
72 if let Some(cmnt) = self.next() {
73 if cmnt.style != comments::Trailing {
76 let span_line = self.sm.lookup_char_pos(span.hi());
77 let comment_line = self.sm.lookup_char_pos(cmnt.pos);
78 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
79 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
88 pub struct State<'a> {
90 comments: Option<Comments<'a>>,
91 ann: &'a (dyn PpAnn + 'a),
95 crate const INDENT_UNIT: usize = 4;
97 /// Requires you to pass an input filename and reader so that
98 /// it can scan the input text for comments to copy forward.
99 pub fn print_crate<'a>(
107 has_injected_crate: bool,
111 comments: Some(Comments::new(sm, filename, input)),
116 if is_expanded && has_injected_crate {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However, we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
122 // `#![feature(prelude_import)]`
123 let pi_nested = attr::mk_nested_word_item(Ident::with_dummy_span(sym::prelude_import));
124 let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), vec![pi_nested]);
125 let fake_attr = attr::mk_attr_inner(list);
126 s.print_attribute(&fake_attr);
128 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
129 // root, so this is not needed, and actually breaks things.
130 if edition == Edition::Edition2015 {
132 let no_std_meta = attr::mk_word_item(Ident::with_dummy_span(sym::no_std));
133 let fake_attr = attr::mk_attr_inner(no_std_meta);
134 s.print_attribute(&fake_attr);
138 s.print_mod(&krate.module, &krate.attrs);
139 s.print_remaining_comments();
140 s.ann.post(&mut s, AnnNode::Crate(krate));
144 pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
146 State { s: pp::mk_printer(), comments: None, ann: &NoAnn, is_expanded: false };
151 // This makes printed token streams look slightly nicer,
152 // and also addresses some specific regressions described in #63896 and #73345.
153 fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool {
154 if let TokenTree::Token(token) = prev {
155 if let token::DocComment(s) = token.kind {
156 return !s.as_str().starts_with("//");
160 TokenTree::Token(token) => match token.kind {
161 token::Comma => false,
164 TokenTree::Delimited(_, DelimToken::Paren, _) => match prev {
165 TokenTree::Token(token) => match token.kind {
166 token::Ident(_, _) => false,
171 TokenTree::Delimited(_, DelimToken::Bracket, _) => match prev {
172 TokenTree::Token(token) => match token.kind {
173 token::Pound => false,
178 TokenTree::Delimited(..) => true,
182 fn binop_to_string(op: BinOpToken) -> &'static str {
188 token::Percent => "%",
197 pub fn literal_to_string(lit: token::Lit) -> String {
198 let token::Lit { kind, symbol, suffix } = lit;
199 let mut out = match kind {
200 token::Byte => format!("b'{}'", symbol),
201 token::Char => format!("'{}'", symbol),
202 token::Str => format!("\"{}\"", symbol),
203 token::StrRaw(n) => {
204 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
206 token::ByteStr => format!("b\"{}\"", symbol),
207 token::ByteStrRaw(n) => {
208 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
210 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
213 if let Some(suffix) = suffix {
214 out.push_str(&suffix.as_str())
220 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
221 pub fn token_kind_to_string(tok: &TokenKind) -> String {
222 token_kind_to_string_ext(tok, None)
225 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
227 token::Eq => "=".to_string(),
228 token::Lt => "<".to_string(),
229 token::Le => "<=".to_string(),
230 token::EqEq => "==".to_string(),
231 token::Ne => "!=".to_string(),
232 token::Ge => ">=".to_string(),
233 token::Gt => ">".to_string(),
234 token::Not => "!".to_string(),
235 token::Tilde => "~".to_string(),
236 token::OrOr => "||".to_string(),
237 token::AndAnd => "&&".to_string(),
238 token::BinOp(op) => binop_to_string(op).to_string(),
239 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
241 /* Structural symbols */
242 token::At => "@".to_string(),
243 token::Dot => ".".to_string(),
244 token::DotDot => "..".to_string(),
245 token::DotDotDot => "...".to_string(),
246 token::DotDotEq => "..=".to_string(),
247 token::Comma => ",".to_string(),
248 token::Semi => ";".to_string(),
249 token::Colon => ":".to_string(),
250 token::ModSep => "::".to_string(),
251 token::RArrow => "->".to_string(),
252 token::LArrow => "<-".to_string(),
253 token::FatArrow => "=>".to_string(),
254 token::OpenDelim(token::Paren) => "(".to_string(),
255 token::CloseDelim(token::Paren) => ")".to_string(),
256 token::OpenDelim(token::Bracket) => "[".to_string(),
257 token::CloseDelim(token::Bracket) => "]".to_string(),
258 token::OpenDelim(token::Brace) => "{".to_string(),
259 token::CloseDelim(token::Brace) => "}".to_string(),
260 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => "".to_string(),
261 token::Pound => "#".to_string(),
262 token::Dollar => "$".to_string(),
263 token::Question => "?".to_string(),
264 token::SingleQuote => "'".to_string(),
267 token::Literal(lit) => literal_to_string(lit),
269 /* Name components */
270 token::Ident(s, is_raw) => IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string(),
271 token::Lifetime(s) => s.to_string(),
274 token::DocComment(s) => s.to_string(),
275 token::Eof => "<eof>".to_string(),
276 token::Whitespace => " ".to_string(),
277 token::Comment => "/* */".to_string(),
278 token::Shebang(s) => format!("/* shebang: {}*/", s),
279 token::Unknown(s) => s.to_string(),
281 token::Interpolated(ref nt) => nonterminal_to_string(nt),
285 /// Print the token precisely, without converting `$crate` into its respective crate name.
286 pub fn token_to_string(token: &Token) -> String {
287 token_to_string_ext(token, false)
290 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
291 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
292 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
295 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
297 token::NtExpr(ref e) => expr_to_string(e),
298 token::NtMeta(ref e) => attr_item_to_string(e),
299 token::NtTy(ref e) => ty_to_string(e),
300 token::NtPath(ref e) => path_to_string(e),
301 token::NtItem(ref e) => item_to_string(e),
302 token::NtBlock(ref e) => block_to_string(e),
303 token::NtStmt(ref e) => stmt_to_string(e),
304 token::NtPat(ref e) => pat_to_string(e),
305 token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(),
306 token::NtLifetime(e) => e.to_string(),
307 token::NtLiteral(ref e) => expr_to_string(e),
308 token::NtTT(ref tree) => tt_to_string(tree),
309 token::NtVis(ref e) => vis_to_string(e),
313 pub fn ty_to_string(ty: &ast::Ty) -> String {
314 to_string(|s| s.print_type(ty))
317 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
318 to_string(|s| s.print_type_bounds("", bounds))
321 pub fn pat_to_string(pat: &ast::Pat) -> String {
322 to_string(|s| s.print_pat(pat))
325 pub fn expr_to_string(e: &ast::Expr) -> String {
326 to_string(|s| s.print_expr(e))
329 pub fn tt_to_string(tt: &TokenTree) -> String {
330 to_string(|s| s.print_tt(tt, false))
333 pub fn tts_to_string(tokens: &TokenStream) -> String {
334 to_string(|s| s.print_tts(tokens, false))
337 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
338 to_string(|s| s.print_stmt(stmt))
341 pub fn item_to_string(i: &ast::Item) -> String {
342 to_string(|s| s.print_item(i))
345 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
346 to_string(|s| s.print_generic_params(generic_params))
349 pub fn path_to_string(p: &ast::Path) -> String {
350 to_string(|s| s.print_path(p, false, 0))
353 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
354 to_string(|s| s.print_path_segment(p, false))
357 pub fn vis_to_string(v: &ast::Visibility) -> String {
358 to_string(|s| s.print_visibility(v))
361 fn block_to_string(blk: &ast::Block) -> String {
363 // Containing cbox, will be closed by `print_block` at `}`.
365 // Head-ibox, will be closed by `print_block` after `{`.
371 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
372 to_string(|s| s.print_meta_list_item(li))
375 fn attr_item_to_string(ai: &ast::AttrItem) -> String {
376 to_string(|s| s.print_attr_item(ai, ai.path.span))
379 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
380 to_string(|s| s.print_attribute(attr))
383 pub fn param_to_string(arg: &ast::Param) -> String {
384 to_string(|s| s.print_param(arg, false))
387 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
388 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
391 impl std::ops::Deref for State<'_> {
392 type Target = pp::Printer;
393 fn deref(&self) -> &Self::Target {
398 impl std::ops::DerefMut for State<'_> {
399 fn deref_mut(&mut self) -> &mut Self::Target {
404 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
405 fn comments(&mut self) -> &mut Option<Comments<'a>>;
406 fn print_ident(&mut self, ident: Ident);
407 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
417 F: FnMut(&mut Self, &T),
420 if let Some((first, rest)) = elts.split_first() {
426 self.word_space(sep);
433 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
435 F: FnMut(&mut Self, &T),
437 self.strsep(",", false, b, elts, op)
440 fn maybe_print_comment(&mut self, pos: BytePos) {
441 while let Some(ref cmnt) = self.next_comment() {
443 self.print_comment(cmnt);
450 fn print_comment(&mut self, cmnt: &comments::Comment) {
453 assert_eq!(cmnt.lines.len(), 1);
455 self.word(cmnt.lines[0].clone());
458 comments::Isolated => {
459 self.hardbreak_if_not_bol();
460 for line in &cmnt.lines {
461 // Don't print empty lines because they will end up as trailing
463 if !line.is_empty() {
464 self.word(line.clone());
469 comments::Trailing => {
470 if !self.is_beginning_of_line() {
473 if cmnt.lines.len() == 1 {
474 self.word(cmnt.lines[0].clone());
478 for line in &cmnt.lines {
479 if !line.is_empty() {
480 self.word(line.clone());
487 comments::BlankLine => {
488 // We need to do at least one, possibly two hardbreaks.
489 let twice = match self.last_token() {
490 pp::Token::String(s) => ";" == s,
491 pp::Token::Begin(_) => true,
492 pp::Token::End => true,
501 if let Some(cmnts) = self.comments() {
506 fn next_comment(&mut self) -> Option<comments::Comment> {
507 self.comments().as_mut().and_then(|c| c.next())
510 fn print_literal(&mut self, lit: &ast::Lit) {
511 self.maybe_print_comment(lit.span.lo());
512 self.word(lit.token.to_string())
515 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
516 let st = match style {
517 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
518 ast::StrStyle::Raw(n) => {
519 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
525 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
526 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
529 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
530 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
533 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
534 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
537 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
538 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
541 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
542 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
545 fn print_either_attributes(
547 attrs: &[ast::Attribute],
548 kind: ast::AttrStyle,
550 trailing_hardbreak: bool,
554 if attr.style == kind {
555 self.print_attribute_inline(attr, is_inline);
562 if count > 0 && trailing_hardbreak && !is_inline {
563 self.hardbreak_if_not_bol();
567 fn print_attribute(&mut self, attr: &ast::Attribute) {
568 self.print_attribute_inline(attr, false)
571 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
573 self.hardbreak_if_not_bol();
575 self.maybe_print_comment(attr.span.lo());
577 ast::AttrKind::Normal(ref item) => {
579 ast::AttrStyle::Inner => self.word("#!["),
580 ast::AttrStyle::Outer => self.word("#["),
582 self.print_attr_item(&item, attr.span);
585 ast::AttrKind::DocComment(comment) => {
586 self.word(comment.to_string());
592 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
595 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
596 Some(MacHeader::Path(&item.path)),
604 MacArgs::Empty | MacArgs::Eq(..) => {
605 self.print_path(&item.path, false, 0);
606 if let MacArgs::Eq(_, tokens) = &item.args {
608 self.word_space("=");
609 self.print_tts(tokens, true);
616 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
618 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
619 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
623 fn print_meta_item(&mut self, item: &ast::MetaItem) {
624 self.ibox(INDENT_UNIT);
626 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
627 ast::MetaItemKind::NameValue(ref value) => {
628 self.print_path(&item.path, false, 0);
630 self.word_space("=");
631 self.print_literal(value);
633 ast::MetaItemKind::List(ref items) => {
634 self.print_path(&item.path, false, 0);
636 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
643 /// This doesn't deserve to be called "pretty" printing, but it should be
644 /// meaning-preserving. A quick hack that might help would be to look at the
645 /// spans embedded in the TTs to decide where to put spaces and newlines.
646 /// But it'd be better to parse these according to the grammar of the
647 /// appropriate macro, transcribe back into the grammar we just parsed from,
648 /// and then pretty-print the resulting AST nodes (so, e.g., we print
649 /// expression arguments as expressions). It can be done! I think.
650 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
652 TokenTree::Token(token) => {
653 self.word(token_to_string_ext(&token, convert_dollar_crate));
654 if let token::DocComment(..) = token.kind {
658 TokenTree::Delimited(dspan, delim, tts) => {
659 self.print_mac_common(
665 convert_dollar_crate,
672 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
673 let mut iter = tts.trees().peekable();
674 while let Some(tt) = iter.next() {
675 self.print_tt(&tt, convert_dollar_crate);
676 if let Some(next) = iter.peek() {
677 if tt_prepend_space(next, &tt) {
686 header: Option<MacHeader<'_>>,
688 ident: Option<Ident>,
691 convert_dollar_crate: bool,
694 if delim == DelimToken::Brace {
695 self.cbox(INDENT_UNIT);
698 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
699 Some(MacHeader::Keyword(kw)) => self.word(kw),
705 if let Some(ident) = ident {
707 self.print_ident(ident);
710 DelimToken::Brace => {
711 if header.is_some() || has_bang || ident.is_some() {
719 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
722 self.print_tts(tts, convert_dollar_crate);
725 DelimToken::Brace => self.bclose(span),
726 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
730 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
731 self.maybe_print_comment(path.span.lo());
733 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
737 self.print_path_segment(segment, colons_before_params);
741 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
742 if segment.ident.name != kw::PathRoot {
743 self.print_ident(segment.ident);
744 if let Some(ref args) = segment.args {
745 self.print_generic_args(args, colons_before_params);
750 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
752 // Outer-box is consistent.
753 self.cbox(INDENT_UNIT);
754 // Head-box is inconsistent.
755 self.ibox(w.len() + 1);
756 // Keyword that starts the head.
762 fn bopen(&mut self) {
764 self.end(); // Close the head-box.
767 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
768 self.maybe_print_comment(span.hi());
769 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
772 self.end(); // Close the outer-box.
776 fn bclose(&mut self, span: rustc_span::Span) {
777 self.bclose_maybe_open(span, true)
780 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
781 if !self.is_beginning_of_line() {
782 self.break_offset(n, off)
784 if off != 0 && self.last_token().is_hardbreak_tok() {
785 // We do something pretty sketchy here: tuck the nonzero
786 // offset-adjustment we were going to deposit along with the
787 // break into the previous hardbreak.
788 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
794 impl<'a> PrintState<'a> for State<'a> {
795 fn comments(&mut self) -> &mut Option<Comments<'a>> {
799 fn print_ident(&mut self, ident: Ident) {
800 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
801 self.ann.post(self, AnnNode::Ident(&ident))
804 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
805 if colons_before_params {
810 ast::GenericArgs::AngleBracketed(ref data) => {
812 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
813 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
814 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
819 ast::GenericArgs::Parenthesized(ref data) => {
821 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
823 self.print_fn_ret_ty(&data.output);
830 // Synthesizes a comment that was not textually present in the original source
832 pub fn synth_comment(&mut self, text: String) {
840 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
842 F: FnMut(&mut State<'_>, &T),
843 G: FnMut(&T) -> rustc_span::Span,
846 let len = elts.len();
849 self.maybe_print_comment(get_span(elt).hi());
854 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
855 self.space_if_not_bol();
861 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
862 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
865 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
866 self.print_inner_attributes(attrs);
867 for item in &_mod.items {
868 self.print_item(item);
872 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[Attribute]) {
873 self.print_inner_attributes(attrs);
874 for item in &nmod.items {
875 self.print_foreign_item(item);
879 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
880 if let Some(lt) = *lifetime {
881 self.print_lifetime(lt);
886 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
887 self.print_ident(constraint.ident);
889 match &constraint.kind {
890 ast::AssocTyConstraintKind::Equality { ty } => {
891 self.word_space("=");
894 ast::AssocTyConstraintKind::Bound { bounds } => {
895 self.print_type_bounds(":", &*bounds);
900 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
902 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
903 GenericArg::Type(ty) => self.print_type(ty),
904 GenericArg::Const(ct) => self.print_expr(&ct.value),
908 pub fn print_type(&mut self, ty: &ast::Ty) {
909 self.maybe_print_comment(ty.span.lo());
912 ast::TyKind::Slice(ref ty) => {
917 ast::TyKind::Ptr(ref mt) => {
919 self.print_mt(mt, true);
921 ast::TyKind::Rptr(ref lifetime, ref mt) => {
923 self.print_opt_lifetime(lifetime);
924 self.print_mt(mt, false);
926 ast::TyKind::Never => {
929 ast::TyKind::Tup(ref elts) => {
931 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
937 ast::TyKind::Paren(ref typ) => {
939 self.print_type(typ);
942 ast::TyKind::BareFn(ref f) => {
943 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
945 ast::TyKind::Path(None, ref path) => {
946 self.print_path(path, false, 0);
948 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
949 ast::TyKind::TraitObject(ref bounds, syntax) => {
950 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
951 self.print_type_bounds(prefix, &bounds[..]);
953 ast::TyKind::ImplTrait(_, ref bounds) => {
954 self.print_type_bounds("impl", &bounds[..]);
956 ast::TyKind::Array(ref ty, ref length) => {
960 self.print_expr(&length.value);
963 ast::TyKind::Typeof(ref e) => {
964 self.s.word("typeof(");
965 self.print_expr(&e.value);
968 ast::TyKind::Infer => {
971 ast::TyKind::Err => {
973 self.s.word("/*ERROR*/");
976 ast::TyKind::ImplicitSelf => {
979 ast::TyKind::MacCall(ref m) => {
982 ast::TyKind::CVarArgs => {
989 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
990 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
991 self.ann.pre(self, AnnNode::SubItem(id));
992 self.hardbreak_if_not_bol();
993 self.maybe_print_comment(span.lo());
994 self.print_outer_attributes(attrs);
996 ast::ForeignItemKind::Fn(def, sig, gen, body) => {
997 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
999 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1000 let def = ast::Defaultness::Final;
1001 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1003 ast::ForeignItemKind::TyAlias(def, generics, bounds, ty) => {
1004 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1006 ast::ForeignItemKind::MacCall(m) => {
1008 if m.args.need_semicolon() {
1013 self.ann.post(self, AnnNode::SubItem(id))
1016 fn print_item_const(
1019 mutbl: Option<ast::Mutability>,
1021 body: Option<&ast::Expr>,
1022 vis: &ast::Visibility,
1023 defaultness: ast::Defaultness,
1026 self.print_visibility(vis);
1027 self.print_defaultness(defaultness);
1028 let leading = match mutbl {
1030 Some(ast::Mutability::Not) => "static",
1031 Some(ast::Mutability::Mut) => "static mut",
1033 self.word_space(leading);
1034 self.print_ident(ident);
1035 self.word_space(":");
1036 self.print_type(ty);
1038 self.end(); // end the head-ibox
1039 if let Some(body) = body {
1040 self.word_space("=");
1041 self.print_expr(body);
1044 self.end(); // end the outer cbox
1047 fn print_associated_type(
1050 generics: &ast::Generics,
1051 bounds: &ast::GenericBounds,
1052 ty: Option<&ast::Ty>,
1053 vis: &ast::Visibility,
1054 defaultness: ast::Defaultness,
1057 self.print_visibility(vis);
1058 self.print_defaultness(defaultness);
1059 self.word_space("type");
1060 self.print_ident(ident);
1061 self.print_generic_params(&generics.params);
1062 self.print_type_bounds(":", bounds);
1063 self.print_where_clause(&generics.where_clause);
1064 if let Some(ty) = ty {
1066 self.word_space("=");
1067 self.print_type(ty);
1070 self.end(); // end inner head-block
1071 self.end(); // end outer head-block
1074 /// Pretty-prints an item.
1075 crate fn print_item(&mut self, item: &ast::Item) {
1076 self.hardbreak_if_not_bol();
1077 self.maybe_print_comment(item.span.lo());
1078 self.print_outer_attributes(&item.attrs);
1079 self.ann.pre(self, AnnNode::Item(item));
1081 ast::ItemKind::ExternCrate(orig_name) => {
1082 self.head(visibility_qualified(&item.vis, "extern crate"));
1083 if let Some(orig_name) = orig_name {
1084 self.print_name(orig_name);
1089 self.print_ident(item.ident);
1091 self.end(); // end inner head-block
1092 self.end(); // end outer head-block
1094 ast::ItemKind::Use(ref tree) => {
1095 self.head(visibility_qualified(&item.vis, "use"));
1096 self.print_use_tree(tree);
1098 self.end(); // end inner head-block
1099 self.end(); // end outer head-block
1101 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1102 let def = ast::Defaultness::Final;
1103 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1105 ast::ItemKind::Const(def, ref ty, ref body) => {
1106 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1108 ast::ItemKind::Fn(def, ref sig, ref gen, ref body) => {
1109 let body = body.as_deref();
1110 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1112 ast::ItemKind::Mod(ref _mod) => {
1113 self.head(visibility_qualified(&item.vis, "mod"));
1114 self.print_ident(item.ident);
1116 if _mod.inline || self.is_expanded {
1119 self.print_mod(_mod, &item.attrs);
1120 self.bclose(item.span);
1123 self.end(); // end inner head-block
1124 self.end(); // end outer head-block
1127 ast::ItemKind::ForeignMod(ref nmod) => {
1128 self.head("extern");
1129 if let Some(abi) = nmod.abi {
1130 self.print_literal(&abi.as_lit());
1134 self.print_foreign_mod(nmod, &item.attrs);
1135 self.bclose(item.span);
1137 ast::ItemKind::GlobalAsm(ref ga) => {
1138 self.head(visibility_qualified(&item.vis, "global_asm!"));
1139 self.s.word(ga.asm.to_string());
1142 ast::ItemKind::TyAlias(def, ref generics, ref bounds, ref ty) => {
1143 let ty = ty.as_deref();
1144 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1146 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1147 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1149 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1150 self.head(visibility_qualified(&item.vis, "struct"));
1151 self.print_struct(struct_def, generics, item.ident, item.span, true);
1153 ast::ItemKind::Union(ref struct_def, ref generics) => {
1154 self.head(visibility_qualified(&item.vis, "union"));
1155 self.print_struct(struct_def, generics, item.ident, item.span, true);
1157 ast::ItemKind::Impl {
1168 self.print_visibility(&item.vis);
1169 self.print_defaultness(defaultness);
1170 self.print_unsafety(unsafety);
1171 self.word_nbsp("impl");
1172 self.print_constness(constness);
1174 if !generics.params.is_empty() {
1175 self.print_generic_params(&generics.params);
1179 if let ast::ImplPolarity::Negative(_) = polarity {
1183 if let Some(ref t) = *of_trait {
1184 self.print_trait_ref(t);
1186 self.word_space("for");
1189 self.print_type(self_ty);
1190 self.print_where_clause(&generics.where_clause);
1194 self.print_inner_attributes(&item.attrs);
1195 for impl_item in items {
1196 self.print_assoc_item(impl_item);
1198 self.bclose(item.span);
1200 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1202 self.print_visibility(&item.vis);
1203 self.print_unsafety(unsafety);
1204 self.print_is_auto(is_auto);
1205 self.word_nbsp("trait");
1206 self.print_ident(item.ident);
1207 self.print_generic_params(&generics.params);
1208 let mut real_bounds = Vec::with_capacity(bounds.len());
1209 for b in bounds.iter() {
1210 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1212 self.word_space("for ?");
1213 self.print_trait_ref(&ptr.trait_ref);
1215 real_bounds.push(b.clone());
1218 self.print_type_bounds(":", &real_bounds[..]);
1219 self.print_where_clause(&generics.where_clause);
1222 self.print_inner_attributes(&item.attrs);
1223 for trait_item in trait_items {
1224 self.print_assoc_item(trait_item);
1226 self.bclose(item.span);
1228 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1230 self.print_visibility(&item.vis);
1231 self.word_nbsp("trait");
1232 self.print_ident(item.ident);
1233 self.print_generic_params(&generics.params);
1234 let mut real_bounds = Vec::with_capacity(bounds.len());
1235 // FIXME(durka) this seems to be some quite outdated syntax
1236 for b in bounds.iter() {
1237 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1239 self.word_space("for ?");
1240 self.print_trait_ref(&ptr.trait_ref);
1242 real_bounds.push(b.clone());
1246 self.print_type_bounds("=", &real_bounds[..]);
1247 self.print_where_clause(&generics.where_clause);
1250 ast::ItemKind::MacCall(ref mac) => {
1251 self.print_mac(mac);
1252 if mac.args.need_semicolon() {
1256 ast::ItemKind::MacroDef(ref macro_def) => {
1257 let (kw, has_bang) = if macro_def.macro_rules {
1258 ("macro_rules", true)
1260 self.print_visibility(&item.vis);
1263 self.print_mac_common(
1264 Some(MacHeader::Keyword(kw)),
1267 macro_def.body.delim(),
1268 ¯o_def.body.inner_tokens(),
1274 self.ann.post(self, AnnNode::Item(item))
1277 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1278 self.print_path(&t.path, false, 0)
1281 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1282 if !generic_params.is_empty() {
1284 self.print_generic_params(generic_params);
1289 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1290 self.print_formal_generic_params(&t.bound_generic_params);
1291 self.print_trait_ref(&t.trait_ref)
1294 crate fn print_enum_def(
1296 enum_definition: &ast::EnumDef,
1297 generics: &ast::Generics,
1299 span: rustc_span::Span,
1300 visibility: &ast::Visibility,
1302 self.head(visibility_qualified(visibility, "enum"));
1303 self.print_ident(ident);
1304 self.print_generic_params(&generics.params);
1305 self.print_where_clause(&generics.where_clause);
1307 self.print_variants(&enum_definition.variants, span)
1310 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1313 self.space_if_not_bol();
1314 self.maybe_print_comment(v.span.lo());
1315 self.print_outer_attributes(&v.attrs);
1316 self.ibox(INDENT_UNIT);
1317 self.print_variant(v);
1320 self.maybe_print_trailing_comment(v.span, None);
1325 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1327 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1328 ast::VisibilityKind::Crate(sugar) => match sugar {
1329 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1330 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1332 ast::VisibilityKind::Restricted { ref path, .. } => {
1333 let path = to_string(|s| s.print_path(path, false, 0));
1334 if path == "self" || path == "super" {
1335 self.word_nbsp(format!("pub({})", path))
1337 self.word_nbsp(format!("pub(in {})", path))
1340 ast::VisibilityKind::Inherited => {}
1344 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1345 if let ast::Defaultness::Default(_) = defaultness {
1346 self.word_nbsp("default");
1350 crate fn print_struct(
1352 struct_def: &ast::VariantData,
1353 generics: &ast::Generics,
1355 span: rustc_span::Span,
1356 print_finalizer: bool,
1358 self.print_ident(ident);
1359 self.print_generic_params(&generics.params);
1361 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1362 if let ast::VariantData::Tuple(..) = struct_def {
1364 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1365 s.maybe_print_comment(field.span.lo());
1366 s.print_outer_attributes(&field.attrs);
1367 s.print_visibility(&field.vis);
1368 s.print_type(&field.ty)
1372 self.print_where_clause(&generics.where_clause);
1373 if print_finalizer {
1377 self.end(); // Close the outer-box.
1379 ast::VariantData::Struct(..) => {
1380 self.print_where_clause(&generics.where_clause);
1383 self.hardbreak_if_not_bol();
1385 for field in struct_def.fields() {
1386 self.hardbreak_if_not_bol();
1387 self.maybe_print_comment(field.span.lo());
1388 self.print_outer_attributes(&field.attrs);
1389 self.print_visibility(&field.vis);
1390 self.print_ident(field.ident.unwrap());
1391 self.word_nbsp(":");
1392 self.print_type(&field.ty);
1401 crate fn print_variant(&mut self, v: &ast::Variant) {
1403 self.print_visibility(&v.vis);
1404 let generics = ast::Generics::default();
1405 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1406 if let Some(ref d) = v.disr_expr {
1408 self.word_space("=");
1409 self.print_expr(&d.value)
1413 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1414 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1415 self.ann.pre(self, AnnNode::SubItem(id));
1416 self.hardbreak_if_not_bol();
1417 self.maybe_print_comment(span.lo());
1418 self.print_outer_attributes(attrs);
1420 ast::AssocItemKind::Fn(def, sig, gen, body) => {
1421 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1423 ast::AssocItemKind::Const(def, ty, body) => {
1424 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1426 ast::AssocItemKind::TyAlias(def, generics, bounds, ty) => {
1427 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1429 ast::AssocItemKind::MacCall(m) => {
1431 if m.args.need_semicolon() {
1436 self.ann.post(self, AnnNode::SubItem(id))
1439 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1440 self.maybe_print_comment(st.span.lo());
1442 ast::StmtKind::Local(ref loc) => {
1443 self.print_outer_attributes(&loc.attrs);
1444 self.space_if_not_bol();
1445 self.ibox(INDENT_UNIT);
1446 self.word_nbsp("let");
1448 self.ibox(INDENT_UNIT);
1449 self.print_local_decl(loc);
1451 if let Some(ref init) = loc.init {
1453 self.word_space("=");
1454 self.print_expr(init);
1459 ast::StmtKind::Item(ref item) => self.print_item(item),
1460 ast::StmtKind::Expr(ref expr) => {
1461 self.space_if_not_bol();
1462 self.print_expr_outer_attr_style(expr, false);
1463 if classify::expr_requires_semi_to_be_stmt(expr) {
1467 ast::StmtKind::Semi(ref expr) => {
1468 self.space_if_not_bol();
1469 self.print_expr_outer_attr_style(expr, false);
1472 ast::StmtKind::Empty => {
1473 self.space_if_not_bol();
1476 ast::StmtKind::MacCall(ref mac) => {
1477 let (ref mac, style, ref attrs) = **mac;
1478 self.space_if_not_bol();
1479 self.print_outer_attributes(attrs);
1480 self.print_mac(mac);
1481 if style == ast::MacStmtStyle::Semicolon {
1486 self.maybe_print_trailing_comment(st.span, None)
1489 crate fn print_block(&mut self, blk: &ast::Block) {
1490 self.print_block_with_attrs(blk, &[])
1493 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1494 self.print_block_maybe_unclosed(blk, &[], false)
1497 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1498 self.print_block_maybe_unclosed(blk, attrs, true)
1501 crate fn print_block_maybe_unclosed(
1504 attrs: &[ast::Attribute],
1508 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1509 BlockCheckMode::Default => (),
1511 self.maybe_print_comment(blk.span.lo());
1512 self.ann.pre(self, AnnNode::Block(blk));
1515 self.print_inner_attributes(attrs);
1517 for (i, st) in blk.stmts.iter().enumerate() {
1519 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1520 self.maybe_print_comment(st.span.lo());
1521 self.space_if_not_bol();
1522 self.print_expr_outer_attr_style(expr, false);
1523 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1525 _ => self.print_stmt(st),
1529 self.bclose_maybe_open(blk.span, close_box);
1530 self.ann.post(self, AnnNode::Block(blk))
1533 /// Print a `let pat = scrutinee` expression.
1534 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1535 self.s.word("let ");
1537 self.print_pat(pat);
1540 self.word_space("=");
1541 self.print_expr_cond_paren(
1543 Self::cond_needs_par(scrutinee)
1544 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1548 fn print_else(&mut self, els: Option<&ast::Expr>) {
1549 if let Some(_else) = els {
1551 // Another `else if` block.
1552 ast::ExprKind::If(ref i, ref then, ref e) => {
1553 self.cbox(INDENT_UNIT - 1);
1555 self.s.word(" else if ");
1556 self.print_expr_as_cond(i);
1558 self.print_block(then);
1559 self.print_else(e.as_deref())
1561 // Final `else` block.
1562 ast::ExprKind::Block(ref b, _) => {
1563 self.cbox(INDENT_UNIT - 1);
1565 self.s.word(" else ");
1568 // Constraints would be great here!
1570 panic!("print_if saw if with weird alternative");
1576 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1579 self.print_expr_as_cond(test);
1582 self.print_block(blk);
1583 self.print_else(elseopt)
1586 crate fn print_mac(&mut self, m: &ast::MacCall) {
1587 self.print_mac_common(
1588 Some(MacHeader::Path(&m.path)),
1592 &m.args.inner_tokens(),
1598 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1600 self.commasep_exprs(Inconsistent, args);
1604 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1605 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1608 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1609 /// `if cond { ... }`.
1610 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1611 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1614 /// Does `expr` need parenthesis when printed in a condition position?
1615 fn cond_needs_par(expr: &ast::Expr) -> bool {
1617 // These cases need parens due to the parse error observed in #26461: `if return {}`
1618 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1619 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1621 _ => parser::contains_exterior_struct_lit(expr),
1625 /// Prints `expr` or `(expr)` when `needs_par` holds.
1626 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1630 self.print_expr(expr);
1636 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1637 self.ibox(INDENT_UNIT);
1639 self.print_inner_attributes_inline(attrs);
1640 self.commasep_exprs(Inconsistent, &exprs[..]);
1645 fn print_expr_repeat(
1647 element: &ast::Expr,
1648 count: &ast::AnonConst,
1649 attrs: &[Attribute],
1651 self.ibox(INDENT_UNIT);
1653 self.print_inner_attributes_inline(attrs);
1654 self.print_expr(element);
1655 self.word_space(";");
1656 self.print_expr(&count.value);
1661 fn print_expr_struct(
1664 fields: &[ast::Field],
1665 wth: &Option<P<ast::Expr>>,
1666 attrs: &[Attribute],
1668 self.print_path(path, true, 0);
1670 self.print_inner_attributes_inline(attrs);
1675 s.print_outer_attributes(&field.attrs);
1676 s.ibox(INDENT_UNIT);
1677 if !field.is_shorthand {
1678 s.print_ident(field.ident);
1681 s.print_expr(&field.expr);
1688 self.ibox(INDENT_UNIT);
1689 if !fields.is_empty() {
1694 self.print_expr(expr);
1698 if !fields.is_empty() {
1706 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1708 self.print_inner_attributes_inline(attrs);
1709 self.commasep_exprs(Inconsistent, &exprs[..]);
1710 if exprs.len() == 1 {
1716 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1717 let prec = match func.kind {
1718 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1719 _ => parser::PREC_POSTFIX,
1722 self.print_expr_maybe_paren(func, prec);
1723 self.print_call_post(args)
1726 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1727 let base_args = &args[1..];
1728 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1730 self.print_ident(segment.ident);
1731 if let Some(ref args) = segment.args {
1732 self.print_generic_args(args, true);
1734 self.print_call_post(base_args)
1737 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1738 let assoc_op = AssocOp::from_ast_binop(op.node);
1739 let prec = assoc_op.precedence() as i8;
1740 let fixity = assoc_op.fixity();
1742 let (left_prec, right_prec) = match fixity {
1743 Fixity::Left => (prec, prec + 1),
1744 Fixity::Right => (prec + 1, prec),
1745 Fixity::None => (prec + 1, prec + 1),
1748 let left_prec = match (&lhs.kind, op.node) {
1749 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1750 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1751 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1752 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1753 parser::PREC_FORCE_PAREN
1755 // We are given `(let _ = a) OP b`.
1757 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1758 // as the parser will interpret this as `(let _ = a) OP b`.
1760 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1761 // parens are required since the parser would interpret `let a = b < c` as
1762 // `let a = (b < c)`. To achieve this, we force parens.
1763 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1764 parser::PREC_FORCE_PAREN
1769 self.print_expr_maybe_paren(lhs, left_prec);
1771 self.word_space(op.node.to_string());
1772 self.print_expr_maybe_paren(rhs, right_prec)
1775 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1776 self.s.word(ast::UnOp::to_string(op));
1777 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1780 fn print_expr_addr_of(
1782 kind: ast::BorrowKind,
1783 mutability: ast::Mutability,
1788 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1789 ast::BorrowKind::Raw => {
1790 self.word_nbsp("raw");
1791 self.print_mutability(mutability, true);
1794 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1797 pub fn print_expr(&mut self, expr: &ast::Expr) {
1798 self.print_expr_outer_attr_style(expr, true)
1801 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1802 self.maybe_print_comment(expr.span.lo());
1804 let attrs = &expr.attrs;
1806 self.print_outer_attributes_inline(attrs);
1808 self.print_outer_attributes(attrs);
1811 self.ibox(INDENT_UNIT);
1812 self.ann.pre(self, AnnNode::Expr(expr));
1814 ast::ExprKind::Box(ref expr) => {
1815 self.word_space("box");
1816 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1818 ast::ExprKind::Array(ref exprs) => {
1819 self.print_expr_vec(&exprs[..], attrs);
1821 ast::ExprKind::Repeat(ref element, ref count) => {
1822 self.print_expr_repeat(element, count, attrs);
1824 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1825 self.print_expr_struct(path, &fields[..], wth, attrs);
1827 ast::ExprKind::Tup(ref exprs) => {
1828 self.print_expr_tup(&exprs[..], attrs);
1830 ast::ExprKind::Call(ref func, ref args) => {
1831 self.print_expr_call(func, &args[..]);
1833 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1834 self.print_expr_method_call(segment, &args[..]);
1836 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1837 self.print_expr_binary(op, lhs, rhs);
1839 ast::ExprKind::Unary(op, ref expr) => {
1840 self.print_expr_unary(op, expr);
1842 ast::ExprKind::AddrOf(k, m, ref expr) => {
1843 self.print_expr_addr_of(k, m, expr);
1845 ast::ExprKind::Lit(ref lit) => {
1846 self.print_literal(lit);
1848 ast::ExprKind::Cast(ref expr, ref ty) => {
1849 let prec = AssocOp::As.precedence() as i8;
1850 self.print_expr_maybe_paren(expr, prec);
1852 self.word_space("as");
1853 self.print_type(ty);
1855 ast::ExprKind::Type(ref expr, ref ty) => {
1856 let prec = AssocOp::Colon.precedence() as i8;
1857 self.print_expr_maybe_paren(expr, prec);
1858 self.word_space(":");
1859 self.print_type(ty);
1861 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1862 self.print_let(pat, scrutinee);
1864 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1865 self.print_if(test, blk, elseopt.as_deref())
1867 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1868 if let Some(label) = opt_label {
1869 self.print_ident(label.ident);
1870 self.word_space(":");
1873 self.print_expr_as_cond(test);
1875 self.print_block_with_attrs(blk, attrs);
1877 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1878 if let Some(label) = opt_label {
1879 self.print_ident(label.ident);
1880 self.word_space(":");
1883 self.print_pat(pat);
1885 self.word_space("in");
1886 self.print_expr_as_cond(iter);
1888 self.print_block_with_attrs(blk, attrs);
1890 ast::ExprKind::Loop(ref blk, opt_label) => {
1891 if let Some(label) = opt_label {
1892 self.print_ident(label.ident);
1893 self.word_space(":");
1897 self.print_block_with_attrs(blk, attrs);
1899 ast::ExprKind::Match(ref expr, ref arms) => {
1900 self.cbox(INDENT_UNIT);
1901 self.ibox(INDENT_UNIT);
1902 self.word_nbsp("match");
1903 self.print_expr_as_cond(expr);
1906 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1908 self.print_arm(arm);
1910 self.bclose(expr.span);
1912 ast::ExprKind::Closure(
1920 self.print_movability(movability);
1921 self.print_asyncness(asyncness);
1922 self.print_capture_clause(capture_clause);
1924 self.print_fn_params_and_ret(decl, true);
1926 self.print_expr(body);
1927 self.end(); // need to close a box
1929 // a box will be closed by print_expr, but we didn't want an overall
1930 // wrapper so we closed the corresponding opening. so create an
1931 // empty box to satisfy the close.
1934 ast::ExprKind::Block(ref blk, opt_label) => {
1935 if let Some(label) = opt_label {
1936 self.print_ident(label.ident);
1937 self.word_space(":");
1939 // containing cbox, will be closed by print-block at }
1940 self.cbox(INDENT_UNIT);
1941 // head-box, will be closed by print-block after {
1943 self.print_block_with_attrs(blk, attrs);
1945 ast::ExprKind::Async(capture_clause, _, ref blk) => {
1946 self.word_nbsp("async");
1947 self.print_capture_clause(capture_clause);
1949 // cbox/ibox in analogy to the `ExprKind::Block` arm above
1950 self.cbox(INDENT_UNIT);
1952 self.print_block_with_attrs(blk, attrs);
1954 ast::ExprKind::Await(ref expr) => {
1955 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1956 self.s.word(".await");
1958 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
1959 let prec = AssocOp::Assign.precedence() as i8;
1960 self.print_expr_maybe_paren(lhs, prec + 1);
1962 self.word_space("=");
1963 self.print_expr_maybe_paren(rhs, prec);
1965 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1966 let prec = AssocOp::Assign.precedence() as i8;
1967 self.print_expr_maybe_paren(lhs, prec + 1);
1969 self.s.word(op.node.to_string());
1970 self.word_space("=");
1971 self.print_expr_maybe_paren(rhs, prec);
1973 ast::ExprKind::Field(ref expr, ident) => {
1974 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1976 self.print_ident(ident);
1978 ast::ExprKind::Index(ref expr, ref index) => {
1979 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1981 self.print_expr(index);
1984 ast::ExprKind::Range(ref start, ref end, limits) => {
1985 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
1986 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
1987 // Here we use a fake precedence value so that any child with lower precedence than
1988 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
1989 let fake_prec = AssocOp::LOr.precedence() as i8;
1990 if let Some(ref e) = *start {
1991 self.print_expr_maybe_paren(e, fake_prec);
1993 if limits == ast::RangeLimits::HalfOpen {
1998 if let Some(ref e) = *end {
1999 self.print_expr_maybe_paren(e, fake_prec);
2002 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2003 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2004 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2005 self.s.word("break");
2007 if let Some(label) = opt_label {
2008 self.print_ident(label.ident);
2011 if let Some(ref expr) = *opt_expr {
2012 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2016 ast::ExprKind::Continue(opt_label) => {
2017 self.s.word("continue");
2019 if let Some(label) = opt_label {
2020 self.print_ident(label.ident);
2024 ast::ExprKind::Ret(ref result) => {
2025 self.s.word("return");
2026 if let Some(ref expr) = *result {
2028 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2031 ast::ExprKind::InlineAsm(ref a) => {
2034 Operand(&'a InlineAsmOperand),
2035 Options(InlineAsmOptions),
2038 let mut args = vec![];
2039 args.push(AsmArg::Template(InlineAsmTemplatePiece::to_string(&a.template)));
2040 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2041 if !a.options.is_empty() {
2042 args.push(AsmArg::Options(a.options));
2047 self.commasep(Consistent, &args, |s, arg| match arg {
2048 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2049 AsmArg::Operand(op) => {
2050 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r
2052 InlineAsmRegOrRegClass::Reg(r) => {
2053 s.print_string(&r.as_str(), ast::StrStyle::Cooked)
2055 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2058 InlineAsmOperand::In { reg, expr } => {
2061 print_reg_or_class(s, reg);
2066 InlineAsmOperand::Out { reg, late, expr } => {
2067 s.word(if *late { "lateout" } else { "out" });
2069 print_reg_or_class(s, reg);
2073 Some(expr) => s.print_expr(expr),
2074 None => s.word("_"),
2077 InlineAsmOperand::InOut { reg, late, expr } => {
2078 s.word(if *late { "inlateout" } else { "inout" });
2080 print_reg_or_class(s, reg);
2085 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2086 s.word(if *late { "inlateout" } else { "inout" });
2088 print_reg_or_class(s, reg);
2091 s.print_expr(in_expr);
2095 Some(out_expr) => s.print_expr(out_expr),
2096 None => s.word("_"),
2099 InlineAsmOperand::Const { expr } => {
2104 InlineAsmOperand::Sym { expr } => {
2111 AsmArg::Options(opts) => {
2114 let mut options = vec![];
2115 if opts.contains(InlineAsmOptions::PURE) {
2116 options.push("pure");
2118 if opts.contains(InlineAsmOptions::NOMEM) {
2119 options.push("nomem");
2121 if opts.contains(InlineAsmOptions::READONLY) {
2122 options.push("readonly");
2124 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2125 options.push("preserves_flags");
2127 if opts.contains(InlineAsmOptions::NORETURN) {
2128 options.push("noreturn");
2130 if opts.contains(InlineAsmOptions::NOSTACK) {
2131 options.push("nostack");
2133 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2134 options.push("att_syntax");
2136 s.commasep(Inconsistent, &options, |s, &opt| {
2144 ast::ExprKind::LlvmInlineAsm(ref a) => {
2145 self.s.word("llvm_asm!");
2147 self.print_string(&a.asm.as_str(), a.asm_str_style);
2148 self.word_space(":");
2150 self.commasep(Inconsistent, &a.outputs, |s, out| {
2151 let constraint = out.constraint.as_str();
2152 let mut ch = constraint.chars();
2154 Some('=') if out.is_rw => {
2155 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2157 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2160 s.print_expr(&out.expr);
2164 self.word_space(":");
2166 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2167 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2173 self.word_space(":");
2175 self.commasep(Inconsistent, &a.clobbers, |s, co| {
2176 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2179 let mut options = vec![];
2181 options.push("volatile");
2184 options.push("alignstack");
2186 if a.dialect == ast::LlvmAsmDialect::Intel {
2187 options.push("intel");
2190 if !options.is_empty() {
2192 self.word_space(":");
2193 self.commasep(Inconsistent, &options, |s, &co| {
2194 s.print_string(co, ast::StrStyle::Cooked);
2200 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2201 ast::ExprKind::Paren(ref e) => {
2203 self.print_inner_attributes_inline(attrs);
2207 ast::ExprKind::Yield(ref e) => {
2208 self.s.word("yield");
2210 if let Some(ref expr) = *e {
2212 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2215 ast::ExprKind::Try(ref e) => {
2216 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2219 ast::ExprKind::TryBlock(ref blk) => {
2222 self.print_block_with_attrs(blk, attrs)
2224 ast::ExprKind::Err => {
2226 self.s.word("/*ERROR*/");
2230 self.ann.post(self, AnnNode::Expr(expr));
2234 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2235 self.print_pat(&loc.pat);
2236 if let Some(ref ty) = loc.ty {
2237 self.word_space(":");
2238 self.print_type(ty);
2242 pub fn print_usize(&mut self, i: usize) {
2243 self.s.word(i.to_string())
2246 crate fn print_name(&mut self, name: Symbol) {
2247 self.s.word(name.to_string());
2248 self.ann.post(self, AnnNode::Name(&name))
2251 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2253 self.print_type(&qself.ty);
2254 if qself.position > 0 {
2256 self.word_space("as");
2257 let depth = path.segments.len() - qself.position;
2258 self.print_path(path, false, depth);
2262 let item_segment = path.segments.last().unwrap();
2263 self.print_ident(item_segment.ident);
2264 if let Some(ref args) = item_segment.args {
2265 self.print_generic_args(args, colons_before_params)
2269 crate fn print_pat(&mut self, pat: &ast::Pat) {
2270 self.maybe_print_comment(pat.span.lo());
2271 self.ann.pre(self, AnnNode::Pat(pat));
2272 /* Pat isn't normalized, but the beauty of it
2273 is that it doesn't matter */
2275 PatKind::Wild => self.s.word("_"),
2276 PatKind::Ident(binding_mode, ident, ref sub) => {
2277 match binding_mode {
2278 ast::BindingMode::ByRef(mutbl) => {
2279 self.word_nbsp("ref");
2280 self.print_mutability(mutbl, false);
2282 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2283 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2284 self.word_nbsp("mut");
2287 self.print_ident(ident);
2288 if let Some(ref p) = *sub {
2290 self.s.word_space("@");
2294 PatKind::TupleStruct(ref path, ref elts) => {
2295 self.print_path(path, true, 0);
2297 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2300 PatKind::Or(ref pats) => {
2301 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2303 PatKind::Path(None, ref path) => {
2304 self.print_path(path, true, 0);
2306 PatKind::Path(Some(ref qself), ref path) => {
2307 self.print_qpath(path, qself, false);
2309 PatKind::Struct(ref path, ref fields, etc) => {
2310 self.print_path(path, true, 0);
2312 self.word_space("{");
2317 s.cbox(INDENT_UNIT);
2318 if !f.is_shorthand {
2319 s.print_ident(f.ident);
2322 s.print_pat(&f.pat);
2328 if !fields.is_empty() {
2329 self.word_space(",");
2336 PatKind::Tuple(ref elts) => {
2338 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2339 if elts.len() == 1 {
2344 PatKind::Box(ref inner) => {
2345 self.s.word("box ");
2346 self.print_pat(inner);
2348 PatKind::Ref(ref inner, mutbl) => {
2350 if mutbl == ast::Mutability::Mut {
2351 self.s.word("mut ");
2353 self.print_pat(inner);
2355 PatKind::Lit(ref e) => self.print_expr(&**e),
2356 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2357 if let Some(e) = begin {
2362 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2363 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2364 RangeEnd::Excluded => self.s.word(".."),
2366 if let Some(e) = end {
2370 PatKind::Slice(ref elts) => {
2372 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2375 PatKind::Rest => self.s.word(".."),
2376 PatKind::Paren(ref inner) => {
2378 self.print_pat(inner);
2381 PatKind::MacCall(ref m) => self.print_mac(m),
2383 self.ann.post(self, AnnNode::Pat(pat))
2386 fn print_arm(&mut self, arm: &ast::Arm) {
2387 // Note, I have no idea why this check is necessary, but here it is.
2388 if arm.attrs.is_empty() {
2391 self.cbox(INDENT_UNIT);
2393 self.maybe_print_comment(arm.pat.span.lo());
2394 self.print_outer_attributes(&arm.attrs);
2395 self.print_pat(&arm.pat);
2397 if let Some(ref e) = arm.guard {
2398 self.word_space("if");
2402 self.word_space("=>");
2404 match arm.body.kind {
2405 ast::ExprKind::Block(ref blk, opt_label) => {
2406 if let Some(label) = opt_label {
2407 self.print_ident(label.ident);
2408 self.word_space(":");
2411 // The block will close the pattern's ibox.
2412 self.print_block_unclosed_indent(blk);
2414 // If it is a user-provided unsafe block, print a comma after it.
2415 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2420 self.end(); // Close the ibox for the pattern.
2421 self.print_expr(&arm.body);
2425 self.end(); // Close enclosing cbox.
2428 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2429 match explicit_self.node {
2430 SelfKind::Value(m) => {
2431 self.print_mutability(m, false);
2434 SelfKind::Region(ref lt, m) => {
2436 self.print_opt_lifetime(lt);
2437 self.print_mutability(m, false);
2440 SelfKind::Explicit(ref typ, m) => {
2441 self.print_mutability(m, false);
2442 self.s.word("self");
2443 self.word_space(":");
2444 self.print_type(typ)
2453 generics: &ast::Generics,
2454 vis: &ast::Visibility,
2455 defaultness: ast::Defaultness,
2456 body: Option<&ast::Block>,
2457 attrs: &[ast::Attribute],
2462 self.print_visibility(vis);
2463 self.print_defaultness(defaultness);
2464 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2465 if let Some(body) = body {
2467 self.print_block_with_attrs(body, attrs);
2476 header: ast::FnHeader,
2477 name: Option<Ident>,
2478 generics: &ast::Generics,
2480 self.print_fn_header_info(header);
2481 if let Some(name) = name {
2483 self.print_ident(name);
2485 self.print_generic_params(&generics.params);
2486 self.print_fn_params_and_ret(decl, false);
2487 self.print_where_clause(&generics.where_clause)
2490 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2491 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2493 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2495 self.print_fn_ret_ty(&decl.output)
2498 crate fn print_movability(&mut self, movability: ast::Movability) {
2500 ast::Movability::Static => self.word_space("static"),
2501 ast::Movability::Movable => {}
2505 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2506 if asyncness.is_async() {
2507 self.word_nbsp("async");
2511 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2512 match capture_clause {
2513 ast::CaptureBy::Value => self.word_space("move"),
2514 ast::CaptureBy::Ref => {}
2518 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2519 if !bounds.is_empty() {
2520 self.s.word(prefix);
2521 let mut first = true;
2522 for bound in bounds {
2523 if !(first && prefix.is_empty()) {
2529 self.word_space("+");
2533 GenericBound::Trait(tref, modifier) => {
2534 if modifier == &TraitBoundModifier::Maybe {
2537 self.print_poly_trait_ref(tref);
2539 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2545 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2546 self.print_name(lifetime.ident.name)
2549 crate fn print_lifetime_bounds(
2551 lifetime: ast::Lifetime,
2552 bounds: &ast::GenericBounds,
2554 self.print_lifetime(lifetime);
2555 if !bounds.is_empty() {
2557 for (i, bound) in bounds.iter().enumerate() {
2562 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2569 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2570 if generic_params.is_empty() {
2576 self.commasep(Inconsistent, &generic_params, |s, param| {
2577 s.print_outer_attributes_inline(¶m.attrs);
2580 ast::GenericParamKind::Lifetime => {
2581 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2582 s.print_lifetime_bounds(lt, ¶m.bounds)
2584 ast::GenericParamKind::Type { ref default } => {
2585 s.print_ident(param.ident);
2586 s.print_type_bounds(":", ¶m.bounds);
2587 if let Some(ref default) = default {
2590 s.print_type(default)
2593 ast::GenericParamKind::Const { ref ty, kw_span: _ } => {
2594 s.word_space("const");
2595 s.print_ident(param.ident);
2599 s.print_type_bounds(":", ¶m.bounds)
2607 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2608 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2613 self.word_space("where");
2615 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2617 self.word_space(",");
2621 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2622 ref bound_generic_params,
2627 self.print_formal_generic_params(bound_generic_params);
2628 self.print_type(bounded_ty);
2629 self.print_type_bounds(":", bounds);
2631 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2636 self.print_lifetime_bounds(*lifetime, bounds);
2638 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2643 self.print_type(lhs_ty);
2645 self.word_space("=");
2646 self.print_type(rhs_ty);
2652 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2654 ast::UseTreeKind::Simple(rename, ..) => {
2655 self.print_path(&tree.prefix, false, 0);
2656 if let Some(rename) = rename {
2658 self.word_space("as");
2659 self.print_ident(rename);
2662 ast::UseTreeKind::Glob => {
2663 if !tree.prefix.segments.is_empty() {
2664 self.print_path(&tree.prefix, false, 0);
2669 ast::UseTreeKind::Nested(ref items) => {
2670 if tree.prefix.segments.is_empty() {
2673 self.print_path(&tree.prefix, false, 0);
2676 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2677 this.print_use_tree(tree)
2684 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2686 ast::Mutability::Mut => self.word_nbsp("mut"),
2687 ast::Mutability::Not => {
2689 self.word_nbsp("const");
2695 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2696 self.print_mutability(mt.mutbl, print_const);
2697 self.print_type(&mt.ty)
2700 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2701 self.ibox(INDENT_UNIT);
2703 self.print_outer_attributes_inline(&input.attrs);
2705 match input.ty.kind {
2706 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2708 if let Some(eself) = input.to_self() {
2709 self.print_explicit_self(&eself);
2711 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2712 ident.name == kw::Invalid
2717 self.print_pat(&input.pat);
2721 self.print_type(&input.ty);
2728 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2729 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2730 self.space_if_not_bol();
2731 self.ibox(INDENT_UNIT);
2732 self.word_space("->");
2733 self.print_type(ty);
2735 self.maybe_print_comment(ty.span.lo());
2739 crate fn print_ty_fn(
2742 unsafety: ast::Unsafe,
2744 name: Option<Ident>,
2745 generic_params: &[ast::GenericParam],
2747 self.ibox(INDENT_UNIT);
2748 if !generic_params.is_empty() {
2750 self.print_generic_params(generic_params);
2752 let generics = ast::Generics {
2754 where_clause: ast::WhereClause {
2755 has_where_token: false,
2756 predicates: Vec::new(),
2757 span: rustc_span::DUMMY_SP,
2759 span: rustc_span::DUMMY_SP,
2761 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2762 self.print_fn(decl, header, name, &generics);
2766 crate fn maybe_print_trailing_comment(
2768 span: rustc_span::Span,
2769 next_pos: Option<BytePos>,
2771 if let Some(cmnts) = self.comments() {
2772 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2773 self.print_comment(&cmnt);
2778 crate fn print_remaining_comments(&mut self) {
2779 // If there aren't any remaining comments, then we need to manually
2780 // make sure there is a line break at the end.
2781 if self.next_comment().is_none() {
2784 while let Some(ref cmnt) = self.next_comment() {
2785 self.print_comment(cmnt);
2789 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2790 self.print_constness(header.constness);
2791 self.print_asyncness(header.asyncness);
2792 self.print_unsafety(header.unsafety);
2795 ast::Extern::None => {}
2796 ast::Extern::Implicit => {
2797 self.word_nbsp("extern");
2799 ast::Extern::Explicit(abi) => {
2800 self.word_nbsp("extern");
2801 self.print_literal(&abi.as_lit());
2809 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2811 ast::Unsafe::No => {}
2812 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2816 crate fn print_constness(&mut self, s: ast::Const) {
2818 ast::Const::No => {}
2819 ast::Const::Yes(_) => self.word_nbsp("const"),
2823 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2825 ast::IsAuto::Yes => self.word_nbsp("auto"),
2826 ast::IsAuto::No => {}