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) {
454 if let Some((last, lines)) = cmnt.lines.split_last() {
458 self.word(line.clone());
462 self.word(last.clone());
469 comments::Isolated => {
470 self.hardbreak_if_not_bol();
471 for line in &cmnt.lines {
472 // Don't print empty lines because they will end up as trailing
474 if !line.is_empty() {
475 self.word(line.clone());
480 comments::Trailing => {
481 if !self.is_beginning_of_line() {
484 if cmnt.lines.len() == 1 {
485 self.word(cmnt.lines[0].clone());
489 for line in &cmnt.lines {
490 if !line.is_empty() {
491 self.word(line.clone());
498 comments::BlankLine => {
499 // We need to do at least one, possibly two hardbreaks.
500 let twice = match self.last_token() {
501 pp::Token::String(s) => ";" == s,
502 pp::Token::Begin(_) => true,
503 pp::Token::End => true,
512 if let Some(cmnts) = self.comments() {
517 fn next_comment(&mut self) -> Option<comments::Comment> {
518 self.comments().as_mut().and_then(|c| c.next())
521 fn print_literal(&mut self, lit: &ast::Lit) {
522 self.maybe_print_comment(lit.span.lo());
523 self.word(lit.token.to_string())
526 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
527 let st = match style {
528 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
529 ast::StrStyle::Raw(n) => {
530 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
536 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
537 self.print_string(&sym.as_str(), style);
540 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
541 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
544 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
545 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
548 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
549 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
552 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
553 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
556 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
557 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
560 fn print_either_attributes(
562 attrs: &[ast::Attribute],
563 kind: ast::AttrStyle,
565 trailing_hardbreak: bool,
569 if attr.style == kind {
570 self.print_attribute_inline(attr, is_inline);
577 if count > 0 && trailing_hardbreak && !is_inline {
578 self.hardbreak_if_not_bol();
582 fn print_attribute(&mut self, attr: &ast::Attribute) {
583 self.print_attribute_inline(attr, false)
586 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
588 self.hardbreak_if_not_bol();
590 self.maybe_print_comment(attr.span.lo());
592 ast::AttrKind::Normal(ref item) => {
594 ast::AttrStyle::Inner => self.word("#!["),
595 ast::AttrStyle::Outer => self.word("#["),
597 self.print_attr_item(&item, attr.span);
600 ast::AttrKind::DocComment(comment) => {
601 self.word(comment.to_string());
607 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
610 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
611 Some(MacHeader::Path(&item.path)),
619 MacArgs::Empty | MacArgs::Eq(..) => {
620 self.print_path(&item.path, false, 0);
621 if let MacArgs::Eq(_, tokens) = &item.args {
623 self.word_space("=");
624 self.print_tts(tokens, true);
631 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
633 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
634 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
638 fn print_meta_item(&mut self, item: &ast::MetaItem) {
639 self.ibox(INDENT_UNIT);
641 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
642 ast::MetaItemKind::NameValue(ref value) => {
643 self.print_path(&item.path, false, 0);
645 self.word_space("=");
646 self.print_literal(value);
648 ast::MetaItemKind::List(ref items) => {
649 self.print_path(&item.path, false, 0);
651 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
658 /// This doesn't deserve to be called "pretty" printing, but it should be
659 /// meaning-preserving. A quick hack that might help would be to look at the
660 /// spans embedded in the TTs to decide where to put spaces and newlines.
661 /// But it'd be better to parse these according to the grammar of the
662 /// appropriate macro, transcribe back into the grammar we just parsed from,
663 /// and then pretty-print the resulting AST nodes (so, e.g., we print
664 /// expression arguments as expressions). It can be done! I think.
665 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
667 TokenTree::Token(token) => {
668 self.word(token_to_string_ext(&token, convert_dollar_crate));
669 if let token::DocComment(..) = token.kind {
673 TokenTree::Delimited(dspan, delim, tts) => {
674 self.print_mac_common(
680 convert_dollar_crate,
687 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
688 let mut iter = tts.trees().peekable();
689 while let Some(tt) = iter.next() {
690 self.print_tt(&tt, convert_dollar_crate);
691 if let Some(next) = iter.peek() {
692 if tt_prepend_space(next, &tt) {
701 header: Option<MacHeader<'_>>,
703 ident: Option<Ident>,
706 convert_dollar_crate: bool,
709 if delim == DelimToken::Brace {
710 self.cbox(INDENT_UNIT);
713 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
714 Some(MacHeader::Keyword(kw)) => self.word(kw),
720 if let Some(ident) = ident {
722 self.print_ident(ident);
725 DelimToken::Brace => {
726 if header.is_some() || has_bang || ident.is_some() {
734 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
737 self.print_tts(tts, convert_dollar_crate);
740 DelimToken::Brace => self.bclose(span),
741 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
745 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
746 self.maybe_print_comment(path.span.lo());
748 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
752 self.print_path_segment(segment, colons_before_params);
756 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
757 if segment.ident.name != kw::PathRoot {
758 self.print_ident(segment.ident);
759 if let Some(ref args) = segment.args {
760 self.print_generic_args(args, colons_before_params);
765 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
767 // Outer-box is consistent.
768 self.cbox(INDENT_UNIT);
769 // Head-box is inconsistent.
770 self.ibox(w.len() + 1);
771 // Keyword that starts the head.
777 fn bopen(&mut self) {
779 self.end(); // Close the head-box.
782 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
783 self.maybe_print_comment(span.hi());
784 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
787 self.end(); // Close the outer-box.
791 fn bclose(&mut self, span: rustc_span::Span) {
792 self.bclose_maybe_open(span, true)
795 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
796 if !self.is_beginning_of_line() {
797 self.break_offset(n, off)
799 if off != 0 && self.last_token().is_hardbreak_tok() {
800 // We do something pretty sketchy here: tuck the nonzero
801 // offset-adjustment we were going to deposit along with the
802 // break into the previous hardbreak.
803 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
809 impl<'a> PrintState<'a> for State<'a> {
810 fn comments(&mut self) -> &mut Option<Comments<'a>> {
814 fn print_ident(&mut self, ident: Ident) {
815 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
816 self.ann.post(self, AnnNode::Ident(&ident))
819 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
820 if colons_before_params {
825 ast::GenericArgs::AngleBracketed(ref data) => {
827 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
828 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
829 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
834 ast::GenericArgs::Parenthesized(ref data) => {
836 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
838 self.print_fn_ret_ty(&data.output);
845 // Synthesizes a comment that was not textually present in the original source
847 pub fn synth_comment(&mut self, text: String) {
855 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
857 F: FnMut(&mut State<'_>, &T),
858 G: FnMut(&T) -> rustc_span::Span,
861 let len = elts.len();
864 self.maybe_print_comment(get_span(elt).hi());
869 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
870 self.space_if_not_bol();
876 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
877 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
880 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
881 self.print_inner_attributes(attrs);
882 for item in &_mod.items {
883 self.print_item(item);
887 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[Attribute]) {
888 self.print_inner_attributes(attrs);
889 for item in &nmod.items {
890 self.print_foreign_item(item);
894 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
895 if let Some(lt) = *lifetime {
896 self.print_lifetime(lt);
901 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
902 self.print_ident(constraint.ident);
904 match &constraint.kind {
905 ast::AssocTyConstraintKind::Equality { ty } => {
906 self.word_space("=");
909 ast::AssocTyConstraintKind::Bound { bounds } => {
910 self.print_type_bounds(":", &*bounds);
915 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
917 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
918 GenericArg::Type(ty) => self.print_type(ty),
919 GenericArg::Const(ct) => self.print_expr(&ct.value),
923 pub fn print_type(&mut self, ty: &ast::Ty) {
924 self.maybe_print_comment(ty.span.lo());
927 ast::TyKind::Slice(ref ty) => {
932 ast::TyKind::Ptr(ref mt) => {
934 self.print_mt(mt, true);
936 ast::TyKind::Rptr(ref lifetime, ref mt) => {
938 self.print_opt_lifetime(lifetime);
939 self.print_mt(mt, false);
941 ast::TyKind::Never => {
944 ast::TyKind::Tup(ref elts) => {
946 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
952 ast::TyKind::Paren(ref typ) => {
954 self.print_type(typ);
957 ast::TyKind::BareFn(ref f) => {
958 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
960 ast::TyKind::Path(None, ref path) => {
961 self.print_path(path, false, 0);
963 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
964 ast::TyKind::TraitObject(ref bounds, syntax) => {
965 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
966 self.print_type_bounds(prefix, &bounds[..]);
968 ast::TyKind::ImplTrait(_, ref bounds) => {
969 self.print_type_bounds("impl", &bounds[..]);
971 ast::TyKind::Array(ref ty, ref length) => {
975 self.print_expr(&length.value);
978 ast::TyKind::Typeof(ref e) => {
979 self.s.word("typeof(");
980 self.print_expr(&e.value);
983 ast::TyKind::Infer => {
986 ast::TyKind::Err => {
988 self.s.word("/*ERROR*/");
991 ast::TyKind::ImplicitSelf => {
994 ast::TyKind::MacCall(ref m) => {
997 ast::TyKind::CVarArgs => {
1004 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1005 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1006 self.ann.pre(self, AnnNode::SubItem(id));
1007 self.hardbreak_if_not_bol();
1008 self.maybe_print_comment(span.lo());
1009 self.print_outer_attributes(attrs);
1011 ast::ForeignItemKind::Fn(def, sig, gen, body) => {
1012 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1014 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1015 let def = ast::Defaultness::Final;
1016 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1018 ast::ForeignItemKind::TyAlias(def, generics, bounds, ty) => {
1019 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1021 ast::ForeignItemKind::MacCall(m) => {
1023 if m.args.need_semicolon() {
1028 self.ann.post(self, AnnNode::SubItem(id))
1031 fn print_item_const(
1034 mutbl: Option<ast::Mutability>,
1036 body: Option<&ast::Expr>,
1037 vis: &ast::Visibility,
1038 defaultness: ast::Defaultness,
1041 self.print_visibility(vis);
1042 self.print_defaultness(defaultness);
1043 let leading = match mutbl {
1045 Some(ast::Mutability::Not) => "static",
1046 Some(ast::Mutability::Mut) => "static mut",
1048 self.word_space(leading);
1049 self.print_ident(ident);
1050 self.word_space(":");
1051 self.print_type(ty);
1053 self.end(); // end the head-ibox
1054 if let Some(body) = body {
1055 self.word_space("=");
1056 self.print_expr(body);
1059 self.end(); // end the outer cbox
1062 fn print_associated_type(
1065 generics: &ast::Generics,
1066 bounds: &ast::GenericBounds,
1067 ty: Option<&ast::Ty>,
1068 vis: &ast::Visibility,
1069 defaultness: ast::Defaultness,
1072 self.print_visibility(vis);
1073 self.print_defaultness(defaultness);
1074 self.word_space("type");
1075 self.print_ident(ident);
1076 self.print_generic_params(&generics.params);
1077 self.print_type_bounds(":", bounds);
1078 self.print_where_clause(&generics.where_clause);
1079 if let Some(ty) = ty {
1081 self.word_space("=");
1082 self.print_type(ty);
1085 self.end(); // end inner head-block
1086 self.end(); // end outer head-block
1089 /// Pretty-prints an item.
1090 crate fn print_item(&mut self, item: &ast::Item) {
1091 self.hardbreak_if_not_bol();
1092 self.maybe_print_comment(item.span.lo());
1093 self.print_outer_attributes(&item.attrs);
1094 self.ann.pre(self, AnnNode::Item(item));
1096 ast::ItemKind::ExternCrate(orig_name) => {
1097 self.head(visibility_qualified(&item.vis, "extern crate"));
1098 if let Some(orig_name) = orig_name {
1099 self.print_name(orig_name);
1104 self.print_ident(item.ident);
1106 self.end(); // end inner head-block
1107 self.end(); // end outer head-block
1109 ast::ItemKind::Use(ref tree) => {
1110 self.head(visibility_qualified(&item.vis, "use"));
1111 self.print_use_tree(tree);
1113 self.end(); // end inner head-block
1114 self.end(); // end outer head-block
1116 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1117 let def = ast::Defaultness::Final;
1118 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1120 ast::ItemKind::Const(def, ref ty, ref body) => {
1121 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1123 ast::ItemKind::Fn(def, ref sig, ref gen, ref body) => {
1124 let body = body.as_deref();
1125 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1127 ast::ItemKind::Mod(ref _mod) => {
1128 self.head(visibility_qualified(&item.vis, "mod"));
1129 self.print_ident(item.ident);
1131 if _mod.inline || self.is_expanded {
1134 self.print_mod(_mod, &item.attrs);
1135 self.bclose(item.span);
1138 self.end(); // end inner head-block
1139 self.end(); // end outer head-block
1142 ast::ItemKind::ForeignMod(ref nmod) => {
1143 self.head("extern");
1144 if let Some(abi) = nmod.abi {
1145 self.print_literal(&abi.as_lit());
1149 self.print_foreign_mod(nmod, &item.attrs);
1150 self.bclose(item.span);
1152 ast::ItemKind::GlobalAsm(ref ga) => {
1153 self.head(visibility_qualified(&item.vis, "global_asm!"));
1154 self.s.word(ga.asm.to_string());
1157 ast::ItemKind::TyAlias(def, ref generics, ref bounds, ref ty) => {
1158 let ty = ty.as_deref();
1159 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1161 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1162 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1164 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1165 self.head(visibility_qualified(&item.vis, "struct"));
1166 self.print_struct(struct_def, generics, item.ident, item.span, true);
1168 ast::ItemKind::Union(ref struct_def, ref generics) => {
1169 self.head(visibility_qualified(&item.vis, "union"));
1170 self.print_struct(struct_def, generics, item.ident, item.span, true);
1172 ast::ItemKind::Impl {
1183 self.print_visibility(&item.vis);
1184 self.print_defaultness(defaultness);
1185 self.print_unsafety(unsafety);
1186 self.word_nbsp("impl");
1187 self.print_constness(constness);
1189 if !generics.params.is_empty() {
1190 self.print_generic_params(&generics.params);
1194 if let ast::ImplPolarity::Negative(_) = polarity {
1198 if let Some(ref t) = *of_trait {
1199 self.print_trait_ref(t);
1201 self.word_space("for");
1204 self.print_type(self_ty);
1205 self.print_where_clause(&generics.where_clause);
1209 self.print_inner_attributes(&item.attrs);
1210 for impl_item in items {
1211 self.print_assoc_item(impl_item);
1213 self.bclose(item.span);
1215 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1217 self.print_visibility(&item.vis);
1218 self.print_unsafety(unsafety);
1219 self.print_is_auto(is_auto);
1220 self.word_nbsp("trait");
1221 self.print_ident(item.ident);
1222 self.print_generic_params(&generics.params);
1223 let mut real_bounds = Vec::with_capacity(bounds.len());
1224 for b in bounds.iter() {
1225 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1227 self.word_space("for ?");
1228 self.print_trait_ref(&ptr.trait_ref);
1230 real_bounds.push(b.clone());
1233 self.print_type_bounds(":", &real_bounds[..]);
1234 self.print_where_clause(&generics.where_clause);
1237 self.print_inner_attributes(&item.attrs);
1238 for trait_item in trait_items {
1239 self.print_assoc_item(trait_item);
1241 self.bclose(item.span);
1243 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1245 self.print_visibility(&item.vis);
1246 self.word_nbsp("trait");
1247 self.print_ident(item.ident);
1248 self.print_generic_params(&generics.params);
1249 let mut real_bounds = Vec::with_capacity(bounds.len());
1250 // FIXME(durka) this seems to be some quite outdated syntax
1251 for b in bounds.iter() {
1252 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1254 self.word_space("for ?");
1255 self.print_trait_ref(&ptr.trait_ref);
1257 real_bounds.push(b.clone());
1261 self.print_type_bounds("=", &real_bounds[..]);
1262 self.print_where_clause(&generics.where_clause);
1265 ast::ItemKind::MacCall(ref mac) => {
1266 self.print_mac(mac);
1267 if mac.args.need_semicolon() {
1271 ast::ItemKind::MacroDef(ref macro_def) => {
1272 let (kw, has_bang) = if macro_def.macro_rules {
1273 ("macro_rules", true)
1275 self.print_visibility(&item.vis);
1278 self.print_mac_common(
1279 Some(MacHeader::Keyword(kw)),
1282 macro_def.body.delim(),
1283 ¯o_def.body.inner_tokens(),
1289 self.ann.post(self, AnnNode::Item(item))
1292 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1293 self.print_path(&t.path, false, 0)
1296 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1297 if !generic_params.is_empty() {
1299 self.print_generic_params(generic_params);
1304 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1305 self.print_formal_generic_params(&t.bound_generic_params);
1306 self.print_trait_ref(&t.trait_ref)
1309 crate fn print_enum_def(
1311 enum_definition: &ast::EnumDef,
1312 generics: &ast::Generics,
1314 span: rustc_span::Span,
1315 visibility: &ast::Visibility,
1317 self.head(visibility_qualified(visibility, "enum"));
1318 self.print_ident(ident);
1319 self.print_generic_params(&generics.params);
1320 self.print_where_clause(&generics.where_clause);
1322 self.print_variants(&enum_definition.variants, span)
1325 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1328 self.space_if_not_bol();
1329 self.maybe_print_comment(v.span.lo());
1330 self.print_outer_attributes(&v.attrs);
1331 self.ibox(INDENT_UNIT);
1332 self.print_variant(v);
1335 self.maybe_print_trailing_comment(v.span, None);
1340 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1342 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1343 ast::VisibilityKind::Crate(sugar) => match sugar {
1344 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1345 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1347 ast::VisibilityKind::Restricted { ref path, .. } => {
1348 let path = to_string(|s| s.print_path(path, false, 0));
1349 if path == "self" || path == "super" {
1350 self.word_nbsp(format!("pub({})", path))
1352 self.word_nbsp(format!("pub(in {})", path))
1355 ast::VisibilityKind::Inherited => {}
1359 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1360 if let ast::Defaultness::Default(_) = defaultness {
1361 self.word_nbsp("default");
1365 crate fn print_struct(
1367 struct_def: &ast::VariantData,
1368 generics: &ast::Generics,
1370 span: rustc_span::Span,
1371 print_finalizer: bool,
1373 self.print_ident(ident);
1374 self.print_generic_params(&generics.params);
1376 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1377 if let ast::VariantData::Tuple(..) = struct_def {
1379 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1380 s.maybe_print_comment(field.span.lo());
1381 s.print_outer_attributes(&field.attrs);
1382 s.print_visibility(&field.vis);
1383 s.print_type(&field.ty)
1387 self.print_where_clause(&generics.where_clause);
1388 if print_finalizer {
1392 self.end(); // Close the outer-box.
1394 ast::VariantData::Struct(..) => {
1395 self.print_where_clause(&generics.where_clause);
1398 self.hardbreak_if_not_bol();
1400 for field in struct_def.fields() {
1401 self.hardbreak_if_not_bol();
1402 self.maybe_print_comment(field.span.lo());
1403 self.print_outer_attributes(&field.attrs);
1404 self.print_visibility(&field.vis);
1405 self.print_ident(field.ident.unwrap());
1406 self.word_nbsp(":");
1407 self.print_type(&field.ty);
1416 crate fn print_variant(&mut self, v: &ast::Variant) {
1418 self.print_visibility(&v.vis);
1419 let generics = ast::Generics::default();
1420 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1421 if let Some(ref d) = v.disr_expr {
1423 self.word_space("=");
1424 self.print_expr(&d.value)
1428 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1429 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1430 self.ann.pre(self, AnnNode::SubItem(id));
1431 self.hardbreak_if_not_bol();
1432 self.maybe_print_comment(span.lo());
1433 self.print_outer_attributes(attrs);
1435 ast::AssocItemKind::Fn(def, sig, gen, body) => {
1436 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1438 ast::AssocItemKind::Const(def, ty, body) => {
1439 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1441 ast::AssocItemKind::TyAlias(def, generics, bounds, ty) => {
1442 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1444 ast::AssocItemKind::MacCall(m) => {
1446 if m.args.need_semicolon() {
1451 self.ann.post(self, AnnNode::SubItem(id))
1454 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1455 self.maybe_print_comment(st.span.lo());
1457 ast::StmtKind::Local(ref loc) => {
1458 self.print_outer_attributes(&loc.attrs);
1459 self.space_if_not_bol();
1460 self.ibox(INDENT_UNIT);
1461 self.word_nbsp("let");
1463 self.ibox(INDENT_UNIT);
1464 self.print_local_decl(loc);
1466 if let Some(ref init) = loc.init {
1468 self.word_space("=");
1469 self.print_expr(init);
1474 ast::StmtKind::Item(ref item) => self.print_item(item),
1475 ast::StmtKind::Expr(ref expr) => {
1476 self.space_if_not_bol();
1477 self.print_expr_outer_attr_style(expr, false);
1478 if classify::expr_requires_semi_to_be_stmt(expr) {
1482 ast::StmtKind::Semi(ref expr) => {
1483 self.space_if_not_bol();
1484 self.print_expr_outer_attr_style(expr, false);
1487 ast::StmtKind::Empty => {
1488 self.space_if_not_bol();
1491 ast::StmtKind::MacCall(ref mac) => {
1492 let (ref mac, style, ref attrs) = **mac;
1493 self.space_if_not_bol();
1494 self.print_outer_attributes(attrs);
1495 self.print_mac(mac);
1496 if style == ast::MacStmtStyle::Semicolon {
1501 self.maybe_print_trailing_comment(st.span, None)
1504 crate fn print_block(&mut self, blk: &ast::Block) {
1505 self.print_block_with_attrs(blk, &[])
1508 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1509 self.print_block_maybe_unclosed(blk, &[], false)
1512 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1513 self.print_block_maybe_unclosed(blk, attrs, true)
1516 crate fn print_block_maybe_unclosed(
1519 attrs: &[ast::Attribute],
1523 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1524 BlockCheckMode::Default => (),
1526 self.maybe_print_comment(blk.span.lo());
1527 self.ann.pre(self, AnnNode::Block(blk));
1530 self.print_inner_attributes(attrs);
1532 for (i, st) in blk.stmts.iter().enumerate() {
1534 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1535 self.maybe_print_comment(st.span.lo());
1536 self.space_if_not_bol();
1537 self.print_expr_outer_attr_style(expr, false);
1538 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1540 _ => self.print_stmt(st),
1544 self.bclose_maybe_open(blk.span, close_box);
1545 self.ann.post(self, AnnNode::Block(blk))
1548 /// Print a `let pat = scrutinee` expression.
1549 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1550 self.s.word("let ");
1552 self.print_pat(pat);
1555 self.word_space("=");
1556 self.print_expr_cond_paren(
1558 Self::cond_needs_par(scrutinee)
1559 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1563 fn print_else(&mut self, els: Option<&ast::Expr>) {
1564 if let Some(_else) = els {
1566 // Another `else if` block.
1567 ast::ExprKind::If(ref i, ref then, ref e) => {
1568 self.cbox(INDENT_UNIT - 1);
1570 self.s.word(" else if ");
1571 self.print_expr_as_cond(i);
1573 self.print_block(then);
1574 self.print_else(e.as_deref())
1576 // Final `else` block.
1577 ast::ExprKind::Block(ref b, _) => {
1578 self.cbox(INDENT_UNIT - 1);
1580 self.s.word(" else ");
1583 // Constraints would be great here!
1585 panic!("print_if saw if with weird alternative");
1591 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1594 self.print_expr_as_cond(test);
1597 self.print_block(blk);
1598 self.print_else(elseopt)
1601 crate fn print_mac(&mut self, m: &ast::MacCall) {
1602 self.print_mac_common(
1603 Some(MacHeader::Path(&m.path)),
1607 &m.args.inner_tokens(),
1613 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1615 self.commasep_exprs(Inconsistent, args);
1619 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1620 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1623 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1624 /// `if cond { ... }`.
1625 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1626 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1629 /// Does `expr` need parenthesis when printed in a condition position?
1630 fn cond_needs_par(expr: &ast::Expr) -> bool {
1632 // These cases need parens due to the parse error observed in #26461: `if return {}`
1633 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1634 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1636 _ => parser::contains_exterior_struct_lit(expr),
1640 /// Prints `expr` or `(expr)` when `needs_par` holds.
1641 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1645 self.print_expr(expr);
1651 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1652 self.ibox(INDENT_UNIT);
1654 self.print_inner_attributes_inline(attrs);
1655 self.commasep_exprs(Inconsistent, &exprs[..]);
1660 fn print_expr_repeat(
1662 element: &ast::Expr,
1663 count: &ast::AnonConst,
1664 attrs: &[Attribute],
1666 self.ibox(INDENT_UNIT);
1668 self.print_inner_attributes_inline(attrs);
1669 self.print_expr(element);
1670 self.word_space(";");
1671 self.print_expr(&count.value);
1676 fn print_expr_struct(
1679 fields: &[ast::Field],
1680 wth: &Option<P<ast::Expr>>,
1681 attrs: &[Attribute],
1683 self.print_path(path, true, 0);
1685 self.print_inner_attributes_inline(attrs);
1690 s.print_outer_attributes(&field.attrs);
1691 s.ibox(INDENT_UNIT);
1692 if !field.is_shorthand {
1693 s.print_ident(field.ident);
1696 s.print_expr(&field.expr);
1703 self.ibox(INDENT_UNIT);
1704 if !fields.is_empty() {
1709 self.print_expr(expr);
1713 if !fields.is_empty() {
1721 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1723 self.print_inner_attributes_inline(attrs);
1724 self.commasep_exprs(Inconsistent, &exprs[..]);
1725 if exprs.len() == 1 {
1731 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1732 let prec = match func.kind {
1733 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1734 _ => parser::PREC_POSTFIX,
1737 self.print_expr_maybe_paren(func, prec);
1738 self.print_call_post(args)
1741 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1742 let base_args = &args[1..];
1743 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1745 self.print_ident(segment.ident);
1746 if let Some(ref args) = segment.args {
1747 self.print_generic_args(args, true);
1749 self.print_call_post(base_args)
1752 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1753 let assoc_op = AssocOp::from_ast_binop(op.node);
1754 let prec = assoc_op.precedence() as i8;
1755 let fixity = assoc_op.fixity();
1757 let (left_prec, right_prec) = match fixity {
1758 Fixity::Left => (prec, prec + 1),
1759 Fixity::Right => (prec + 1, prec),
1760 Fixity::None => (prec + 1, prec + 1),
1763 let left_prec = match (&lhs.kind, op.node) {
1764 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1765 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1766 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1767 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1768 parser::PREC_FORCE_PAREN
1770 // We are given `(let _ = a) OP b`.
1772 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1773 // as the parser will interpret this as `(let _ = a) OP b`.
1775 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1776 // parens are required since the parser would interpret `let a = b < c` as
1777 // `let a = (b < c)`. To achieve this, we force parens.
1778 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1779 parser::PREC_FORCE_PAREN
1784 self.print_expr_maybe_paren(lhs, left_prec);
1786 self.word_space(op.node.to_string());
1787 self.print_expr_maybe_paren(rhs, right_prec)
1790 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1791 self.s.word(ast::UnOp::to_string(op));
1792 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1795 fn print_expr_addr_of(
1797 kind: ast::BorrowKind,
1798 mutability: ast::Mutability,
1803 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1804 ast::BorrowKind::Raw => {
1805 self.word_nbsp("raw");
1806 self.print_mutability(mutability, true);
1809 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1812 pub fn print_expr(&mut self, expr: &ast::Expr) {
1813 self.print_expr_outer_attr_style(expr, true)
1816 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1817 self.maybe_print_comment(expr.span.lo());
1819 let attrs = &expr.attrs;
1821 self.print_outer_attributes_inline(attrs);
1823 self.print_outer_attributes(attrs);
1826 self.ibox(INDENT_UNIT);
1827 self.ann.pre(self, AnnNode::Expr(expr));
1829 ast::ExprKind::Box(ref expr) => {
1830 self.word_space("box");
1831 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1833 ast::ExprKind::Array(ref exprs) => {
1834 self.print_expr_vec(&exprs[..], attrs);
1836 ast::ExprKind::Repeat(ref element, ref count) => {
1837 self.print_expr_repeat(element, count, attrs);
1839 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1840 self.print_expr_struct(path, &fields[..], wth, attrs);
1842 ast::ExprKind::Tup(ref exprs) => {
1843 self.print_expr_tup(&exprs[..], attrs);
1845 ast::ExprKind::Call(ref func, ref args) => {
1846 self.print_expr_call(func, &args[..]);
1848 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1849 self.print_expr_method_call(segment, &args[..]);
1851 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1852 self.print_expr_binary(op, lhs, rhs);
1854 ast::ExprKind::Unary(op, ref expr) => {
1855 self.print_expr_unary(op, expr);
1857 ast::ExprKind::AddrOf(k, m, ref expr) => {
1858 self.print_expr_addr_of(k, m, expr);
1860 ast::ExprKind::Lit(ref lit) => {
1861 self.print_literal(lit);
1863 ast::ExprKind::Cast(ref expr, ref ty) => {
1864 let prec = AssocOp::As.precedence() as i8;
1865 self.print_expr_maybe_paren(expr, prec);
1867 self.word_space("as");
1868 self.print_type(ty);
1870 ast::ExprKind::Type(ref expr, ref ty) => {
1871 let prec = AssocOp::Colon.precedence() as i8;
1872 self.print_expr_maybe_paren(expr, prec);
1873 self.word_space(":");
1874 self.print_type(ty);
1876 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1877 self.print_let(pat, scrutinee);
1879 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1880 self.print_if(test, blk, elseopt.as_deref())
1882 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1883 if let Some(label) = opt_label {
1884 self.print_ident(label.ident);
1885 self.word_space(":");
1888 self.print_expr_as_cond(test);
1890 self.print_block_with_attrs(blk, attrs);
1892 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1893 if let Some(label) = opt_label {
1894 self.print_ident(label.ident);
1895 self.word_space(":");
1898 self.print_pat(pat);
1900 self.word_space("in");
1901 self.print_expr_as_cond(iter);
1903 self.print_block_with_attrs(blk, attrs);
1905 ast::ExprKind::Loop(ref blk, opt_label) => {
1906 if let Some(label) = opt_label {
1907 self.print_ident(label.ident);
1908 self.word_space(":");
1912 self.print_block_with_attrs(blk, attrs);
1914 ast::ExprKind::Match(ref expr, ref arms) => {
1915 self.cbox(INDENT_UNIT);
1916 self.ibox(INDENT_UNIT);
1917 self.word_nbsp("match");
1918 self.print_expr_as_cond(expr);
1921 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1923 self.print_arm(arm);
1925 self.bclose(expr.span);
1927 ast::ExprKind::Closure(
1935 self.print_movability(movability);
1936 self.print_asyncness(asyncness);
1937 self.print_capture_clause(capture_clause);
1939 self.print_fn_params_and_ret(decl, true);
1941 self.print_expr(body);
1942 self.end(); // need to close a box
1944 // a box will be closed by print_expr, but we didn't want an overall
1945 // wrapper so we closed the corresponding opening. so create an
1946 // empty box to satisfy the close.
1949 ast::ExprKind::Block(ref blk, opt_label) => {
1950 if let Some(label) = opt_label {
1951 self.print_ident(label.ident);
1952 self.word_space(":");
1954 // containing cbox, will be closed by print-block at }
1955 self.cbox(INDENT_UNIT);
1956 // head-box, will be closed by print-block after {
1958 self.print_block_with_attrs(blk, attrs);
1960 ast::ExprKind::Async(capture_clause, _, ref blk) => {
1961 self.word_nbsp("async");
1962 self.print_capture_clause(capture_clause);
1964 // cbox/ibox in analogy to the `ExprKind::Block` arm above
1965 self.cbox(INDENT_UNIT);
1967 self.print_block_with_attrs(blk, attrs);
1969 ast::ExprKind::Await(ref expr) => {
1970 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1971 self.s.word(".await");
1973 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
1974 let prec = AssocOp::Assign.precedence() as i8;
1975 self.print_expr_maybe_paren(lhs, prec + 1);
1977 self.word_space("=");
1978 self.print_expr_maybe_paren(rhs, prec);
1980 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1981 let prec = AssocOp::Assign.precedence() as i8;
1982 self.print_expr_maybe_paren(lhs, prec + 1);
1984 self.s.word(op.node.to_string());
1985 self.word_space("=");
1986 self.print_expr_maybe_paren(rhs, prec);
1988 ast::ExprKind::Field(ref expr, ident) => {
1989 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1991 self.print_ident(ident);
1993 ast::ExprKind::Index(ref expr, ref index) => {
1994 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1996 self.print_expr(index);
1999 ast::ExprKind::Range(ref start, ref end, limits) => {
2000 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2001 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2002 // Here we use a fake precedence value so that any child with lower precedence than
2003 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2004 let fake_prec = AssocOp::LOr.precedence() as i8;
2005 if let Some(ref e) = *start {
2006 self.print_expr_maybe_paren(e, fake_prec);
2008 if limits == ast::RangeLimits::HalfOpen {
2013 if let Some(ref e) = *end {
2014 self.print_expr_maybe_paren(e, fake_prec);
2017 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2018 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2019 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2020 self.s.word("break");
2022 if let Some(label) = opt_label {
2023 self.print_ident(label.ident);
2026 if let Some(ref expr) = *opt_expr {
2027 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2031 ast::ExprKind::Continue(opt_label) => {
2032 self.s.word("continue");
2034 if let Some(label) = opt_label {
2035 self.print_ident(label.ident);
2039 ast::ExprKind::Ret(ref result) => {
2040 self.s.word("return");
2041 if let Some(ref expr) = *result {
2043 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2046 ast::ExprKind::InlineAsm(ref a) => {
2049 Operand(&'a InlineAsmOperand),
2050 Options(InlineAsmOptions),
2053 let mut args = vec![];
2054 args.push(AsmArg::Template(InlineAsmTemplatePiece::to_string(&a.template)));
2055 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2056 if !a.options.is_empty() {
2057 args.push(AsmArg::Options(a.options));
2062 self.commasep(Consistent, &args, |s, arg| match arg {
2063 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2064 AsmArg::Operand(op) => {
2065 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r
2067 InlineAsmRegOrRegClass::Reg(r) => {
2068 s.print_symbol(*r, ast::StrStyle::Cooked)
2070 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2073 InlineAsmOperand::In { reg, expr } => {
2076 print_reg_or_class(s, reg);
2081 InlineAsmOperand::Out { reg, late, expr } => {
2082 s.word(if *late { "lateout" } else { "out" });
2084 print_reg_or_class(s, reg);
2088 Some(expr) => s.print_expr(expr),
2089 None => s.word("_"),
2092 InlineAsmOperand::InOut { reg, late, expr } => {
2093 s.word(if *late { "inlateout" } else { "inout" });
2095 print_reg_or_class(s, reg);
2100 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2101 s.word(if *late { "inlateout" } else { "inout" });
2103 print_reg_or_class(s, reg);
2106 s.print_expr(in_expr);
2110 Some(out_expr) => s.print_expr(out_expr),
2111 None => s.word("_"),
2114 InlineAsmOperand::Const { expr } => {
2119 InlineAsmOperand::Sym { expr } => {
2126 AsmArg::Options(opts) => {
2129 let mut options = vec![];
2130 if opts.contains(InlineAsmOptions::PURE) {
2131 options.push("pure");
2133 if opts.contains(InlineAsmOptions::NOMEM) {
2134 options.push("nomem");
2136 if opts.contains(InlineAsmOptions::READONLY) {
2137 options.push("readonly");
2139 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2140 options.push("preserves_flags");
2142 if opts.contains(InlineAsmOptions::NORETURN) {
2143 options.push("noreturn");
2145 if opts.contains(InlineAsmOptions::NOSTACK) {
2146 options.push("nostack");
2148 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2149 options.push("att_syntax");
2151 s.commasep(Inconsistent, &options, |s, &opt| {
2159 ast::ExprKind::LlvmInlineAsm(ref a) => {
2160 self.s.word("llvm_asm!");
2162 self.print_symbol(a.asm, a.asm_str_style);
2163 self.word_space(":");
2165 self.commasep(Inconsistent, &a.outputs, |s, out| {
2166 let constraint = out.constraint.as_str();
2167 let mut ch = constraint.chars();
2169 Some('=') if out.is_rw => {
2170 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2172 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2175 s.print_expr(&out.expr);
2179 self.word_space(":");
2181 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2182 s.print_symbol(co, ast::StrStyle::Cooked);
2188 self.word_space(":");
2190 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2191 s.print_symbol(co, ast::StrStyle::Cooked);
2194 let mut options = vec![];
2196 options.push("volatile");
2199 options.push("alignstack");
2201 if a.dialect == ast::LlvmAsmDialect::Intel {
2202 options.push("intel");
2205 if !options.is_empty() {
2207 self.word_space(":");
2208 self.commasep(Inconsistent, &options, |s, &co| {
2209 s.print_string(co, ast::StrStyle::Cooked);
2215 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2216 ast::ExprKind::Paren(ref e) => {
2218 self.print_inner_attributes_inline(attrs);
2222 ast::ExprKind::Yield(ref e) => {
2223 self.s.word("yield");
2225 if let Some(ref expr) = *e {
2227 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2230 ast::ExprKind::Try(ref e) => {
2231 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2234 ast::ExprKind::TryBlock(ref blk) => {
2237 self.print_block_with_attrs(blk, attrs)
2239 ast::ExprKind::Err => {
2241 self.s.word("/*ERROR*/");
2245 self.ann.post(self, AnnNode::Expr(expr));
2249 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2250 self.print_pat(&loc.pat);
2251 if let Some(ref ty) = loc.ty {
2252 self.word_space(":");
2253 self.print_type(ty);
2257 pub fn print_usize(&mut self, i: usize) {
2258 self.s.word(i.to_string())
2261 crate fn print_name(&mut self, name: Symbol) {
2262 self.s.word(name.to_string());
2263 self.ann.post(self, AnnNode::Name(&name))
2266 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2268 self.print_type(&qself.ty);
2269 if qself.position > 0 {
2271 self.word_space("as");
2272 let depth = path.segments.len() - qself.position;
2273 self.print_path(path, false, depth);
2277 let item_segment = path.segments.last().unwrap();
2278 self.print_ident(item_segment.ident);
2279 if let Some(ref args) = item_segment.args {
2280 self.print_generic_args(args, colons_before_params)
2284 crate fn print_pat(&mut self, pat: &ast::Pat) {
2285 self.maybe_print_comment(pat.span.lo());
2286 self.ann.pre(self, AnnNode::Pat(pat));
2287 /* Pat isn't normalized, but the beauty of it
2288 is that it doesn't matter */
2290 PatKind::Wild => self.s.word("_"),
2291 PatKind::Ident(binding_mode, ident, ref sub) => {
2292 match binding_mode {
2293 ast::BindingMode::ByRef(mutbl) => {
2294 self.word_nbsp("ref");
2295 self.print_mutability(mutbl, false);
2297 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2298 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2299 self.word_nbsp("mut");
2302 self.print_ident(ident);
2303 if let Some(ref p) = *sub {
2305 self.s.word_space("@");
2309 PatKind::TupleStruct(ref path, ref elts) => {
2310 self.print_path(path, true, 0);
2312 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2315 PatKind::Or(ref pats) => {
2316 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2318 PatKind::Path(None, ref path) => {
2319 self.print_path(path, true, 0);
2321 PatKind::Path(Some(ref qself), ref path) => {
2322 self.print_qpath(path, qself, false);
2324 PatKind::Struct(ref path, ref fields, etc) => {
2325 self.print_path(path, true, 0);
2327 self.word_space("{");
2332 s.cbox(INDENT_UNIT);
2333 if !f.is_shorthand {
2334 s.print_ident(f.ident);
2337 s.print_pat(&f.pat);
2343 if !fields.is_empty() {
2344 self.word_space(",");
2351 PatKind::Tuple(ref elts) => {
2353 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2354 if elts.len() == 1 {
2359 PatKind::Box(ref inner) => {
2360 self.s.word("box ");
2361 self.print_pat(inner);
2363 PatKind::Ref(ref inner, mutbl) => {
2365 if mutbl == ast::Mutability::Mut {
2366 self.s.word("mut ");
2368 self.print_pat(inner);
2370 PatKind::Lit(ref e) => self.print_expr(&**e),
2371 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2372 if let Some(e) = begin {
2377 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2378 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2379 RangeEnd::Excluded => self.s.word(".."),
2381 if let Some(e) = end {
2385 PatKind::Slice(ref elts) => {
2387 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2390 PatKind::Rest => self.s.word(".."),
2391 PatKind::Paren(ref inner) => {
2393 self.print_pat(inner);
2396 PatKind::MacCall(ref m) => self.print_mac(m),
2398 self.ann.post(self, AnnNode::Pat(pat))
2401 fn print_arm(&mut self, arm: &ast::Arm) {
2402 // Note, I have no idea why this check is necessary, but here it is.
2403 if arm.attrs.is_empty() {
2406 self.cbox(INDENT_UNIT);
2408 self.maybe_print_comment(arm.pat.span.lo());
2409 self.print_outer_attributes(&arm.attrs);
2410 self.print_pat(&arm.pat);
2412 if let Some(ref e) = arm.guard {
2413 self.word_space("if");
2417 self.word_space("=>");
2419 match arm.body.kind {
2420 ast::ExprKind::Block(ref blk, opt_label) => {
2421 if let Some(label) = opt_label {
2422 self.print_ident(label.ident);
2423 self.word_space(":");
2426 // The block will close the pattern's ibox.
2427 self.print_block_unclosed_indent(blk);
2429 // If it is a user-provided unsafe block, print a comma after it.
2430 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2435 self.end(); // Close the ibox for the pattern.
2436 self.print_expr(&arm.body);
2440 self.end(); // Close enclosing cbox.
2443 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2444 match explicit_self.node {
2445 SelfKind::Value(m) => {
2446 self.print_mutability(m, false);
2449 SelfKind::Region(ref lt, m) => {
2451 self.print_opt_lifetime(lt);
2452 self.print_mutability(m, false);
2455 SelfKind::Explicit(ref typ, m) => {
2456 self.print_mutability(m, false);
2457 self.s.word("self");
2458 self.word_space(":");
2459 self.print_type(typ)
2468 generics: &ast::Generics,
2469 vis: &ast::Visibility,
2470 defaultness: ast::Defaultness,
2471 body: Option<&ast::Block>,
2472 attrs: &[ast::Attribute],
2477 self.print_visibility(vis);
2478 self.print_defaultness(defaultness);
2479 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2480 if let Some(body) = body {
2482 self.print_block_with_attrs(body, attrs);
2491 header: ast::FnHeader,
2492 name: Option<Ident>,
2493 generics: &ast::Generics,
2495 self.print_fn_header_info(header);
2496 if let Some(name) = name {
2498 self.print_ident(name);
2500 self.print_generic_params(&generics.params);
2501 self.print_fn_params_and_ret(decl, false);
2502 self.print_where_clause(&generics.where_clause)
2505 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2506 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2508 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2510 self.print_fn_ret_ty(&decl.output)
2513 crate fn print_movability(&mut self, movability: ast::Movability) {
2515 ast::Movability::Static => self.word_space("static"),
2516 ast::Movability::Movable => {}
2520 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2521 if asyncness.is_async() {
2522 self.word_nbsp("async");
2526 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2527 match capture_clause {
2528 ast::CaptureBy::Value => self.word_space("move"),
2529 ast::CaptureBy::Ref => {}
2533 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2534 if !bounds.is_empty() {
2535 self.s.word(prefix);
2536 let mut first = true;
2537 for bound in bounds {
2538 if !(first && prefix.is_empty()) {
2544 self.word_space("+");
2548 GenericBound::Trait(tref, modifier) => {
2549 if modifier == &TraitBoundModifier::Maybe {
2552 self.print_poly_trait_ref(tref);
2554 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2560 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2561 self.print_name(lifetime.ident.name)
2564 crate fn print_lifetime_bounds(
2566 lifetime: ast::Lifetime,
2567 bounds: &ast::GenericBounds,
2569 self.print_lifetime(lifetime);
2570 if !bounds.is_empty() {
2572 for (i, bound) in bounds.iter().enumerate() {
2577 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2584 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2585 if generic_params.is_empty() {
2591 self.commasep(Inconsistent, &generic_params, |s, param| {
2592 s.print_outer_attributes_inline(¶m.attrs);
2595 ast::GenericParamKind::Lifetime => {
2596 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2597 s.print_lifetime_bounds(lt, ¶m.bounds)
2599 ast::GenericParamKind::Type { ref default } => {
2600 s.print_ident(param.ident);
2601 s.print_type_bounds(":", ¶m.bounds);
2602 if let Some(ref default) = default {
2605 s.print_type(default)
2608 ast::GenericParamKind::Const { ref ty, kw_span: _ } => {
2609 s.word_space("const");
2610 s.print_ident(param.ident);
2614 s.print_type_bounds(":", ¶m.bounds)
2622 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2623 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2628 self.word_space("where");
2630 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2632 self.word_space(",");
2636 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2637 ref bound_generic_params,
2642 self.print_formal_generic_params(bound_generic_params);
2643 self.print_type(bounded_ty);
2644 self.print_type_bounds(":", bounds);
2646 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2651 self.print_lifetime_bounds(*lifetime, bounds);
2653 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2658 self.print_type(lhs_ty);
2660 self.word_space("=");
2661 self.print_type(rhs_ty);
2667 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2669 ast::UseTreeKind::Simple(rename, ..) => {
2670 self.print_path(&tree.prefix, false, 0);
2671 if let Some(rename) = rename {
2673 self.word_space("as");
2674 self.print_ident(rename);
2677 ast::UseTreeKind::Glob => {
2678 if !tree.prefix.segments.is_empty() {
2679 self.print_path(&tree.prefix, false, 0);
2684 ast::UseTreeKind::Nested(ref items) => {
2685 if tree.prefix.segments.is_empty() {
2688 self.print_path(&tree.prefix, false, 0);
2691 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2692 this.print_use_tree(tree)
2699 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2701 ast::Mutability::Mut => self.word_nbsp("mut"),
2702 ast::Mutability::Not => {
2704 self.word_nbsp("const");
2710 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2711 self.print_mutability(mt.mutbl, print_const);
2712 self.print_type(&mt.ty)
2715 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2716 self.ibox(INDENT_UNIT);
2718 self.print_outer_attributes_inline(&input.attrs);
2720 match input.ty.kind {
2721 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2723 if let Some(eself) = input.to_self() {
2724 self.print_explicit_self(&eself);
2726 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2727 ident.name == kw::Invalid
2732 self.print_pat(&input.pat);
2736 self.print_type(&input.ty);
2743 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2744 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2745 self.space_if_not_bol();
2746 self.ibox(INDENT_UNIT);
2747 self.word_space("->");
2748 self.print_type(ty);
2750 self.maybe_print_comment(ty.span.lo());
2754 crate fn print_ty_fn(
2757 unsafety: ast::Unsafe,
2759 name: Option<Ident>,
2760 generic_params: &[ast::GenericParam],
2762 self.ibox(INDENT_UNIT);
2763 if !generic_params.is_empty() {
2765 self.print_generic_params(generic_params);
2767 let generics = ast::Generics {
2769 where_clause: ast::WhereClause {
2770 has_where_token: false,
2771 predicates: Vec::new(),
2772 span: rustc_span::DUMMY_SP,
2774 span: rustc_span::DUMMY_SP,
2776 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2777 self.print_fn(decl, header, name, &generics);
2781 crate fn maybe_print_trailing_comment(
2783 span: rustc_span::Span,
2784 next_pos: Option<BytePos>,
2786 if let Some(cmnts) = self.comments() {
2787 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2788 self.print_comment(&cmnt);
2793 crate fn print_remaining_comments(&mut self) {
2794 // If there aren't any remaining comments, then we need to manually
2795 // make sure there is a line break at the end.
2796 if self.next_comment().is_none() {
2799 while let Some(ref cmnt) = self.next_comment() {
2800 self.print_comment(cmnt);
2804 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2805 self.print_constness(header.constness);
2806 self.print_asyncness(header.asyncness);
2807 self.print_unsafety(header.unsafety);
2810 ast::Extern::None => {}
2811 ast::Extern::Implicit => {
2812 self.word_nbsp("extern");
2814 ast::Extern::Explicit(abi) => {
2815 self.word_nbsp("extern");
2816 self.print_literal(&abi.as_lit());
2824 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2826 ast::Unsafe::No => {}
2827 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2831 crate fn print_constness(&mut self, s: ast::Const) {
2833 ast::Const::No => {}
2834 ast::Const::Yes(_) => self.word_nbsp("const"),
2838 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2840 ast::IsAuto::Yes => self.word_nbsp("auto"),
2841 ast::IsAuto::No => {}