1 use crate::pp::Breaks::{Consistent, Inconsistent};
2 use crate::pp::{self, Breaks};
4 use rustc_span::edition::Edition;
5 use rustc_span::source_map::{dummy_spanned, SourceMap, Spanned};
6 use rustc_span::symbol::{kw, sym};
7 use rustc_span::{BytePos, FileName, Span};
8 use syntax::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
9 use syntax::ast::{Attribute, GenericArg, MacArgs};
10 use syntax::ast::{GenericBound, SelfKind, TraitBoundModifier};
13 use syntax::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
14 use syntax::tokenstream::{self, TokenStream, TokenTree};
15 use syntax::util::parser::{self, AssocOp, Fixity};
16 use syntax::util::{classify, comments};
23 pub enum MacHeader<'a> {
25 Keyword(&'static str),
28 pub enum AnnNode<'a> {
29 Ident(&'a ast::Ident),
31 Block(&'a ast::Block),
36 Crate(&'a ast::Crate),
40 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
44 #[derive(Copy, Clone)]
47 impl PpAnn for NoAnn {}
49 pub struct Comments<'a> {
51 comments: Vec<comments::Comment>,
55 impl<'a> Comments<'a> {
56 pub fn new(cm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
57 let comments = comments::gather_comments(cm, filename, input);
58 Comments { cm, comments, current: 0 }
61 pub fn next(&self) -> Option<comments::Comment> {
62 self.comments.get(self.current).cloned()
65 pub fn trailing_comment(
67 span: rustc_span::Span,
68 next_pos: Option<BytePos>,
69 ) -> Option<comments::Comment> {
70 if let Some(cmnt) = self.next() {
71 if cmnt.style != comments::Trailing {
74 let span_line = self.cm.lookup_char_pos(span.hi());
75 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
76 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
77 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
86 pub struct State<'a> {
88 comments: Option<Comments<'a>>,
89 ann: &'a (dyn PpAnn + 'a),
93 crate const INDENT_UNIT: usize = 4;
95 /// Requires you to pass an input filename and reader so that
96 /// it can scan the input text for comments to copy forward.
97 pub fn print_crate<'a>(
105 has_injected_crate: bool,
109 comments: Some(Comments::new(cm, filename, input)),
114 if is_expanded && has_injected_crate {
115 // We need to print `#![no_std]` (and its feature gate) so that
116 // compiling pretty-printed source won't inject libstd again.
117 // However, we don't want these attributes in the AST because
118 // of the feature gate, so we fake them up here.
120 // `#![feature(prelude_import)]`
121 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_dummy_span(sym::prelude_import));
122 let list = attr::mk_list_item(ast::Ident::with_dummy_span(sym::feature), vec![pi_nested]);
123 let fake_attr = attr::mk_attr_inner(list);
124 s.print_attribute(&fake_attr);
126 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
127 // root, so this is not needed, and actually breaks things.
128 if edition == Edition::Edition2015 {
130 let no_std_meta = attr::mk_word_item(ast::Ident::with_dummy_span(sym::no_std));
131 let fake_attr = attr::mk_attr_inner(no_std_meta);
132 s.print_attribute(&fake_attr);
136 s.print_mod(&krate.module, &krate.attrs);
137 s.print_remaining_comments();
138 s.ann.post(&mut s, AnnNode::Crate(krate));
142 pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
144 State { s: pp::mk_printer(), comments: None, ann: &NoAnn, is_expanded: false };
149 // This makes comma-separated lists look slightly nicer,
150 // and also addresses a specific regression described in issue #63896.
151 fn tt_prepend_space(tt: &TokenTree) -> bool {
153 TokenTree::Token(token) => match token.kind {
154 token::Comma => false,
161 fn binop_to_string(op: BinOpToken) -> &'static str {
167 token::Percent => "%",
176 pub fn literal_to_string(lit: token::Lit) -> String {
177 let token::Lit { kind, symbol, suffix } = lit;
178 let mut out = match kind {
179 token::Byte => format!("b'{}'", symbol),
180 token::Char => format!("'{}'", symbol),
181 token::Str => format!("\"{}\"", symbol),
182 token::StrRaw(n) => {
183 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
185 token::ByteStr => format!("b\"{}\"", symbol),
186 token::ByteStrRaw(n) => {
187 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
189 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
192 if let Some(suffix) = suffix {
193 out.push_str(&suffix.as_str())
199 /// Print an ident from AST, `$crate` is converted into its respective crate name.
200 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
201 ident_to_string(ident.name, is_raw, Some(ident.span))
204 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
205 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
206 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
207 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
208 // hygiene data, most importantly name of the crate it refers to.
209 // As a result we print `$crate` as `crate` if it refers to the local crate
210 // and as `::other_crate_name` if it refers to some other crate.
211 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
212 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
213 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
214 // done for a token stream or a single token.
215 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
217 format!("r#{}", name)
219 if name == kw::DollarCrate {
220 if let Some(span) = convert_dollar_crate {
221 let converted = span.ctxt().dollar_crate_name();
222 return if converted.is_path_segment_keyword() {
223 converted.to_string()
225 format!("::{}", converted)
233 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
234 pub fn token_kind_to_string(tok: &TokenKind) -> String {
235 token_kind_to_string_ext(tok, None)
238 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
240 token::Eq => "=".to_string(),
241 token::Lt => "<".to_string(),
242 token::Le => "<=".to_string(),
243 token::EqEq => "==".to_string(),
244 token::Ne => "!=".to_string(),
245 token::Ge => ">=".to_string(),
246 token::Gt => ">".to_string(),
247 token::Not => "!".to_string(),
248 token::Tilde => "~".to_string(),
249 token::OrOr => "||".to_string(),
250 token::AndAnd => "&&".to_string(),
251 token::BinOp(op) => binop_to_string(op).to_string(),
252 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
254 /* Structural symbols */
255 token::At => "@".to_string(),
256 token::Dot => ".".to_string(),
257 token::DotDot => "..".to_string(),
258 token::DotDotDot => "...".to_string(),
259 token::DotDotEq => "..=".to_string(),
260 token::Comma => ",".to_string(),
261 token::Semi => ";".to_string(),
262 token::Colon => ":".to_string(),
263 token::ModSep => "::".to_string(),
264 token::RArrow => "->".to_string(),
265 token::LArrow => "<-".to_string(),
266 token::FatArrow => "=>".to_string(),
267 token::OpenDelim(token::Paren) => "(".to_string(),
268 token::CloseDelim(token::Paren) => ")".to_string(),
269 token::OpenDelim(token::Bracket) => "[".to_string(),
270 token::CloseDelim(token::Bracket) => "]".to_string(),
271 token::OpenDelim(token::Brace) => "{".to_string(),
272 token::CloseDelim(token::Brace) => "}".to_string(),
273 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => " ".to_string(),
274 token::Pound => "#".to_string(),
275 token::Dollar => "$".to_string(),
276 token::Question => "?".to_string(),
277 token::SingleQuote => "'".to_string(),
280 token::Literal(lit) => literal_to_string(lit),
282 /* Name components */
283 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
284 token::Lifetime(s) => s.to_string(),
287 token::DocComment(s) => s.to_string(),
288 token::Eof => "<eof>".to_string(),
289 token::Whitespace => " ".to_string(),
290 token::Comment => "/* */".to_string(),
291 token::Shebang(s) => format!("/* shebang: {}*/", s),
292 token::Unknown(s) => s.to_string(),
294 token::Interpolated(ref nt) => nonterminal_to_string(nt),
298 /// Print the token precisely, without converting `$crate` into its respective crate name.
299 pub fn token_to_string(token: &Token) -> String {
300 token_to_string_ext(token, false)
303 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
304 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
305 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
308 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
310 token::NtExpr(ref e) => expr_to_string(e),
311 token::NtMeta(ref e) => attr_item_to_string(e),
312 token::NtTy(ref e) => ty_to_string(e),
313 token::NtPath(ref e) => path_to_string(e),
314 token::NtItem(ref e) => item_to_string(e),
315 token::NtBlock(ref e) => block_to_string(e),
316 token::NtStmt(ref e) => stmt_to_string(e),
317 token::NtPat(ref e) => pat_to_string(e),
318 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
319 token::NtLifetime(e) => e.to_string(),
320 token::NtLiteral(ref e) => expr_to_string(e),
321 token::NtTT(ref tree) => tt_to_string(tree.clone()),
322 // FIXME(Centril): merge these variants.
323 token::NtImplItem(ref e) | token::NtTraitItem(ref e) => assoc_item_to_string(e),
324 token::NtVis(ref e) => vis_to_string(e),
325 token::NtForeignItem(ref e) => foreign_item_to_string(e),
329 pub fn ty_to_string(ty: &ast::Ty) -> String {
330 to_string(|s| s.print_type(ty))
333 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
334 to_string(|s| s.print_type_bounds("", bounds))
337 pub fn pat_to_string(pat: &ast::Pat) -> String {
338 to_string(|s| s.print_pat(pat))
341 pub fn expr_to_string(e: &ast::Expr) -> String {
342 to_string(|s| s.print_expr(e))
345 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
346 to_string(|s| s.print_tt(tt, false))
349 pub fn tts_to_string(tokens: TokenStream) -> String {
350 to_string(|s| s.print_tts(tokens, false))
353 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
354 to_string(|s| s.print_stmt(stmt))
357 pub fn item_to_string(i: &ast::Item) -> String {
358 to_string(|s| s.print_item(i))
361 fn assoc_item_to_string(i: &ast::AssocItem) -> String {
362 to_string(|s| s.print_assoc_item(i))
365 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
366 to_string(|s| s.print_generic_params(generic_params))
369 pub fn path_to_string(p: &ast::Path) -> String {
370 to_string(|s| s.print_path(p, false, 0))
373 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
374 to_string(|s| s.print_path_segment(p, false))
377 pub fn vis_to_string(v: &ast::Visibility) -> String {
378 to_string(|s| s.print_visibility(v))
381 fn block_to_string(blk: &ast::Block) -> String {
383 // Containing cbox, will be closed by `print_block` at `}`.
385 // Head-ibox, will be closed by `print_block` after `{`.
391 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
392 to_string(|s| s.print_meta_list_item(li))
395 fn attr_item_to_string(ai: &ast::AttrItem) -> String {
396 to_string(|s| s.print_attr_item(ai, ai.path.span))
399 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
400 to_string(|s| s.print_attribute(attr))
403 pub fn param_to_string(arg: &ast::Param) -> String {
404 to_string(|s| s.print_param(arg, false))
407 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
408 to_string(|s| s.print_foreign_item(arg))
411 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
412 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
415 impl std::ops::Deref for State<'_> {
416 type Target = pp::Printer;
417 fn deref(&self) -> &Self::Target {
422 impl std::ops::DerefMut for State<'_> {
423 fn deref_mut(&mut self) -> &mut Self::Target {
428 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
429 fn comments(&mut self) -> &mut Option<Comments<'a>>;
430 fn print_ident(&mut self, ident: ast::Ident);
431 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
441 F: FnMut(&mut Self, &T),
444 if let Some((first, rest)) = elts.split_first() {
450 self.word_space(sep);
457 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
459 F: FnMut(&mut Self, &T),
461 self.strsep(",", false, b, elts, op)
464 fn maybe_print_comment(&mut self, pos: BytePos) {
465 while let Some(ref cmnt) = self.next_comment() {
467 self.print_comment(cmnt);
474 fn print_comment(&mut self, cmnt: &comments::Comment) {
477 assert_eq!(cmnt.lines.len(), 1);
479 self.word(cmnt.lines[0].clone());
482 comments::Isolated => {
483 self.hardbreak_if_not_bol();
484 for line in &cmnt.lines {
485 // Don't print empty lines because they will end up as trailing
487 if !line.is_empty() {
488 self.word(line.clone());
493 comments::Trailing => {
494 if !self.is_beginning_of_line() {
497 if cmnt.lines.len() == 1 {
498 self.word(cmnt.lines[0].clone());
502 for line in &cmnt.lines {
503 if !line.is_empty() {
504 self.word(line.clone());
511 comments::BlankLine => {
512 // We need to do at least one, possibly two hardbreaks.
513 let twice = match self.last_token() {
514 pp::Token::String(s) => ";" == s,
515 pp::Token::Begin(_) => true,
516 pp::Token::End => true,
525 if let Some(cm) = self.comments() {
530 fn next_comment(&mut self) -> Option<comments::Comment> {
531 self.comments().as_mut().and_then(|c| c.next())
534 fn print_literal(&mut self, lit: &ast::Lit) {
535 self.maybe_print_comment(lit.span.lo());
536 self.word(lit.token.to_string())
539 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
540 let st = match style {
541 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
542 ast::StrStyle::Raw(n) => {
543 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
549 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
550 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
553 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
554 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
557 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
558 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
561 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
562 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
565 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
566 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
569 fn print_either_attributes(
571 attrs: &[ast::Attribute],
572 kind: ast::AttrStyle,
574 trailing_hardbreak: bool,
578 if attr.style == kind {
579 self.print_attribute_inline(attr, is_inline);
586 if count > 0 && trailing_hardbreak && !is_inline {
587 self.hardbreak_if_not_bol();
591 fn print_attribute(&mut self, attr: &ast::Attribute) {
592 self.print_attribute_inline(attr, false)
595 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
597 self.hardbreak_if_not_bol();
599 self.maybe_print_comment(attr.span.lo());
601 ast::AttrKind::Normal(ref item) => {
603 ast::AttrStyle::Inner => self.word("#!["),
604 ast::AttrStyle::Outer => self.word("#["),
606 self.print_attr_item(&item, attr.span);
609 ast::AttrKind::DocComment(comment) => {
610 self.word(comment.to_string());
616 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
619 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
620 Some(MacHeader::Path(&item.path)),
628 MacArgs::Empty | MacArgs::Eq(..) => {
629 self.print_path(&item.path, false, 0);
630 if let MacArgs::Eq(_, tokens) = &item.args {
632 self.word_space("=");
633 self.print_tts(tokens.clone(), true);
640 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
642 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
643 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
647 fn print_meta_item(&mut self, item: &ast::MetaItem) {
648 self.ibox(INDENT_UNIT);
650 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
651 ast::MetaItemKind::NameValue(ref value) => {
652 self.print_path(&item.path, false, 0);
654 self.word_space("=");
655 self.print_literal(value);
657 ast::MetaItemKind::List(ref items) => {
658 self.print_path(&item.path, false, 0);
660 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
667 /// This doesn't deserve to be called "pretty" printing, but it should be
668 /// meaning-preserving. A quick hack that might help would be to look at the
669 /// spans embedded in the TTs to decide where to put spaces and newlines.
670 /// But it'd be better to parse these according to the grammar of the
671 /// appropriate macro, transcribe back into the grammar we just parsed from,
672 /// and then pretty-print the resulting AST nodes (so, e.g., we print
673 /// expression arguments as expressions). It can be done! I think.
674 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
676 TokenTree::Token(ref token) => {
677 self.word(token_to_string_ext(&token, convert_dollar_crate));
679 token::DocComment(..) => self.hardbreak(),
683 TokenTree::Delimited(dspan, delim, tts) => {
684 self.print_mac_common(
690 convert_dollar_crate,
697 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
698 for (i, tt) in tts.into_trees().enumerate() {
699 if i != 0 && tt_prepend_space(&tt) {
702 self.print_tt(tt, convert_dollar_crate);
708 header: Option<MacHeader<'_>>,
710 ident: Option<ast::Ident>,
713 convert_dollar_crate: bool,
716 if delim == DelimToken::Brace {
717 self.cbox(INDENT_UNIT);
720 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
721 Some(MacHeader::Keyword(kw)) => self.word(kw),
727 if let Some(ident) = ident {
729 self.print_ident(ident);
732 DelimToken::Brace => {
733 if header.is_some() || has_bang || ident.is_some() {
741 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
744 self.print_tts(tts, convert_dollar_crate);
747 DelimToken::Brace => self.bclose(span),
748 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
752 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
753 self.maybe_print_comment(path.span.lo());
755 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
759 self.print_path_segment(segment, colons_before_params);
763 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
764 if segment.ident.name != kw::PathRoot {
765 self.print_ident(segment.ident);
766 if let Some(ref args) = segment.args {
767 self.print_generic_args(args, colons_before_params);
772 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
774 // Outer-box is consistent.
775 self.cbox(INDENT_UNIT);
776 // Head-box is inconsistent.
777 self.ibox(w.len() + 1);
778 // Keyword that starts the head.
784 fn bopen(&mut self) {
786 self.end(); // Close the head-box.
789 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
790 self.maybe_print_comment(span.hi());
791 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
794 self.end(); // Close the outer-box.
798 fn bclose(&mut self, span: rustc_span::Span) {
799 self.bclose_maybe_open(span, true)
802 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
803 if !self.is_beginning_of_line() {
804 self.break_offset(n, off)
806 if off != 0 && self.last_token().is_hardbreak_tok() {
807 // We do something pretty sketchy here: tuck the nonzero
808 // offset-adjustment we were going to deposit along with the
809 // break into the previous hardbreak.
810 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
816 impl<'a> PrintState<'a> for State<'a> {
817 fn comments(&mut self) -> &mut Option<Comments<'a>> {
821 fn print_ident(&mut self, ident: ast::Ident) {
822 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
823 self.ann.post(self, AnnNode::Ident(&ident))
826 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
827 if colons_before_params {
832 ast::GenericArgs::AngleBracketed(ref data) => {
835 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
836 s.print_generic_arg(generic_arg)
839 let mut comma = data.args.len() != 0;
841 for constraint in data.constraints.iter() {
845 self.print_ident(constraint.ident);
847 match constraint.kind {
848 ast::AssocTyConstraintKind::Equality { ref ty } => {
849 self.word_space("=");
852 ast::AssocTyConstraintKind::Bound { ref bounds } => {
853 self.print_type_bounds(":", &*bounds);
862 ast::GenericArgs::Parenthesized(ref data) => {
864 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
866 self.print_fn_ret_ty(&data.output);
873 // Synthesizes a comment that was not textually present in the original source
875 pub fn synth_comment(&mut self, text: String) {
883 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
885 F: FnMut(&mut State<'_>, &T),
886 G: FnMut(&T) -> rustc_span::Span,
889 let len = elts.len();
892 self.maybe_print_comment(get_span(elt).hi());
897 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
898 self.space_if_not_bol();
904 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
905 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
908 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
909 self.print_inner_attributes(attrs);
910 for item in &_mod.items {
911 self.print_item(item);
915 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
916 self.print_inner_attributes(attrs);
917 for item in &nmod.items {
918 self.print_foreign_item(item);
922 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
923 if let Some(lt) = *lifetime {
924 self.print_lifetime(lt);
929 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
931 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
932 GenericArg::Type(ty) => self.print_type(ty),
933 GenericArg::Const(ct) => self.print_expr(&ct.value),
937 pub fn print_type(&mut self, ty: &ast::Ty) {
938 self.maybe_print_comment(ty.span.lo());
941 ast::TyKind::Slice(ref ty) => {
946 ast::TyKind::Ptr(ref mt) => {
948 self.print_mt(mt, true);
950 ast::TyKind::Rptr(ref lifetime, ref mt) => {
952 self.print_opt_lifetime(lifetime);
953 self.print_mt(mt, false);
955 ast::TyKind::Never => {
958 ast::TyKind::Tup(ref elts) => {
960 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
966 ast::TyKind::Paren(ref typ) => {
968 self.print_type(typ);
971 ast::TyKind::BareFn(ref f) => {
972 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
974 ast::TyKind::Path(None, ref path) => {
975 self.print_path(path, false, 0);
977 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
978 ast::TyKind::TraitObject(ref bounds, syntax) => {
979 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
980 self.print_type_bounds(prefix, &bounds[..]);
982 ast::TyKind::ImplTrait(_, ref bounds) => {
983 self.print_type_bounds("impl", &bounds[..]);
985 ast::TyKind::Array(ref ty, ref length) => {
989 self.print_expr(&length.value);
992 ast::TyKind::Typeof(ref e) => {
993 self.s.word("typeof(");
994 self.print_expr(&e.value);
997 ast::TyKind::Infer => {
1000 ast::TyKind::Err => {
1002 self.s.word("/*ERROR*/");
1005 ast::TyKind::ImplicitSelf => {
1006 self.s.word("Self");
1008 ast::TyKind::Mac(ref m) => {
1011 ast::TyKind::CVarArgs => {
1018 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1019 self.hardbreak_if_not_bol();
1020 self.maybe_print_comment(item.span.lo());
1021 self.print_outer_attributes(&item.attrs);
1023 ast::ForeignItemKind::Fn(ref sig, ref gen, ref body) => {
1024 self.print_fn_full(sig, item.ident, gen, &item.vis, body.as_deref(), &item.attrs);
1026 ast::ForeignItemKind::Static(ref t, m) => {
1027 self.head(visibility_qualified(&item.vis, "static"));
1028 if m == ast::Mutability::Mut {
1029 self.word_space("mut");
1031 self.print_ident(item.ident);
1032 self.word_space(":");
1035 self.end(); // end the head-ibox
1036 self.end(); // end the outer cbox
1038 ast::ForeignItemKind::Ty => {
1039 self.head(visibility_qualified(&item.vis, "type"));
1040 self.print_ident(item.ident);
1042 self.end(); // end the head-ibox
1043 self.end(); // end the outer cbox
1045 ast::ForeignItemKind::Macro(ref m) => {
1047 if m.args.need_semicolon() {
1054 fn print_associated_const(
1058 default: Option<&ast::Expr>,
1059 vis: &ast::Visibility,
1061 self.s.word(visibility_qualified(vis, ""));
1062 self.word_space("const");
1063 self.print_ident(ident);
1064 self.word_space(":");
1065 self.print_type(ty);
1066 if let Some(expr) = default {
1068 self.word_space("=");
1069 self.print_expr(expr);
1074 fn print_associated_type(
1077 bounds: &ast::GenericBounds,
1078 ty: Option<&ast::Ty>,
1080 self.word_space("type");
1081 self.print_ident(ident);
1082 self.print_type_bounds(":", bounds);
1083 if let Some(ty) = ty {
1085 self.word_space("=");
1086 self.print_type(ty);
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, m, ref expr) => {
1119 self.head(visibility_qualified(&item.vis, "static"));
1120 if m == ast::Mutability::Mut {
1121 self.word_space("mut");
1123 self.print_ident(item.ident);
1124 self.word_space(":");
1125 self.print_type(ty);
1127 self.end(); // end the head-ibox
1129 self.word_space("=");
1130 self.print_expr(expr);
1132 self.end(); // end the outer cbox
1134 ast::ItemKind::Const(ref ty, ref expr) => {
1135 self.head(visibility_qualified(&item.vis, "const"));
1136 self.print_ident(item.ident);
1137 self.word_space(":");
1138 self.print_type(ty);
1140 self.end(); // end the head-ibox
1142 self.word_space("=");
1143 self.print_expr(expr);
1145 self.end(); // end the outer cbox
1147 ast::ItemKind::Fn(ref sig, ref gen, ref body) => {
1148 self.print_fn_full(sig, item.ident, gen, &item.vis, body.as_deref(), &item.attrs);
1150 ast::ItemKind::Mod(ref _mod) => {
1151 self.head(visibility_qualified(&item.vis, "mod"));
1152 self.print_ident(item.ident);
1154 if _mod.inline || self.is_expanded {
1157 self.print_mod(_mod, &item.attrs);
1158 self.bclose(item.span);
1161 self.end(); // end inner head-block
1162 self.end(); // end outer head-block
1165 ast::ItemKind::ForeignMod(ref nmod) => {
1166 self.head("extern");
1167 if let Some(abi) = nmod.abi {
1168 self.print_literal(&abi.as_lit());
1172 self.print_foreign_mod(nmod, &item.attrs);
1173 self.bclose(item.span);
1175 ast::ItemKind::GlobalAsm(ref ga) => {
1176 self.head(visibility_qualified(&item.vis, "global_asm!"));
1177 self.s.word(ga.asm.to_string());
1180 ast::ItemKind::TyAlias(ref ty, ref generics) => {
1181 self.head(visibility_qualified(&item.vis, "type"));
1182 self.print_ident(item.ident);
1183 self.print_generic_params(&generics.params);
1184 self.end(); // end the inner ibox
1186 self.print_where_clause(&generics.where_clause);
1188 self.word_space("=");
1189 self.print_type(ty);
1191 self.end(); // end the outer ibox
1193 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1194 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1196 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1197 self.head(visibility_qualified(&item.vis, "struct"));
1198 self.print_struct(struct_def, generics, item.ident, item.span, true);
1200 ast::ItemKind::Union(ref struct_def, ref generics) => {
1201 self.head(visibility_qualified(&item.vis, "union"));
1202 self.print_struct(struct_def, generics, item.ident, item.span, true);
1204 ast::ItemKind::Impl {
1215 self.print_visibility(&item.vis);
1216 self.print_defaultness(defaultness);
1217 self.print_unsafety(unsafety);
1218 self.word_nbsp("impl");
1219 self.print_constness(constness);
1221 if !generics.params.is_empty() {
1222 self.print_generic_params(&generics.params);
1226 if polarity == ast::ImplPolarity::Negative {
1230 if let Some(ref t) = *of_trait {
1231 self.print_trait_ref(t);
1233 self.word_space("for");
1236 self.print_type(self_ty);
1237 self.print_where_clause(&generics.where_clause);
1241 self.print_inner_attributes(&item.attrs);
1242 for impl_item in items {
1243 self.print_assoc_item(impl_item);
1245 self.bclose(item.span);
1247 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1249 self.print_visibility(&item.vis);
1250 self.print_unsafety(unsafety);
1251 self.print_is_auto(is_auto);
1252 self.word_nbsp("trait");
1253 self.print_ident(item.ident);
1254 self.print_generic_params(&generics.params);
1255 let mut real_bounds = Vec::with_capacity(bounds.len());
1256 for b in bounds.iter() {
1257 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1259 self.word_space("for ?");
1260 self.print_trait_ref(&ptr.trait_ref);
1262 real_bounds.push(b.clone());
1265 self.print_type_bounds(":", &real_bounds[..]);
1266 self.print_where_clause(&generics.where_clause);
1269 for trait_item in trait_items {
1270 self.print_assoc_item(trait_item);
1272 self.bclose(item.span);
1274 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1276 self.print_visibility(&item.vis);
1277 self.word_nbsp("trait");
1278 self.print_ident(item.ident);
1279 self.print_generic_params(&generics.params);
1280 let mut real_bounds = Vec::with_capacity(bounds.len());
1281 // FIXME(durka) this seems to be some quite outdated syntax
1282 for b in bounds.iter() {
1283 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1285 self.word_space("for ?");
1286 self.print_trait_ref(&ptr.trait_ref);
1288 real_bounds.push(b.clone());
1292 self.print_type_bounds("=", &real_bounds[..]);
1293 self.print_where_clause(&generics.where_clause);
1296 ast::ItemKind::Mac(ref mac) => {
1297 self.print_mac(mac);
1298 if mac.args.need_semicolon() {
1302 ast::ItemKind::MacroDef(ref macro_def) => {
1303 let (kw, has_bang) = if macro_def.legacy {
1304 ("macro_rules", true)
1306 self.print_visibility(&item.vis);
1309 self.print_mac_common(
1310 Some(MacHeader::Keyword(kw)),
1313 macro_def.body.delim(),
1314 macro_def.body.inner_tokens(),
1320 self.ann.post(self, AnnNode::Item(item))
1323 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1324 self.print_path(&t.path, false, 0)
1327 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1328 if !generic_params.is_empty() {
1330 self.print_generic_params(generic_params);
1335 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1336 self.print_formal_generic_params(&t.bound_generic_params);
1337 self.print_trait_ref(&t.trait_ref)
1340 crate fn print_enum_def(
1342 enum_definition: &ast::EnumDef,
1343 generics: &ast::Generics,
1345 span: rustc_span::Span,
1346 visibility: &ast::Visibility,
1348 self.head(visibility_qualified(visibility, "enum"));
1349 self.print_ident(ident);
1350 self.print_generic_params(&generics.params);
1351 self.print_where_clause(&generics.where_clause);
1353 self.print_variants(&enum_definition.variants, span)
1356 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1359 self.space_if_not_bol();
1360 self.maybe_print_comment(v.span.lo());
1361 self.print_outer_attributes(&v.attrs);
1362 self.ibox(INDENT_UNIT);
1363 self.print_variant(v);
1366 self.maybe_print_trailing_comment(v.span, None);
1371 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1373 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1374 ast::VisibilityKind::Crate(sugar) => match sugar {
1375 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1376 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1378 ast::VisibilityKind::Restricted { ref path, .. } => {
1379 let path = to_string(|s| s.print_path(path, false, 0));
1380 if path == "self" || path == "super" {
1381 self.word_nbsp(format!("pub({})", path))
1383 self.word_nbsp(format!("pub(in {})", path))
1386 ast::VisibilityKind::Inherited => {}
1390 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1391 if let ast::Defaultness::Default = defaultness {
1392 self.word_nbsp("default");
1396 crate fn print_struct(
1398 struct_def: &ast::VariantData,
1399 generics: &ast::Generics,
1401 span: rustc_span::Span,
1402 print_finalizer: bool,
1404 self.print_ident(ident);
1405 self.print_generic_params(&generics.params);
1407 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1408 if let ast::VariantData::Tuple(..) = struct_def {
1410 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1411 s.maybe_print_comment(field.span.lo());
1412 s.print_outer_attributes(&field.attrs);
1413 s.print_visibility(&field.vis);
1414 s.print_type(&field.ty)
1418 self.print_where_clause(&generics.where_clause);
1419 if print_finalizer {
1423 self.end(); // Close the outer-box.
1425 ast::VariantData::Struct(..) => {
1426 self.print_where_clause(&generics.where_clause);
1429 self.hardbreak_if_not_bol();
1431 for field in struct_def.fields() {
1432 self.hardbreak_if_not_bol();
1433 self.maybe_print_comment(field.span.lo());
1434 self.print_outer_attributes(&field.attrs);
1435 self.print_visibility(&field.vis);
1436 self.print_ident(field.ident.unwrap());
1437 self.word_nbsp(":");
1438 self.print_type(&field.ty);
1447 crate fn print_variant(&mut self, v: &ast::Variant) {
1449 self.print_visibility(&v.vis);
1450 let generics = ast::Generics::default();
1451 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1455 self.word_space("=");
1456 self.print_expr(&d.value)
1462 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1463 self.ann.pre(self, AnnNode::SubItem(item.id));
1464 self.hardbreak_if_not_bol();
1465 self.maybe_print_comment(item.span.lo());
1466 self.print_outer_attributes(&item.attrs);
1467 self.print_defaultness(item.defaultness);
1469 ast::AssocItemKind::Const(ty, expr) => {
1470 self.print_associated_const(item.ident, ty, expr.as_deref(), &item.vis);
1472 ast::AssocItemKind::Fn(sig, body) => {
1473 let body = body.as_deref();
1474 self.print_fn_full(sig, item.ident, &item.generics, &item.vis, body, &item.attrs);
1476 ast::AssocItemKind::TyAlias(bounds, ty) => {
1477 self.print_associated_type(item.ident, bounds, ty.as_deref());
1479 ast::AssocItemKind::Macro(mac) => {
1480 self.print_mac(mac);
1481 if mac.args.need_semicolon() {
1486 self.ann.post(self, AnnNode::SubItem(item.id))
1489 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1490 self.maybe_print_comment(st.span.lo());
1492 ast::StmtKind::Local(ref loc) => {
1493 self.print_outer_attributes(&loc.attrs);
1494 self.space_if_not_bol();
1495 self.ibox(INDENT_UNIT);
1496 self.word_nbsp("let");
1498 self.ibox(INDENT_UNIT);
1499 self.print_local_decl(loc);
1501 if let Some(ref init) = loc.init {
1503 self.word_space("=");
1504 self.print_expr(init);
1509 ast::StmtKind::Item(ref item) => self.print_item(item),
1510 ast::StmtKind::Expr(ref expr) => {
1511 self.space_if_not_bol();
1512 self.print_expr_outer_attr_style(expr, false);
1513 if classify::expr_requires_semi_to_be_stmt(expr) {
1517 ast::StmtKind::Semi(ref expr) => {
1519 // Filter out empty `Tup` exprs created for the `redundant_semicolon`
1520 // lint, as they shouldn't be visible and interact poorly
1521 // with proc macros.
1522 ast::ExprKind::Tup(ref exprs) if exprs.is_empty() && expr.attrs.is_empty() => {
1526 self.space_if_not_bol();
1527 self.print_expr_outer_attr_style(expr, false);
1532 ast::StmtKind::Mac(ref mac) => {
1533 let (ref mac, style, ref attrs) = **mac;
1534 self.space_if_not_bol();
1535 self.print_outer_attributes(attrs);
1536 self.print_mac(mac);
1537 if style == ast::MacStmtStyle::Semicolon {
1542 self.maybe_print_trailing_comment(st.span, None)
1545 crate fn print_block(&mut self, blk: &ast::Block) {
1546 self.print_block_with_attrs(blk, &[])
1549 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1550 self.print_block_maybe_unclosed(blk, &[], false)
1553 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1554 self.print_block_maybe_unclosed(blk, attrs, true)
1557 crate fn print_block_maybe_unclosed(
1560 attrs: &[ast::Attribute],
1564 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1565 BlockCheckMode::Default => (),
1567 self.maybe_print_comment(blk.span.lo());
1568 self.ann.pre(self, AnnNode::Block(blk));
1571 self.print_inner_attributes(attrs);
1573 for (i, st) in blk.stmts.iter().enumerate() {
1575 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1576 self.maybe_print_comment(st.span.lo());
1577 self.space_if_not_bol();
1578 self.print_expr_outer_attr_style(expr, false);
1579 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1581 _ => self.print_stmt(st),
1585 self.bclose_maybe_open(blk.span, close_box);
1586 self.ann.post(self, AnnNode::Block(blk))
1589 /// Print a `let pat = scrutinee` expression.
1590 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1591 self.s.word("let ");
1593 self.print_pat(pat);
1596 self.word_space("=");
1597 self.print_expr_cond_paren(
1599 Self::cond_needs_par(scrutinee)
1600 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1604 fn print_else(&mut self, els: Option<&ast::Expr>) {
1605 if let Some(_else) = els {
1607 // Another `else if` block.
1608 ast::ExprKind::If(ref i, ref then, ref e) => {
1609 self.cbox(INDENT_UNIT - 1);
1611 self.s.word(" else if ");
1612 self.print_expr_as_cond(i);
1614 self.print_block(then);
1615 self.print_else(e.as_deref())
1617 // Final `else` block.
1618 ast::ExprKind::Block(ref b, _) => {
1619 self.cbox(INDENT_UNIT - 1);
1621 self.s.word(" else ");
1624 // Constraints would be great here!
1626 panic!("print_if saw if with weird alternative");
1632 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1635 self.print_expr_as_cond(test);
1638 self.print_block(blk);
1639 self.print_else(elseopt)
1642 crate fn print_mac(&mut self, m: &ast::Mac) {
1643 self.print_mac_common(
1644 Some(MacHeader::Path(&m.path)),
1648 m.args.inner_tokens(),
1654 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1656 self.commasep_exprs(Inconsistent, args);
1660 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1661 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1664 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1665 /// `if cond { ... }`.
1666 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1667 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1670 /// Does `expr` need parenthesis when printed in a condition position?
1671 fn cond_needs_par(expr: &ast::Expr) -> bool {
1673 // These cases need parens due to the parse error observed in #26461: `if return {}`
1674 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1675 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1677 _ => parser::contains_exterior_struct_lit(expr),
1681 /// Prints `expr` or `(expr)` when `needs_par` holds.
1682 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1686 self.print_expr(expr);
1692 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1693 self.ibox(INDENT_UNIT);
1695 self.print_inner_attributes_inline(attrs);
1696 self.commasep_exprs(Inconsistent, &exprs[..]);
1701 fn print_expr_repeat(
1703 element: &ast::Expr,
1704 count: &ast::AnonConst,
1705 attrs: &[Attribute],
1707 self.ibox(INDENT_UNIT);
1709 self.print_inner_attributes_inline(attrs);
1710 self.print_expr(element);
1711 self.word_space(";");
1712 self.print_expr(&count.value);
1717 fn print_expr_struct(
1720 fields: &[ast::Field],
1721 wth: &Option<P<ast::Expr>>,
1722 attrs: &[Attribute],
1724 self.print_path(path, true, 0);
1726 self.print_inner_attributes_inline(attrs);
1731 s.print_outer_attributes(&field.attrs);
1732 s.ibox(INDENT_UNIT);
1733 if !field.is_shorthand {
1734 s.print_ident(field.ident);
1737 s.print_expr(&field.expr);
1744 self.ibox(INDENT_UNIT);
1745 if !fields.is_empty() {
1750 self.print_expr(expr);
1754 if !fields.is_empty() {
1762 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1764 self.print_inner_attributes_inline(attrs);
1765 self.commasep_exprs(Inconsistent, &exprs[..]);
1766 if exprs.len() == 1 {
1772 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1773 let prec = match func.kind {
1774 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1775 _ => parser::PREC_POSTFIX,
1778 self.print_expr_maybe_paren(func, prec);
1779 self.print_call_post(args)
1782 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1783 let base_args = &args[1..];
1784 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1786 self.print_ident(segment.ident);
1787 if let Some(ref args) = segment.args {
1788 self.print_generic_args(args, true);
1790 self.print_call_post(base_args)
1793 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1794 let assoc_op = AssocOp::from_ast_binop(op.node);
1795 let prec = assoc_op.precedence() as i8;
1796 let fixity = assoc_op.fixity();
1798 let (left_prec, right_prec) = match fixity {
1799 Fixity::Left => (prec, prec + 1),
1800 Fixity::Right => (prec + 1, prec),
1801 Fixity::None => (prec + 1, prec + 1),
1804 let left_prec = match (&lhs.kind, op.node) {
1805 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1806 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1807 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1808 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt)
1809 | (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1810 // We are given `(let _ = a) OP b`.
1812 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1813 // as the parser will interpret this as `(let _ = a) OP b`.
1815 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1816 // parens are required since the parser would interpret `let a = b < c` as
1817 // `let a = (b < c)`. To achieve this, we force parens.
1818 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1819 parser::PREC_FORCE_PAREN
1824 self.print_expr_maybe_paren(lhs, left_prec);
1826 self.word_space(op.node.to_string());
1827 self.print_expr_maybe_paren(rhs, right_prec)
1830 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1831 self.s.word(ast::UnOp::to_string(op));
1832 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1835 fn print_expr_addr_of(
1837 kind: ast::BorrowKind,
1838 mutability: ast::Mutability,
1843 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1844 ast::BorrowKind::Raw => {
1845 self.word_nbsp("raw");
1846 self.print_mutability(mutability, true);
1849 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1852 pub fn print_expr(&mut self, expr: &ast::Expr) {
1853 self.print_expr_outer_attr_style(expr, true)
1856 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1857 self.maybe_print_comment(expr.span.lo());
1859 let attrs = &expr.attrs;
1861 self.print_outer_attributes_inline(attrs);
1863 self.print_outer_attributes(attrs);
1866 self.ibox(INDENT_UNIT);
1867 self.ann.pre(self, AnnNode::Expr(expr));
1869 ast::ExprKind::Box(ref expr) => {
1870 self.word_space("box");
1871 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1873 ast::ExprKind::Array(ref exprs) => {
1874 self.print_expr_vec(&exprs[..], attrs);
1876 ast::ExprKind::Repeat(ref element, ref count) => {
1877 self.print_expr_repeat(element, count, attrs);
1879 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1880 self.print_expr_struct(path, &fields[..], wth, attrs);
1882 ast::ExprKind::Tup(ref exprs) => {
1883 self.print_expr_tup(&exprs[..], attrs);
1885 ast::ExprKind::Call(ref func, ref args) => {
1886 self.print_expr_call(func, &args[..]);
1888 ast::ExprKind::MethodCall(ref segment, ref args) => {
1889 self.print_expr_method_call(segment, &args[..]);
1891 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1892 self.print_expr_binary(op, lhs, rhs);
1894 ast::ExprKind::Unary(op, ref expr) => {
1895 self.print_expr_unary(op, expr);
1897 ast::ExprKind::AddrOf(k, m, ref expr) => {
1898 self.print_expr_addr_of(k, m, expr);
1900 ast::ExprKind::Lit(ref lit) => {
1901 self.print_literal(lit);
1903 ast::ExprKind::Cast(ref expr, ref ty) => {
1904 let prec = AssocOp::As.precedence() as i8;
1905 self.print_expr_maybe_paren(expr, prec);
1907 self.word_space("as");
1908 self.print_type(ty);
1910 ast::ExprKind::Type(ref expr, ref ty) => {
1911 let prec = AssocOp::Colon.precedence() as i8;
1912 self.print_expr_maybe_paren(expr, prec);
1913 self.word_space(":");
1914 self.print_type(ty);
1916 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1917 self.print_let(pat, scrutinee);
1919 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1920 self.print_if(test, blk, elseopt.as_deref())
1922 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1923 if let Some(label) = opt_label {
1924 self.print_ident(label.ident);
1925 self.word_space(":");
1928 self.print_expr_as_cond(test);
1930 self.print_block_with_attrs(blk, attrs);
1932 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1933 if let Some(label) = opt_label {
1934 self.print_ident(label.ident);
1935 self.word_space(":");
1938 self.print_pat(pat);
1940 self.word_space("in");
1941 self.print_expr_as_cond(iter);
1943 self.print_block_with_attrs(blk, attrs);
1945 ast::ExprKind::Loop(ref blk, opt_label) => {
1946 if let Some(label) = opt_label {
1947 self.print_ident(label.ident);
1948 self.word_space(":");
1952 self.print_block_with_attrs(blk, attrs);
1954 ast::ExprKind::Match(ref expr, ref arms) => {
1955 self.cbox(INDENT_UNIT);
1956 self.ibox(INDENT_UNIT);
1957 self.word_nbsp("match");
1958 self.print_expr_as_cond(expr);
1961 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1963 self.print_arm(arm);
1965 self.bclose(expr.span);
1967 ast::ExprKind::Closure(
1975 self.print_movability(movability);
1976 self.print_asyncness(asyncness);
1977 self.print_capture_clause(capture_clause);
1979 self.print_fn_params_and_ret(decl, true);
1981 self.print_expr(body);
1982 self.end(); // need to close a box
1984 // a box will be closed by print_expr, but we didn't want an overall
1985 // wrapper so we closed the corresponding opening. so create an
1986 // empty box to satisfy the close.
1989 ast::ExprKind::Block(ref blk, opt_label) => {
1990 if let Some(label) = opt_label {
1991 self.print_ident(label.ident);
1992 self.word_space(":");
1994 // containing cbox, will be closed by print-block at }
1995 self.cbox(INDENT_UNIT);
1996 // head-box, will be closed by print-block after {
1998 self.print_block_with_attrs(blk, attrs);
2000 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2001 self.word_nbsp("async");
2002 self.print_capture_clause(capture_clause);
2004 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2005 self.cbox(INDENT_UNIT);
2007 self.print_block_with_attrs(blk, attrs);
2009 ast::ExprKind::Await(ref expr) => {
2010 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2011 self.s.word(".await");
2013 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2014 let prec = AssocOp::Assign.precedence() as i8;
2015 self.print_expr_maybe_paren(lhs, prec + 1);
2017 self.word_space("=");
2018 self.print_expr_maybe_paren(rhs, prec);
2020 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2021 let prec = AssocOp::Assign.precedence() as i8;
2022 self.print_expr_maybe_paren(lhs, prec + 1);
2024 self.s.word(op.node.to_string());
2025 self.word_space("=");
2026 self.print_expr_maybe_paren(rhs, prec);
2028 ast::ExprKind::Field(ref expr, ident) => {
2029 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2031 self.print_ident(ident);
2033 ast::ExprKind::Index(ref expr, ref index) => {
2034 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2036 self.print_expr(index);
2039 ast::ExprKind::Range(ref start, ref end, limits) => {
2040 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2041 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2042 // Here we use a fake precedence value so that any child with lower precedence than
2043 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2044 let fake_prec = AssocOp::LOr.precedence() as i8;
2045 if let Some(ref e) = *start {
2046 self.print_expr_maybe_paren(e, fake_prec);
2048 if limits == ast::RangeLimits::HalfOpen {
2053 if let Some(ref e) = *end {
2054 self.print_expr_maybe_paren(e, fake_prec);
2057 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2058 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2059 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2060 self.s.word("break");
2062 if let Some(label) = opt_label {
2063 self.print_ident(label.ident);
2066 if let Some(ref expr) = *opt_expr {
2067 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2071 ast::ExprKind::Continue(opt_label) => {
2072 self.s.word("continue");
2074 if let Some(label) = opt_label {
2075 self.print_ident(label.ident);
2079 ast::ExprKind::Ret(ref result) => {
2080 self.s.word("return");
2081 if let Some(ref expr) = *result {
2083 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2086 ast::ExprKind::InlineAsm(ref a) => {
2087 self.s.word("asm!");
2089 self.print_string(&a.asm.as_str(), a.asm_str_style);
2090 self.word_space(":");
2092 self.commasep(Inconsistent, &a.outputs, |s, out| {
2093 let constraint = out.constraint.as_str();
2094 let mut ch = constraint.chars();
2096 Some('=') if out.is_rw => {
2097 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2099 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2102 s.print_expr(&out.expr);
2106 self.word_space(":");
2108 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2109 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2115 self.word_space(":");
2117 self.commasep(Inconsistent, &a.clobbers, |s, co| {
2118 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2121 let mut options = vec![];
2123 options.push("volatile");
2126 options.push("alignstack");
2128 if a.dialect == ast::AsmDialect::Intel {
2129 options.push("intel");
2132 if !options.is_empty() {
2134 self.word_space(":");
2135 self.commasep(Inconsistent, &options, |s, &co| {
2136 s.print_string(co, ast::StrStyle::Cooked);
2142 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2143 ast::ExprKind::Paren(ref e) => {
2145 self.print_inner_attributes_inline(attrs);
2149 ast::ExprKind::Yield(ref e) => {
2150 self.s.word("yield");
2154 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2159 ast::ExprKind::Try(ref e) => {
2160 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2163 ast::ExprKind::TryBlock(ref blk) => {
2166 self.print_block_with_attrs(blk, attrs)
2168 ast::ExprKind::Err => {
2170 self.s.word("/*ERROR*/");
2174 self.ann.post(self, AnnNode::Expr(expr));
2178 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2179 self.print_pat(&loc.pat);
2180 if let Some(ref ty) = loc.ty {
2181 self.word_space(":");
2182 self.print_type(ty);
2186 pub fn print_usize(&mut self, i: usize) {
2187 self.s.word(i.to_string())
2190 crate fn print_name(&mut self, name: ast::Name) {
2191 self.s.word(name.to_string());
2192 self.ann.post(self, AnnNode::Name(&name))
2195 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2197 self.print_type(&qself.ty);
2198 if qself.position > 0 {
2200 self.word_space("as");
2201 let depth = path.segments.len() - qself.position;
2202 self.print_path(path, false, depth);
2206 let item_segment = path.segments.last().unwrap();
2207 self.print_ident(item_segment.ident);
2208 match item_segment.args {
2209 Some(ref args) => self.print_generic_args(args, colons_before_params),
2214 crate fn print_pat(&mut self, pat: &ast::Pat) {
2215 self.maybe_print_comment(pat.span.lo());
2216 self.ann.pre(self, AnnNode::Pat(pat));
2217 /* Pat isn't normalized, but the beauty of it
2218 is that it doesn't matter */
2220 PatKind::Wild => self.s.word("_"),
2221 PatKind::Ident(binding_mode, ident, ref sub) => {
2222 match binding_mode {
2223 ast::BindingMode::ByRef(mutbl) => {
2224 self.word_nbsp("ref");
2225 self.print_mutability(mutbl, false);
2227 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2228 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2229 self.word_nbsp("mut");
2232 self.print_ident(ident);
2233 if let Some(ref p) = *sub {
2235 self.s.word_space("@");
2239 PatKind::TupleStruct(ref path, ref elts) => {
2240 self.print_path(path, true, 0);
2242 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2245 PatKind::Or(ref pats) => {
2246 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2248 PatKind::Path(None, ref path) => {
2249 self.print_path(path, true, 0);
2251 PatKind::Path(Some(ref qself), ref path) => {
2252 self.print_qpath(path, qself, false);
2254 PatKind::Struct(ref path, ref fields, etc) => {
2255 self.print_path(path, true, 0);
2257 self.word_space("{");
2262 s.cbox(INDENT_UNIT);
2263 if !f.is_shorthand {
2264 s.print_ident(f.ident);
2267 s.print_pat(&f.pat);
2273 if !fields.is_empty() {
2274 self.word_space(",");
2281 PatKind::Tuple(ref elts) => {
2283 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2284 if elts.len() == 1 {
2289 PatKind::Box(ref inner) => {
2290 self.s.word("box ");
2291 self.print_pat(inner);
2293 PatKind::Ref(ref inner, mutbl) => {
2295 if mutbl == ast::Mutability::Mut {
2296 self.s.word("mut ");
2298 self.print_pat(inner);
2300 PatKind::Lit(ref e) => self.print_expr(&**e),
2301 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2302 if let Some(e) = begin {
2307 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2308 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2309 RangeEnd::Excluded => self.s.word(".."),
2311 if let Some(e) = end {
2315 PatKind::Slice(ref elts) => {
2317 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2320 PatKind::Rest => self.s.word(".."),
2321 PatKind::Paren(ref inner) => {
2323 self.print_pat(inner);
2326 PatKind::Mac(ref m) => self.print_mac(m),
2328 self.ann.post(self, AnnNode::Pat(pat))
2331 fn print_arm(&mut self, arm: &ast::Arm) {
2332 // Note, I have no idea why this check is necessary, but here it is.
2333 if arm.attrs.is_empty() {
2336 self.cbox(INDENT_UNIT);
2338 self.maybe_print_comment(arm.pat.span.lo());
2339 self.print_outer_attributes(&arm.attrs);
2340 self.print_pat(&arm.pat);
2342 if let Some(ref e) = arm.guard {
2343 self.word_space("if");
2347 self.word_space("=>");
2349 match arm.body.kind {
2350 ast::ExprKind::Block(ref blk, opt_label) => {
2351 if let Some(label) = opt_label {
2352 self.print_ident(label.ident);
2353 self.word_space(":");
2356 // The block will close the pattern's ibox.
2357 self.print_block_unclosed_indent(blk);
2359 // If it is a user-provided unsafe block, print a comma after it.
2360 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2365 self.end(); // Close the ibox for the pattern.
2366 self.print_expr(&arm.body);
2370 self.end(); // Close enclosing cbox.
2373 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2374 match explicit_self.node {
2375 SelfKind::Value(m) => {
2376 self.print_mutability(m, false);
2379 SelfKind::Region(ref lt, m) => {
2381 self.print_opt_lifetime(lt);
2382 self.print_mutability(m, false);
2385 SelfKind::Explicit(ref typ, m) => {
2386 self.print_mutability(m, false);
2387 self.s.word("self");
2388 self.word_space(":");
2389 self.print_type(typ)
2398 generics: &ast::Generics,
2399 vis: &ast::Visibility,
2400 body: Option<&ast::Block>,
2401 attrs: &[ast::Attribute],
2406 self.print_fn(&sig.decl, sig.header, Some(name), generics, vis);
2407 if let Some(body) = body {
2409 self.print_block_with_attrs(body, attrs);
2418 header: ast::FnHeader,
2419 name: Option<ast::Ident>,
2420 generics: &ast::Generics,
2421 vis: &ast::Visibility,
2423 self.print_fn_header_info(header, vis);
2425 if let Some(name) = name {
2427 self.print_ident(name);
2429 self.print_generic_params(&generics.params);
2430 self.print_fn_params_and_ret(decl, false);
2431 self.print_where_clause(&generics.where_clause)
2434 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2435 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2437 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2439 self.print_fn_ret_ty(&decl.output)
2442 crate fn print_movability(&mut self, movability: ast::Movability) {
2444 ast::Movability::Static => self.word_space("static"),
2445 ast::Movability::Movable => {}
2449 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2450 if asyncness.is_async() {
2451 self.word_nbsp("async");
2455 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2456 match capture_clause {
2457 ast::CaptureBy::Value => self.word_space("move"),
2458 ast::CaptureBy::Ref => {}
2462 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2463 if !bounds.is_empty() {
2464 self.s.word(prefix);
2465 let mut first = true;
2466 for bound in bounds {
2467 if !(first && prefix.is_empty()) {
2473 self.word_space("+");
2477 GenericBound::Trait(tref, modifier) => {
2478 if modifier == &TraitBoundModifier::Maybe {
2481 self.print_poly_trait_ref(tref);
2483 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2489 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2490 self.print_name(lifetime.ident.name)
2493 crate fn print_lifetime_bounds(
2495 lifetime: ast::Lifetime,
2496 bounds: &ast::GenericBounds,
2498 self.print_lifetime(lifetime);
2499 if !bounds.is_empty() {
2501 for (i, bound) in bounds.iter().enumerate() {
2506 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2513 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2514 if generic_params.is_empty() {
2520 self.commasep(Inconsistent, &generic_params, |s, param| {
2521 s.print_outer_attributes_inline(¶m.attrs);
2524 ast::GenericParamKind::Lifetime => {
2525 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2526 s.print_lifetime_bounds(lt, ¶m.bounds)
2528 ast::GenericParamKind::Type { ref default } => {
2529 s.print_ident(param.ident);
2530 s.print_type_bounds(":", ¶m.bounds);
2531 if let Some(ref default) = default {
2534 s.print_type(default)
2537 ast::GenericParamKind::Const { ref ty } => {
2538 s.word_space("const");
2539 s.print_ident(param.ident);
2543 s.print_type_bounds(":", ¶m.bounds)
2551 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2552 if where_clause.predicates.is_empty() {
2557 self.word_space("where");
2559 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2561 self.word_space(",");
2565 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2566 ref bound_generic_params,
2571 self.print_formal_generic_params(bound_generic_params);
2572 self.print_type(bounded_ty);
2573 self.print_type_bounds(":", bounds);
2575 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2580 self.print_lifetime_bounds(*lifetime, bounds);
2582 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2587 self.print_type(lhs_ty);
2589 self.word_space("=");
2590 self.print_type(rhs_ty);
2596 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2598 ast::UseTreeKind::Simple(rename, ..) => {
2599 self.print_path(&tree.prefix, false, 0);
2600 if let Some(rename) = rename {
2602 self.word_space("as");
2603 self.print_ident(rename);
2606 ast::UseTreeKind::Glob => {
2607 if !tree.prefix.segments.is_empty() {
2608 self.print_path(&tree.prefix, false, 0);
2613 ast::UseTreeKind::Nested(ref items) => {
2614 if tree.prefix.segments.is_empty() {
2617 self.print_path(&tree.prefix, false, 0);
2620 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2621 this.print_use_tree(tree)
2628 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2630 ast::Mutability::Mut => self.word_nbsp("mut"),
2631 ast::Mutability::Not => {
2633 self.word_nbsp("const");
2639 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2640 self.print_mutability(mt.mutbl, print_const);
2641 self.print_type(&mt.ty)
2644 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2645 self.ibox(INDENT_UNIT);
2647 self.print_outer_attributes_inline(&input.attrs);
2649 match input.ty.kind {
2650 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2652 if let Some(eself) = input.to_self() {
2653 self.print_explicit_self(&eself);
2655 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2656 ident.name == kw::Invalid
2661 self.print_pat(&input.pat);
2665 self.print_type(&input.ty);
2672 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FunctionRetTy) {
2673 if let ast::FunctionRetTy::Ty(ty) = fn_ret_ty {
2674 self.space_if_not_bol();
2675 self.ibox(INDENT_UNIT);
2676 self.word_space("->");
2677 self.print_type(ty);
2679 self.maybe_print_comment(ty.span.lo());
2683 crate fn print_ty_fn(
2686 unsafety: ast::Unsafety,
2688 name: Option<ast::Ident>,
2689 generic_params: &[ast::GenericParam],
2691 self.ibox(INDENT_UNIT);
2692 if !generic_params.is_empty() {
2694 self.print_generic_params(generic_params);
2696 let generics = ast::Generics {
2698 where_clause: ast::WhereClause { predicates: Vec::new(), span: rustc_span::DUMMY_SP },
2699 span: rustc_span::DUMMY_SP,
2701 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2702 let vis = dummy_spanned(ast::VisibilityKind::Inherited);
2703 self.print_fn(decl, header, name, &generics, &vis);
2707 crate fn maybe_print_trailing_comment(
2709 span: rustc_span::Span,
2710 next_pos: Option<BytePos>,
2712 if let Some(cmnts) = self.comments() {
2713 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2714 self.print_comment(&cmnt);
2719 crate fn print_remaining_comments(&mut self) {
2720 // If there aren't any remaining comments, then we need to manually
2721 // make sure there is a line break at the end.
2722 if self.next_comment().is_none() {
2725 while let Some(ref cmnt) = self.next_comment() {
2726 self.print_comment(cmnt);
2730 crate fn print_fn_header_info(&mut self, header: ast::FnHeader, vis: &ast::Visibility) {
2731 self.s.word(visibility_qualified(vis, ""));
2733 match header.constness.node {
2734 ast::Constness::NotConst => {}
2735 ast::Constness::Const => self.word_nbsp("const"),
2738 self.print_asyncness(header.asyncness.node);
2739 self.print_unsafety(header.unsafety);
2742 ast::Extern::None => {}
2743 ast::Extern::Implicit => {
2744 self.word_nbsp("extern");
2746 ast::Extern::Explicit(abi) => {
2747 self.word_nbsp("extern");
2748 self.print_literal(&abi.as_lit());
2756 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2758 ast::Unsafety::Normal => {}
2759 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2763 crate fn print_constness(&mut self, s: ast::Constness) {
2765 ast::Constness::Const => self.word_nbsp("const"),
2766 ast::Constness::NotConst => {}
2770 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2772 ast::IsAuto::Yes => self.word_nbsp("auto"),
2773 ast::IsAuto::No => {}