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 if !self.is_beginning_of_line() {
456 if let Some((last, lines)) = cmnt.lines.split_last() {
460 self.word(line.clone());
464 self.word(last.clone());
471 comments::Isolated => {
472 self.hardbreak_if_not_bol();
473 for line in &cmnt.lines {
474 // Don't print empty lines because they will end up as trailing
476 if !line.is_empty() {
477 self.word(line.clone());
482 comments::Trailing => {
483 if !self.is_beginning_of_line() {
486 if cmnt.lines.len() == 1 {
487 self.word(cmnt.lines[0].clone());
491 for line in &cmnt.lines {
492 if !line.is_empty() {
493 self.word(line.clone());
500 comments::BlankLine => {
501 // We need to do at least one, possibly two hardbreaks.
502 let twice = match self.last_token() {
503 pp::Token::String(s) => ";" == s,
504 pp::Token::Begin(_) => true,
505 pp::Token::End => true,
514 if let Some(cmnts) = self.comments() {
519 fn next_comment(&mut self) -> Option<comments::Comment> {
520 self.comments().as_mut().and_then(|c| c.next())
523 fn print_literal(&mut self, lit: &ast::Lit) {
524 self.maybe_print_comment(lit.span.lo());
525 self.word(lit.token.to_string())
528 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
529 let st = match style {
530 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
531 ast::StrStyle::Raw(n) => {
532 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
538 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
539 self.print_string(&sym.as_str(), style);
542 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
543 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
546 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
547 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
550 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
551 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
554 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
555 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
558 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
559 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
562 fn print_either_attributes(
564 attrs: &[ast::Attribute],
565 kind: ast::AttrStyle,
567 trailing_hardbreak: bool,
571 if attr.style == kind {
572 self.print_attribute_inline(attr, is_inline);
579 if count > 0 && trailing_hardbreak && !is_inline {
580 self.hardbreak_if_not_bol();
584 fn print_attribute(&mut self, attr: &ast::Attribute) {
585 self.print_attribute_inline(attr, false)
588 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
590 self.hardbreak_if_not_bol();
592 self.maybe_print_comment(attr.span.lo());
594 ast::AttrKind::Normal(ref item) => {
596 ast::AttrStyle::Inner => self.word("#!["),
597 ast::AttrStyle::Outer => self.word("#["),
599 self.print_attr_item(&item, attr.span);
602 ast::AttrKind::DocComment(comment) => {
603 self.word(comment.to_string());
609 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
612 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
613 Some(MacHeader::Path(&item.path)),
621 MacArgs::Empty | MacArgs::Eq(..) => {
622 self.print_path(&item.path, false, 0);
623 if let MacArgs::Eq(_, tokens) = &item.args {
625 self.word_space("=");
626 self.print_tts(tokens, true);
633 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
635 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
636 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
640 fn print_meta_item(&mut self, item: &ast::MetaItem) {
641 self.ibox(INDENT_UNIT);
643 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
644 ast::MetaItemKind::NameValue(ref value) => {
645 self.print_path(&item.path, false, 0);
647 self.word_space("=");
648 self.print_literal(value);
650 ast::MetaItemKind::List(ref items) => {
651 self.print_path(&item.path, false, 0);
653 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
660 /// This doesn't deserve to be called "pretty" printing, but it should be
661 /// meaning-preserving. A quick hack that might help would be to look at the
662 /// spans embedded in the TTs to decide where to put spaces and newlines.
663 /// But it'd be better to parse these according to the grammar of the
664 /// appropriate macro, transcribe back into the grammar we just parsed from,
665 /// and then pretty-print the resulting AST nodes (so, e.g., we print
666 /// expression arguments as expressions). It can be done! I think.
667 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) {
669 TokenTree::Token(token) => {
670 self.word(token_to_string_ext(&token, convert_dollar_crate));
671 if let token::DocComment(..) = token.kind {
675 TokenTree::Delimited(dspan, delim, tts) => {
676 self.print_mac_common(
682 convert_dollar_crate,
689 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
690 let mut iter = tts.trees().peekable();
691 while let Some(tt) = iter.next() {
692 self.print_tt(&tt, convert_dollar_crate);
693 if let Some(next) = iter.peek() {
694 if tt_prepend_space(next, &tt) {
703 header: Option<MacHeader<'_>>,
705 ident: Option<Ident>,
708 convert_dollar_crate: bool,
711 if delim == DelimToken::Brace {
712 self.cbox(INDENT_UNIT);
715 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
716 Some(MacHeader::Keyword(kw)) => self.word(kw),
722 if let Some(ident) = ident {
724 self.print_ident(ident);
727 DelimToken::Brace => {
728 if header.is_some() || has_bang || ident.is_some() {
736 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
739 self.print_tts(tts, convert_dollar_crate);
742 DelimToken::Brace => self.bclose(span),
743 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
747 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
748 self.maybe_print_comment(path.span.lo());
750 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
754 self.print_path_segment(segment, colons_before_params);
758 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
759 if segment.ident.name != kw::PathRoot {
760 self.print_ident(segment.ident);
761 if let Some(ref args) = segment.args {
762 self.print_generic_args(args, colons_before_params);
767 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
769 // Outer-box is consistent.
770 self.cbox(INDENT_UNIT);
771 // Head-box is inconsistent.
772 self.ibox(w.len() + 1);
773 // Keyword that starts the head.
779 fn bopen(&mut self) {
781 self.end(); // Close the head-box.
784 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
785 self.maybe_print_comment(span.hi());
786 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
789 self.end(); // Close the outer-box.
793 fn bclose(&mut self, span: rustc_span::Span) {
794 self.bclose_maybe_open(span, true)
797 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
798 if !self.is_beginning_of_line() {
799 self.break_offset(n, off)
801 if off != 0 && self.last_token().is_hardbreak_tok() {
802 // We do something pretty sketchy here: tuck the nonzero
803 // offset-adjustment we were going to deposit along with the
804 // break into the previous hardbreak.
805 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
811 impl<'a> PrintState<'a> for State<'a> {
812 fn comments(&mut self) -> &mut Option<Comments<'a>> {
816 fn print_ident(&mut self, ident: Ident) {
817 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
818 self.ann.post(self, AnnNode::Ident(&ident))
821 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
822 if colons_before_params {
827 ast::GenericArgs::AngleBracketed(ref data) => {
829 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
830 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
831 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_constraint(c),
836 ast::GenericArgs::Parenthesized(ref data) => {
838 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
840 self.print_fn_ret_ty(&data.output);
847 // Synthesizes a comment that was not textually present in the original source
849 pub fn synth_comment(&mut self, text: String) {
857 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
859 F: FnMut(&mut State<'_>, &T),
860 G: FnMut(&T) -> rustc_span::Span,
863 let len = elts.len();
866 self.maybe_print_comment(get_span(elt).hi());
871 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
872 self.space_if_not_bol();
878 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
879 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
882 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
883 self.print_inner_attributes(attrs);
884 for item in &_mod.items {
885 self.print_item(item);
889 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[Attribute]) {
890 self.print_inner_attributes(attrs);
891 for item in &nmod.items {
892 self.print_foreign_item(item);
896 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
897 if let Some(lt) = *lifetime {
898 self.print_lifetime(lt);
903 pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
904 self.print_ident(constraint.ident);
906 match &constraint.kind {
907 ast::AssocTyConstraintKind::Equality { ty } => {
908 self.word_space("=");
911 ast::AssocTyConstraintKind::Bound { bounds } => {
912 self.print_type_bounds(":", &*bounds);
917 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
919 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
920 GenericArg::Type(ty) => self.print_type(ty),
921 GenericArg::Const(ct) => self.print_expr(&ct.value),
925 pub fn print_type(&mut self, ty: &ast::Ty) {
926 self.maybe_print_comment(ty.span.lo());
929 ast::TyKind::Slice(ref ty) => {
934 ast::TyKind::Ptr(ref mt) => {
936 self.print_mt(mt, true);
938 ast::TyKind::Rptr(ref lifetime, ref mt) => {
940 self.print_opt_lifetime(lifetime);
941 self.print_mt(mt, false);
943 ast::TyKind::Never => {
946 ast::TyKind::Tup(ref elts) => {
948 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
954 ast::TyKind::Paren(ref typ) => {
956 self.print_type(typ);
959 ast::TyKind::BareFn(ref f) => {
960 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
962 ast::TyKind::Path(None, ref path) => {
963 self.print_path(path, false, 0);
965 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
966 ast::TyKind::TraitObject(ref bounds, syntax) => {
967 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
968 self.print_type_bounds(prefix, &bounds[..]);
970 ast::TyKind::ImplTrait(_, ref bounds) => {
971 self.print_type_bounds("impl", &bounds[..]);
973 ast::TyKind::Array(ref ty, ref length) => {
977 self.print_expr(&length.value);
980 ast::TyKind::Typeof(ref e) => {
981 self.s.word("typeof(");
982 self.print_expr(&e.value);
985 ast::TyKind::Infer => {
988 ast::TyKind::Err => {
990 self.s.word("/*ERROR*/");
993 ast::TyKind::ImplicitSelf => {
996 ast::TyKind::MacCall(ref m) => {
999 ast::TyKind::CVarArgs => {
1006 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1007 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1008 self.ann.pre(self, AnnNode::SubItem(id));
1009 self.hardbreak_if_not_bol();
1010 self.maybe_print_comment(span.lo());
1011 self.print_outer_attributes(attrs);
1013 ast::ForeignItemKind::Fn(def, sig, gen, body) => {
1014 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1016 ast::ForeignItemKind::Static(ty, mutbl, body) => {
1017 let def = ast::Defaultness::Final;
1018 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1020 ast::ForeignItemKind::TyAlias(def, generics, bounds, ty) => {
1021 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1023 ast::ForeignItemKind::MacCall(m) => {
1025 if m.args.need_semicolon() {
1030 self.ann.post(self, AnnNode::SubItem(id))
1033 fn print_item_const(
1036 mutbl: Option<ast::Mutability>,
1038 body: Option<&ast::Expr>,
1039 vis: &ast::Visibility,
1040 defaultness: ast::Defaultness,
1043 self.print_visibility(vis);
1044 self.print_defaultness(defaultness);
1045 let leading = match mutbl {
1047 Some(ast::Mutability::Not) => "static",
1048 Some(ast::Mutability::Mut) => "static mut",
1050 self.word_space(leading);
1051 self.print_ident(ident);
1052 self.word_space(":");
1053 self.print_type(ty);
1055 self.end(); // end the head-ibox
1056 if let Some(body) = body {
1057 self.word_space("=");
1058 self.print_expr(body);
1061 self.end(); // end the outer cbox
1064 fn print_associated_type(
1067 generics: &ast::Generics,
1068 bounds: &ast::GenericBounds,
1069 ty: Option<&ast::Ty>,
1070 vis: &ast::Visibility,
1071 defaultness: ast::Defaultness,
1074 self.print_visibility(vis);
1075 self.print_defaultness(defaultness);
1076 self.word_space("type");
1077 self.print_ident(ident);
1078 self.print_generic_params(&generics.params);
1079 self.print_type_bounds(":", bounds);
1080 self.print_where_clause(&generics.where_clause);
1081 if let Some(ty) = ty {
1083 self.word_space("=");
1084 self.print_type(ty);
1087 self.end(); // end inner head-block
1088 self.end(); // end outer head-block
1091 /// Pretty-prints an item.
1092 crate fn print_item(&mut self, item: &ast::Item) {
1093 self.hardbreak_if_not_bol();
1094 self.maybe_print_comment(item.span.lo());
1095 self.print_outer_attributes(&item.attrs);
1096 self.ann.pre(self, AnnNode::Item(item));
1098 ast::ItemKind::ExternCrate(orig_name) => {
1099 self.head(visibility_qualified(&item.vis, "extern crate"));
1100 if let Some(orig_name) = orig_name {
1101 self.print_name(orig_name);
1106 self.print_ident(item.ident);
1108 self.end(); // end inner head-block
1109 self.end(); // end outer head-block
1111 ast::ItemKind::Use(ref tree) => {
1112 self.head(visibility_qualified(&item.vis, "use"));
1113 self.print_use_tree(tree);
1115 self.end(); // end inner head-block
1116 self.end(); // end outer head-block
1118 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1119 let def = ast::Defaultness::Final;
1120 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1122 ast::ItemKind::Const(def, ref ty, ref body) => {
1123 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1125 ast::ItemKind::Fn(def, ref sig, ref gen, ref body) => {
1126 let body = body.as_deref();
1127 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1129 ast::ItemKind::Mod(ref _mod) => {
1130 self.head(visibility_qualified(&item.vis, "mod"));
1131 self.print_ident(item.ident);
1133 if _mod.inline || self.is_expanded {
1136 self.print_mod(_mod, &item.attrs);
1137 self.bclose(item.span);
1140 self.end(); // end inner head-block
1141 self.end(); // end outer head-block
1144 ast::ItemKind::ForeignMod(ref nmod) => {
1145 self.head("extern");
1146 if let Some(abi) = nmod.abi {
1147 self.print_literal(&abi.as_lit());
1151 self.print_foreign_mod(nmod, &item.attrs);
1152 self.bclose(item.span);
1154 ast::ItemKind::GlobalAsm(ref ga) => {
1155 self.head(visibility_qualified(&item.vis, "global_asm!"));
1156 self.s.word(ga.asm.to_string());
1159 ast::ItemKind::TyAlias(def, ref generics, ref bounds, ref ty) => {
1160 let ty = ty.as_deref();
1161 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1163 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1164 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1166 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1167 self.head(visibility_qualified(&item.vis, "struct"));
1168 self.print_struct(struct_def, generics, item.ident, item.span, true);
1170 ast::ItemKind::Union(ref struct_def, ref generics) => {
1171 self.head(visibility_qualified(&item.vis, "union"));
1172 self.print_struct(struct_def, generics, item.ident, item.span, true);
1174 ast::ItemKind::Impl {
1185 self.print_visibility(&item.vis);
1186 self.print_defaultness(defaultness);
1187 self.print_unsafety(unsafety);
1188 self.word_nbsp("impl");
1189 self.print_constness(constness);
1191 if !generics.params.is_empty() {
1192 self.print_generic_params(&generics.params);
1196 if let ast::ImplPolarity::Negative(_) = polarity {
1200 if let Some(ref t) = *of_trait {
1201 self.print_trait_ref(t);
1203 self.word_space("for");
1206 self.print_type(self_ty);
1207 self.print_where_clause(&generics.where_clause);
1211 self.print_inner_attributes(&item.attrs);
1212 for impl_item in items {
1213 self.print_assoc_item(impl_item);
1215 self.bclose(item.span);
1217 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1219 self.print_visibility(&item.vis);
1220 self.print_unsafety(unsafety);
1221 self.print_is_auto(is_auto);
1222 self.word_nbsp("trait");
1223 self.print_ident(item.ident);
1224 self.print_generic_params(&generics.params);
1225 let mut real_bounds = Vec::with_capacity(bounds.len());
1226 for b in bounds.iter() {
1227 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1229 self.word_space("for ?");
1230 self.print_trait_ref(&ptr.trait_ref);
1232 real_bounds.push(b.clone());
1235 self.print_type_bounds(":", &real_bounds[..]);
1236 self.print_where_clause(&generics.where_clause);
1239 self.print_inner_attributes(&item.attrs);
1240 for trait_item in trait_items {
1241 self.print_assoc_item(trait_item);
1243 self.bclose(item.span);
1245 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1247 self.print_visibility(&item.vis);
1248 self.word_nbsp("trait");
1249 self.print_ident(item.ident);
1250 self.print_generic_params(&generics.params);
1251 let mut real_bounds = Vec::with_capacity(bounds.len());
1252 // FIXME(durka) this seems to be some quite outdated syntax
1253 for b in bounds.iter() {
1254 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1256 self.word_space("for ?");
1257 self.print_trait_ref(&ptr.trait_ref);
1259 real_bounds.push(b.clone());
1263 self.print_type_bounds("=", &real_bounds[..]);
1264 self.print_where_clause(&generics.where_clause);
1267 ast::ItemKind::MacCall(ref mac) => {
1268 self.print_mac(mac);
1269 if mac.args.need_semicolon() {
1273 ast::ItemKind::MacroDef(ref macro_def) => {
1274 let (kw, has_bang) = if macro_def.macro_rules {
1275 ("macro_rules", true)
1277 self.print_visibility(&item.vis);
1280 self.print_mac_common(
1281 Some(MacHeader::Keyword(kw)),
1284 macro_def.body.delim(),
1285 ¯o_def.body.inner_tokens(),
1291 self.ann.post(self, AnnNode::Item(item))
1294 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1295 self.print_path(&t.path, false, 0)
1298 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1299 if !generic_params.is_empty() {
1301 self.print_generic_params(generic_params);
1306 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1307 self.print_formal_generic_params(&t.bound_generic_params);
1308 self.print_trait_ref(&t.trait_ref)
1311 crate fn print_enum_def(
1313 enum_definition: &ast::EnumDef,
1314 generics: &ast::Generics,
1316 span: rustc_span::Span,
1317 visibility: &ast::Visibility,
1319 self.head(visibility_qualified(visibility, "enum"));
1320 self.print_ident(ident);
1321 self.print_generic_params(&generics.params);
1322 self.print_where_clause(&generics.where_clause);
1324 self.print_variants(&enum_definition.variants, span)
1327 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1330 self.space_if_not_bol();
1331 self.maybe_print_comment(v.span.lo());
1332 self.print_outer_attributes(&v.attrs);
1333 self.ibox(INDENT_UNIT);
1334 self.print_variant(v);
1337 self.maybe_print_trailing_comment(v.span, None);
1342 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1344 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1345 ast::VisibilityKind::Crate(sugar) => match sugar {
1346 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1347 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1349 ast::VisibilityKind::Restricted { ref path, .. } => {
1350 let path = to_string(|s| s.print_path(path, false, 0));
1351 if path == "self" || path == "super" {
1352 self.word_nbsp(format!("pub({})", path))
1354 self.word_nbsp(format!("pub(in {})", path))
1357 ast::VisibilityKind::Inherited => {}
1361 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1362 if let ast::Defaultness::Default(_) = defaultness {
1363 self.word_nbsp("default");
1367 crate fn print_struct(
1369 struct_def: &ast::VariantData,
1370 generics: &ast::Generics,
1372 span: rustc_span::Span,
1373 print_finalizer: bool,
1375 self.print_ident(ident);
1376 self.print_generic_params(&generics.params);
1378 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1379 if let ast::VariantData::Tuple(..) = struct_def {
1381 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1382 s.maybe_print_comment(field.span.lo());
1383 s.print_outer_attributes(&field.attrs);
1384 s.print_visibility(&field.vis);
1385 s.print_type(&field.ty)
1389 self.print_where_clause(&generics.where_clause);
1390 if print_finalizer {
1394 self.end(); // Close the outer-box.
1396 ast::VariantData::Struct(..) => {
1397 self.print_where_clause(&generics.where_clause);
1400 self.hardbreak_if_not_bol();
1402 for field in struct_def.fields() {
1403 self.hardbreak_if_not_bol();
1404 self.maybe_print_comment(field.span.lo());
1405 self.print_outer_attributes(&field.attrs);
1406 self.print_visibility(&field.vis);
1407 self.print_ident(field.ident.unwrap());
1408 self.word_nbsp(":");
1409 self.print_type(&field.ty);
1418 crate fn print_variant(&mut self, v: &ast::Variant) {
1420 self.print_visibility(&v.vis);
1421 let generics = ast::Generics::default();
1422 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1423 if let Some(ref d) = v.disr_expr {
1425 self.word_space("=");
1426 self.print_expr(&d.value)
1430 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1431 let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1432 self.ann.pre(self, AnnNode::SubItem(id));
1433 self.hardbreak_if_not_bol();
1434 self.maybe_print_comment(span.lo());
1435 self.print_outer_attributes(attrs);
1437 ast::AssocItemKind::Fn(def, sig, gen, body) => {
1438 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
1440 ast::AssocItemKind::Const(def, ty, body) => {
1441 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1443 ast::AssocItemKind::TyAlias(def, generics, bounds, ty) => {
1444 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1446 ast::AssocItemKind::MacCall(m) => {
1448 if m.args.need_semicolon() {
1453 self.ann.post(self, AnnNode::SubItem(id))
1456 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1457 self.maybe_print_comment(st.span.lo());
1459 ast::StmtKind::Local(ref loc) => {
1460 self.print_outer_attributes(&loc.attrs);
1461 self.space_if_not_bol();
1462 self.ibox(INDENT_UNIT);
1463 self.word_nbsp("let");
1465 self.ibox(INDENT_UNIT);
1466 self.print_local_decl(loc);
1468 if let Some(ref init) = loc.init {
1470 self.word_space("=");
1471 self.print_expr(init);
1476 ast::StmtKind::Item(ref item) => self.print_item(item),
1477 ast::StmtKind::Expr(ref expr) => {
1478 self.space_if_not_bol();
1479 self.print_expr_outer_attr_style(expr, false);
1480 if classify::expr_requires_semi_to_be_stmt(expr) {
1484 ast::StmtKind::Semi(ref expr) => {
1485 self.space_if_not_bol();
1486 self.print_expr_outer_attr_style(expr, false);
1489 ast::StmtKind::Empty => {
1490 self.space_if_not_bol();
1493 ast::StmtKind::MacCall(ref mac) => {
1494 let (ref mac, style, ref attrs) = **mac;
1495 self.space_if_not_bol();
1496 self.print_outer_attributes(attrs);
1497 self.print_mac(mac);
1498 if style == ast::MacStmtStyle::Semicolon {
1503 self.maybe_print_trailing_comment(st.span, None)
1506 crate fn print_block(&mut self, blk: &ast::Block) {
1507 self.print_block_with_attrs(blk, &[])
1510 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1511 self.print_block_maybe_unclosed(blk, &[], false)
1514 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1515 self.print_block_maybe_unclosed(blk, attrs, true)
1518 crate fn print_block_maybe_unclosed(
1521 attrs: &[ast::Attribute],
1525 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1526 BlockCheckMode::Default => (),
1528 self.maybe_print_comment(blk.span.lo());
1529 self.ann.pre(self, AnnNode::Block(blk));
1532 self.print_inner_attributes(attrs);
1534 for (i, st) in blk.stmts.iter().enumerate() {
1536 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1537 self.maybe_print_comment(st.span.lo());
1538 self.space_if_not_bol();
1539 self.print_expr_outer_attr_style(expr, false);
1540 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1542 _ => self.print_stmt(st),
1546 self.bclose_maybe_open(blk.span, close_box);
1547 self.ann.post(self, AnnNode::Block(blk))
1550 /// Print a `let pat = scrutinee` expression.
1551 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1552 self.s.word("let ");
1554 self.print_pat(pat);
1557 self.word_space("=");
1558 self.print_expr_cond_paren(
1560 Self::cond_needs_par(scrutinee)
1561 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1565 fn print_else(&mut self, els: Option<&ast::Expr>) {
1566 if let Some(_else) = els {
1568 // Another `else if` block.
1569 ast::ExprKind::If(ref i, ref then, ref e) => {
1570 self.cbox(INDENT_UNIT - 1);
1572 self.s.word(" else if ");
1573 self.print_expr_as_cond(i);
1575 self.print_block(then);
1576 self.print_else(e.as_deref())
1578 // Final `else` block.
1579 ast::ExprKind::Block(ref b, _) => {
1580 self.cbox(INDENT_UNIT - 1);
1582 self.s.word(" else ");
1585 // Constraints would be great here!
1587 panic!("print_if saw if with weird alternative");
1593 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1596 self.print_expr_as_cond(test);
1599 self.print_block(blk);
1600 self.print_else(elseopt)
1603 crate fn print_mac(&mut self, m: &ast::MacCall) {
1604 self.print_mac_common(
1605 Some(MacHeader::Path(&m.path)),
1609 &m.args.inner_tokens(),
1615 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1617 self.commasep_exprs(Inconsistent, args);
1621 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1622 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1625 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1626 /// `if cond { ... }`.
1627 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1628 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1631 /// Does `expr` need parenthesis when printed in a condition position?
1632 fn cond_needs_par(expr: &ast::Expr) -> bool {
1634 // These cases need parens due to the parse error observed in #26461: `if return {}`
1635 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1636 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1638 _ => parser::contains_exterior_struct_lit(expr),
1642 /// Prints `expr` or `(expr)` when `needs_par` holds.
1643 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1647 self.print_expr(expr);
1653 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1654 self.ibox(INDENT_UNIT);
1656 self.print_inner_attributes_inline(attrs);
1657 self.commasep_exprs(Inconsistent, &exprs[..]);
1662 fn print_expr_repeat(
1664 element: &ast::Expr,
1665 count: &ast::AnonConst,
1666 attrs: &[Attribute],
1668 self.ibox(INDENT_UNIT);
1670 self.print_inner_attributes_inline(attrs);
1671 self.print_expr(element);
1672 self.word_space(";");
1673 self.print_expr(&count.value);
1678 fn print_expr_struct(
1681 fields: &[ast::Field],
1682 wth: &Option<P<ast::Expr>>,
1683 attrs: &[Attribute],
1685 self.print_path(path, true, 0);
1687 self.print_inner_attributes_inline(attrs);
1692 s.print_outer_attributes(&field.attrs);
1693 s.ibox(INDENT_UNIT);
1694 if !field.is_shorthand {
1695 s.print_ident(field.ident);
1698 s.print_expr(&field.expr);
1705 self.ibox(INDENT_UNIT);
1706 if !fields.is_empty() {
1711 self.print_expr(expr);
1715 if !fields.is_empty() {
1723 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1725 self.print_inner_attributes_inline(attrs);
1726 self.commasep_exprs(Inconsistent, &exprs[..]);
1727 if exprs.len() == 1 {
1733 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1734 let prec = match func.kind {
1735 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1736 _ => parser::PREC_POSTFIX,
1739 self.print_expr_maybe_paren(func, prec);
1740 self.print_call_post(args)
1743 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1744 let base_args = &args[1..];
1745 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1747 self.print_ident(segment.ident);
1748 if let Some(ref args) = segment.args {
1749 self.print_generic_args(args, true);
1751 self.print_call_post(base_args)
1754 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1755 let assoc_op = AssocOp::from_ast_binop(op.node);
1756 let prec = assoc_op.precedence() as i8;
1757 let fixity = assoc_op.fixity();
1759 let (left_prec, right_prec) = match fixity {
1760 Fixity::Left => (prec, prec + 1),
1761 Fixity::Right => (prec + 1, prec),
1762 Fixity::None => (prec + 1, prec + 1),
1765 let left_prec = match (&lhs.kind, op.node) {
1766 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1767 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1768 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1769 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1770 parser::PREC_FORCE_PAREN
1772 // We are given `(let _ = a) OP b`.
1774 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1775 // as the parser will interpret this as `(let _ = a) OP b`.
1777 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1778 // parens are required since the parser would interpret `let a = b < c` as
1779 // `let a = (b < c)`. To achieve this, we force parens.
1780 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1781 parser::PREC_FORCE_PAREN
1786 self.print_expr_maybe_paren(lhs, left_prec);
1788 self.word_space(op.node.to_string());
1789 self.print_expr_maybe_paren(rhs, right_prec)
1792 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1793 self.s.word(ast::UnOp::to_string(op));
1794 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1797 fn print_expr_addr_of(
1799 kind: ast::BorrowKind,
1800 mutability: ast::Mutability,
1805 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1806 ast::BorrowKind::Raw => {
1807 self.word_nbsp("raw");
1808 self.print_mutability(mutability, true);
1811 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1814 pub fn print_expr(&mut self, expr: &ast::Expr) {
1815 self.print_expr_outer_attr_style(expr, true)
1818 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1819 self.maybe_print_comment(expr.span.lo());
1821 let attrs = &expr.attrs;
1823 self.print_outer_attributes_inline(attrs);
1825 self.print_outer_attributes(attrs);
1828 self.ibox(INDENT_UNIT);
1829 self.ann.pre(self, AnnNode::Expr(expr));
1831 ast::ExprKind::Box(ref expr) => {
1832 self.word_space("box");
1833 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1835 ast::ExprKind::Array(ref exprs) => {
1836 self.print_expr_vec(&exprs[..], attrs);
1838 ast::ExprKind::Repeat(ref element, ref count) => {
1839 self.print_expr_repeat(element, count, attrs);
1841 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1842 self.print_expr_struct(path, &fields[..], wth, attrs);
1844 ast::ExprKind::Tup(ref exprs) => {
1845 self.print_expr_tup(&exprs[..], attrs);
1847 ast::ExprKind::Call(ref func, ref args) => {
1848 self.print_expr_call(func, &args[..]);
1850 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1851 self.print_expr_method_call(segment, &args[..]);
1853 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1854 self.print_expr_binary(op, lhs, rhs);
1856 ast::ExprKind::Unary(op, ref expr) => {
1857 self.print_expr_unary(op, expr);
1859 ast::ExprKind::AddrOf(k, m, ref expr) => {
1860 self.print_expr_addr_of(k, m, expr);
1862 ast::ExprKind::Lit(ref lit) => {
1863 self.print_literal(lit);
1865 ast::ExprKind::Cast(ref expr, ref ty) => {
1866 let prec = AssocOp::As.precedence() as i8;
1867 self.print_expr_maybe_paren(expr, prec);
1869 self.word_space("as");
1870 self.print_type(ty);
1872 ast::ExprKind::Type(ref expr, ref ty) => {
1873 let prec = AssocOp::Colon.precedence() as i8;
1874 self.print_expr_maybe_paren(expr, prec);
1875 self.word_space(":");
1876 self.print_type(ty);
1878 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1879 self.print_let(pat, scrutinee);
1881 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1882 self.print_if(test, blk, elseopt.as_deref())
1884 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1885 if let Some(label) = opt_label {
1886 self.print_ident(label.ident);
1887 self.word_space(":");
1890 self.print_expr_as_cond(test);
1892 self.print_block_with_attrs(blk, attrs);
1894 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1895 if let Some(label) = opt_label {
1896 self.print_ident(label.ident);
1897 self.word_space(":");
1900 self.print_pat(pat);
1902 self.word_space("in");
1903 self.print_expr_as_cond(iter);
1905 self.print_block_with_attrs(blk, attrs);
1907 ast::ExprKind::Loop(ref blk, opt_label) => {
1908 if let Some(label) = opt_label {
1909 self.print_ident(label.ident);
1910 self.word_space(":");
1914 self.print_block_with_attrs(blk, attrs);
1916 ast::ExprKind::Match(ref expr, ref arms) => {
1917 self.cbox(INDENT_UNIT);
1918 self.ibox(INDENT_UNIT);
1919 self.word_nbsp("match");
1920 self.print_expr_as_cond(expr);
1923 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1925 self.print_arm(arm);
1927 self.bclose(expr.span);
1929 ast::ExprKind::Closure(
1937 self.print_movability(movability);
1938 self.print_asyncness(asyncness);
1939 self.print_capture_clause(capture_clause);
1941 self.print_fn_params_and_ret(decl, true);
1943 self.print_expr(body);
1944 self.end(); // need to close a box
1946 // a box will be closed by print_expr, but we didn't want an overall
1947 // wrapper so we closed the corresponding opening. so create an
1948 // empty box to satisfy the close.
1951 ast::ExprKind::Block(ref blk, opt_label) => {
1952 if let Some(label) = opt_label {
1953 self.print_ident(label.ident);
1954 self.word_space(":");
1956 // containing cbox, will be closed by print-block at }
1957 self.cbox(INDENT_UNIT);
1958 // head-box, will be closed by print-block after {
1960 self.print_block_with_attrs(blk, attrs);
1962 ast::ExprKind::Async(capture_clause, _, ref blk) => {
1963 self.word_nbsp("async");
1964 self.print_capture_clause(capture_clause);
1966 // cbox/ibox in analogy to the `ExprKind::Block` arm above
1967 self.cbox(INDENT_UNIT);
1969 self.print_block_with_attrs(blk, attrs);
1971 ast::ExprKind::Await(ref expr) => {
1972 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1973 self.s.word(".await");
1975 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
1976 let prec = AssocOp::Assign.precedence() as i8;
1977 self.print_expr_maybe_paren(lhs, prec + 1);
1979 self.word_space("=");
1980 self.print_expr_maybe_paren(rhs, prec);
1982 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1983 let prec = AssocOp::Assign.precedence() as i8;
1984 self.print_expr_maybe_paren(lhs, prec + 1);
1986 self.s.word(op.node.to_string());
1987 self.word_space("=");
1988 self.print_expr_maybe_paren(rhs, prec);
1990 ast::ExprKind::Field(ref expr, ident) => {
1991 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1993 self.print_ident(ident);
1995 ast::ExprKind::Index(ref expr, ref index) => {
1996 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1998 self.print_expr(index);
2001 ast::ExprKind::Range(ref start, ref end, limits) => {
2002 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2003 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2004 // Here we use a fake precedence value so that any child with lower precedence than
2005 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2006 let fake_prec = AssocOp::LOr.precedence() as i8;
2007 if let Some(ref e) = *start {
2008 self.print_expr_maybe_paren(e, fake_prec);
2010 if limits == ast::RangeLimits::HalfOpen {
2015 if let Some(ref e) = *end {
2016 self.print_expr_maybe_paren(e, fake_prec);
2019 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2020 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2021 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2022 self.s.word("break");
2024 if let Some(label) = opt_label {
2025 self.print_ident(label.ident);
2028 if let Some(ref expr) = *opt_expr {
2029 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2033 ast::ExprKind::Continue(opt_label) => {
2034 self.s.word("continue");
2036 if let Some(label) = opt_label {
2037 self.print_ident(label.ident);
2041 ast::ExprKind::Ret(ref result) => {
2042 self.s.word("return");
2043 if let Some(ref expr) = *result {
2045 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2048 ast::ExprKind::InlineAsm(ref a) => {
2051 Operand(&'a InlineAsmOperand),
2052 Options(InlineAsmOptions),
2055 let mut args = vec![];
2056 args.push(AsmArg::Template(InlineAsmTemplatePiece::to_string(&a.template)));
2057 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2058 if !a.options.is_empty() {
2059 args.push(AsmArg::Options(a.options));
2064 self.commasep(Consistent, &args, |s, arg| match arg {
2065 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2066 AsmArg::Operand(op) => {
2067 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r
2069 InlineAsmRegOrRegClass::Reg(r) => {
2070 s.print_symbol(*r, ast::StrStyle::Cooked)
2072 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2075 InlineAsmOperand::In { reg, expr } => {
2078 print_reg_or_class(s, reg);
2083 InlineAsmOperand::Out { reg, late, expr } => {
2084 s.word(if *late { "lateout" } else { "out" });
2086 print_reg_or_class(s, reg);
2090 Some(expr) => s.print_expr(expr),
2091 None => s.word("_"),
2094 InlineAsmOperand::InOut { reg, late, expr } => {
2095 s.word(if *late { "inlateout" } else { "inout" });
2097 print_reg_or_class(s, reg);
2102 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2103 s.word(if *late { "inlateout" } else { "inout" });
2105 print_reg_or_class(s, reg);
2108 s.print_expr(in_expr);
2112 Some(out_expr) => s.print_expr(out_expr),
2113 None => s.word("_"),
2116 InlineAsmOperand::Const { expr } => {
2121 InlineAsmOperand::Sym { expr } => {
2128 AsmArg::Options(opts) => {
2131 let mut options = vec![];
2132 if opts.contains(InlineAsmOptions::PURE) {
2133 options.push("pure");
2135 if opts.contains(InlineAsmOptions::NOMEM) {
2136 options.push("nomem");
2138 if opts.contains(InlineAsmOptions::READONLY) {
2139 options.push("readonly");
2141 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2142 options.push("preserves_flags");
2144 if opts.contains(InlineAsmOptions::NORETURN) {
2145 options.push("noreturn");
2147 if opts.contains(InlineAsmOptions::NOSTACK) {
2148 options.push("nostack");
2150 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2151 options.push("att_syntax");
2153 s.commasep(Inconsistent, &options, |s, &opt| {
2161 ast::ExprKind::LlvmInlineAsm(ref a) => {
2162 self.s.word("llvm_asm!");
2164 self.print_symbol(a.asm, a.asm_str_style);
2165 self.word_space(":");
2167 self.commasep(Inconsistent, &a.outputs, |s, out| {
2168 let constraint = out.constraint.as_str();
2169 let mut ch = constraint.chars();
2171 Some('=') if out.is_rw => {
2172 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2174 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2177 s.print_expr(&out.expr);
2181 self.word_space(":");
2183 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2184 s.print_symbol(co, ast::StrStyle::Cooked);
2190 self.word_space(":");
2192 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2193 s.print_symbol(co, ast::StrStyle::Cooked);
2196 let mut options = vec![];
2198 options.push("volatile");
2201 options.push("alignstack");
2203 if a.dialect == ast::LlvmAsmDialect::Intel {
2204 options.push("intel");
2207 if !options.is_empty() {
2209 self.word_space(":");
2210 self.commasep(Inconsistent, &options, |s, &co| {
2211 s.print_string(co, ast::StrStyle::Cooked);
2217 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2218 ast::ExprKind::Paren(ref e) => {
2220 self.print_inner_attributes_inline(attrs);
2224 ast::ExprKind::Yield(ref e) => {
2225 self.s.word("yield");
2227 if let Some(ref expr) = *e {
2229 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2232 ast::ExprKind::Try(ref e) => {
2233 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2236 ast::ExprKind::TryBlock(ref blk) => {
2239 self.print_block_with_attrs(blk, attrs)
2241 ast::ExprKind::Err => {
2243 self.s.word("/*ERROR*/");
2247 self.ann.post(self, AnnNode::Expr(expr));
2251 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2252 self.print_pat(&loc.pat);
2253 if let Some(ref ty) = loc.ty {
2254 self.word_space(":");
2255 self.print_type(ty);
2259 pub fn print_usize(&mut self, i: usize) {
2260 self.s.word(i.to_string())
2263 crate fn print_name(&mut self, name: Symbol) {
2264 self.s.word(name.to_string());
2265 self.ann.post(self, AnnNode::Name(&name))
2268 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2270 self.print_type(&qself.ty);
2271 if qself.position > 0 {
2273 self.word_space("as");
2274 let depth = path.segments.len() - qself.position;
2275 self.print_path(path, false, depth);
2279 let item_segment = path.segments.last().unwrap();
2280 self.print_ident(item_segment.ident);
2281 if let Some(ref args) = item_segment.args {
2282 self.print_generic_args(args, colons_before_params)
2286 crate fn print_pat(&mut self, pat: &ast::Pat) {
2287 self.maybe_print_comment(pat.span.lo());
2288 self.ann.pre(self, AnnNode::Pat(pat));
2289 /* Pat isn't normalized, but the beauty of it
2290 is that it doesn't matter */
2292 PatKind::Wild => self.s.word("_"),
2293 PatKind::Ident(binding_mode, ident, ref sub) => {
2294 match binding_mode {
2295 ast::BindingMode::ByRef(mutbl) => {
2296 self.word_nbsp("ref");
2297 self.print_mutability(mutbl, false);
2299 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2300 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2301 self.word_nbsp("mut");
2304 self.print_ident(ident);
2305 if let Some(ref p) = *sub {
2307 self.s.word_space("@");
2311 PatKind::TupleStruct(ref path, ref elts) => {
2312 self.print_path(path, true, 0);
2314 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2317 PatKind::Or(ref pats) => {
2318 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2320 PatKind::Path(None, ref path) => {
2321 self.print_path(path, true, 0);
2323 PatKind::Path(Some(ref qself), ref path) => {
2324 self.print_qpath(path, qself, false);
2326 PatKind::Struct(ref path, ref fields, etc) => {
2327 self.print_path(path, true, 0);
2329 self.word_space("{");
2334 s.cbox(INDENT_UNIT);
2335 if !f.is_shorthand {
2336 s.print_ident(f.ident);
2339 s.print_pat(&f.pat);
2345 if !fields.is_empty() {
2346 self.word_space(",");
2353 PatKind::Tuple(ref elts) => {
2355 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2356 if elts.len() == 1 {
2361 PatKind::Box(ref inner) => {
2362 self.s.word("box ");
2363 self.print_pat(inner);
2365 PatKind::Ref(ref inner, mutbl) => {
2367 if mutbl == ast::Mutability::Mut {
2368 self.s.word("mut ");
2370 self.print_pat(inner);
2372 PatKind::Lit(ref e) => self.print_expr(&**e),
2373 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2374 if let Some(e) = begin {
2379 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2380 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2381 RangeEnd::Excluded => self.s.word(".."),
2383 if let Some(e) = end {
2387 PatKind::Slice(ref elts) => {
2389 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2392 PatKind::Rest => self.s.word(".."),
2393 PatKind::Paren(ref inner) => {
2395 self.print_pat(inner);
2398 PatKind::MacCall(ref m) => self.print_mac(m),
2400 self.ann.post(self, AnnNode::Pat(pat))
2403 fn print_arm(&mut self, arm: &ast::Arm) {
2404 // Note, I have no idea why this check is necessary, but here it is.
2405 if arm.attrs.is_empty() {
2408 self.cbox(INDENT_UNIT);
2410 self.maybe_print_comment(arm.pat.span.lo());
2411 self.print_outer_attributes(&arm.attrs);
2412 self.print_pat(&arm.pat);
2414 if let Some(ref e) = arm.guard {
2415 self.word_space("if");
2419 self.word_space("=>");
2421 match arm.body.kind {
2422 ast::ExprKind::Block(ref blk, opt_label) => {
2423 if let Some(label) = opt_label {
2424 self.print_ident(label.ident);
2425 self.word_space(":");
2428 // The block will close the pattern's ibox.
2429 self.print_block_unclosed_indent(blk);
2431 // If it is a user-provided unsafe block, print a comma after it.
2432 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2437 self.end(); // Close the ibox for the pattern.
2438 self.print_expr(&arm.body);
2442 self.end(); // Close enclosing cbox.
2445 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2446 match explicit_self.node {
2447 SelfKind::Value(m) => {
2448 self.print_mutability(m, false);
2451 SelfKind::Region(ref lt, m) => {
2453 self.print_opt_lifetime(lt);
2454 self.print_mutability(m, false);
2457 SelfKind::Explicit(ref typ, m) => {
2458 self.print_mutability(m, false);
2459 self.s.word("self");
2460 self.word_space(":");
2461 self.print_type(typ)
2470 generics: &ast::Generics,
2471 vis: &ast::Visibility,
2472 defaultness: ast::Defaultness,
2473 body: Option<&ast::Block>,
2474 attrs: &[ast::Attribute],
2479 self.print_visibility(vis);
2480 self.print_defaultness(defaultness);
2481 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2482 if let Some(body) = body {
2484 self.print_block_with_attrs(body, attrs);
2493 header: ast::FnHeader,
2494 name: Option<Ident>,
2495 generics: &ast::Generics,
2497 self.print_fn_header_info(header);
2498 if let Some(name) = name {
2500 self.print_ident(name);
2502 self.print_generic_params(&generics.params);
2503 self.print_fn_params_and_ret(decl, false);
2504 self.print_where_clause(&generics.where_clause)
2507 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2508 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2510 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2512 self.print_fn_ret_ty(&decl.output)
2515 crate fn print_movability(&mut self, movability: ast::Movability) {
2517 ast::Movability::Static => self.word_space("static"),
2518 ast::Movability::Movable => {}
2522 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2523 if asyncness.is_async() {
2524 self.word_nbsp("async");
2528 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2529 match capture_clause {
2530 ast::CaptureBy::Value => self.word_space("move"),
2531 ast::CaptureBy::Ref => {}
2535 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2536 if !bounds.is_empty() {
2537 self.s.word(prefix);
2538 let mut first = true;
2539 for bound in bounds {
2540 if !(first && prefix.is_empty()) {
2546 self.word_space("+");
2550 GenericBound::Trait(tref, modifier) => {
2551 if modifier == &TraitBoundModifier::Maybe {
2554 self.print_poly_trait_ref(tref);
2556 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2562 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2563 self.print_name(lifetime.ident.name)
2566 crate fn print_lifetime_bounds(
2568 lifetime: ast::Lifetime,
2569 bounds: &ast::GenericBounds,
2571 self.print_lifetime(lifetime);
2572 if !bounds.is_empty() {
2574 for (i, bound) in bounds.iter().enumerate() {
2579 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2586 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2587 if generic_params.is_empty() {
2593 self.commasep(Inconsistent, &generic_params, |s, param| {
2594 s.print_outer_attributes_inline(¶m.attrs);
2597 ast::GenericParamKind::Lifetime => {
2598 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2599 s.print_lifetime_bounds(lt, ¶m.bounds)
2601 ast::GenericParamKind::Type { ref default } => {
2602 s.print_ident(param.ident);
2603 s.print_type_bounds(":", ¶m.bounds);
2604 if let Some(ref default) = default {
2607 s.print_type(default)
2610 ast::GenericParamKind::Const { ref ty, kw_span: _ } => {
2611 s.word_space("const");
2612 s.print_ident(param.ident);
2616 s.print_type_bounds(":", ¶m.bounds)
2624 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2625 if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2630 self.word_space("where");
2632 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2634 self.word_space(",");
2638 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2639 ref bound_generic_params,
2644 self.print_formal_generic_params(bound_generic_params);
2645 self.print_type(bounded_ty);
2646 self.print_type_bounds(":", bounds);
2648 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2653 self.print_lifetime_bounds(*lifetime, bounds);
2655 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2660 self.print_type(lhs_ty);
2662 self.word_space("=");
2663 self.print_type(rhs_ty);
2669 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2671 ast::UseTreeKind::Simple(rename, ..) => {
2672 self.print_path(&tree.prefix, false, 0);
2673 if let Some(rename) = rename {
2675 self.word_space("as");
2676 self.print_ident(rename);
2679 ast::UseTreeKind::Glob => {
2680 if !tree.prefix.segments.is_empty() {
2681 self.print_path(&tree.prefix, false, 0);
2686 ast::UseTreeKind::Nested(ref items) => {
2687 if tree.prefix.segments.is_empty() {
2690 self.print_path(&tree.prefix, false, 0);
2693 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2694 this.print_use_tree(tree)
2701 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2703 ast::Mutability::Mut => self.word_nbsp("mut"),
2704 ast::Mutability::Not => {
2706 self.word_nbsp("const");
2712 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2713 self.print_mutability(mt.mutbl, print_const);
2714 self.print_type(&mt.ty)
2717 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2718 self.ibox(INDENT_UNIT);
2720 self.print_outer_attributes_inline(&input.attrs);
2722 match input.ty.kind {
2723 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2725 if let Some(eself) = input.to_self() {
2726 self.print_explicit_self(&eself);
2728 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2729 ident.name == kw::Invalid
2734 self.print_pat(&input.pat);
2738 self.print_type(&input.ty);
2745 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2746 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2747 self.space_if_not_bol();
2748 self.ibox(INDENT_UNIT);
2749 self.word_space("->");
2750 self.print_type(ty);
2752 self.maybe_print_comment(ty.span.lo());
2756 crate fn print_ty_fn(
2759 unsafety: ast::Unsafe,
2761 name: Option<Ident>,
2762 generic_params: &[ast::GenericParam],
2764 self.ibox(INDENT_UNIT);
2765 if !generic_params.is_empty() {
2767 self.print_generic_params(generic_params);
2769 let generics = ast::Generics {
2771 where_clause: ast::WhereClause {
2772 has_where_token: false,
2773 predicates: Vec::new(),
2774 span: rustc_span::DUMMY_SP,
2776 span: rustc_span::DUMMY_SP,
2778 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2779 self.print_fn(decl, header, name, &generics);
2783 crate fn maybe_print_trailing_comment(
2785 span: rustc_span::Span,
2786 next_pos: Option<BytePos>,
2788 if let Some(cmnts) = self.comments() {
2789 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2790 self.print_comment(&cmnt);
2795 crate fn print_remaining_comments(&mut self) {
2796 // If there aren't any remaining comments, then we need to manually
2797 // make sure there is a line break at the end.
2798 if self.next_comment().is_none() {
2801 while let Some(ref cmnt) = self.next_comment() {
2802 self.print_comment(cmnt);
2806 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2807 self.print_constness(header.constness);
2808 self.print_asyncness(header.asyncness);
2809 self.print_unsafety(header.unsafety);
2812 ast::Extern::None => {}
2813 ast::Extern::Implicit => {
2814 self.word_nbsp("extern");
2816 ast::Extern::Explicit(abi) => {
2817 self.word_nbsp("extern");
2818 self.print_literal(&abi.as_lit());
2826 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2828 ast::Unsafe::No => {}
2829 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2833 crate fn print_constness(&mut self, s: ast::Const) {
2835 ast::Const::No => {}
2836 ast::Const::Yes(_) => self.word_nbsp("const"),
2840 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2842 ast::IsAuto::Yes => self.word_nbsp("auto"),
2843 ast::IsAuto::No => {}